Programs & Examples On #Xp theme

Python: "TypeError: __str__ returned non-string" but still prints to output?

Just Try this:

def __str__(self):
    return f'Memo={self.memo}, Tag={self.tags}'

Send inline image in email

    MailMessage mail = new MailMessage();
    //set the addresses
    mail.From = new MailAddress("[email protected]");
    mail.To.Add("[email protected]");

    //set the content
    mail.Subject = "Sucessfully Sent the HTML and Content of mail";

    //first we create the Plain Text part
    string plainText = "Non-HTML Plain Text Message for Non-HTML enable mode";
    AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainText, null, "text/plain");
    XmlTextReader reader = new XmlTextReader(@"E:\HTMLPage.htm");
    string[] address = new string[30];
    string finalHtml = "";
    var i = -1;
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { // The node is an element.
            if (reader.AttributeCount <= 1)
            {
                if (reader.Name == "img")
                {
                    finalHtml += "<" + reader.Name;
                    while (reader.MoveToNextAttribute())
                    {
                        if (reader.Name == "src")
                        {
                            i++;
                            address[i] = reader.Value;
                            address[i] = address[i].Remove(0, 8);
                            finalHtml += " " + reader.Name + "=" + "cid:chartlogo" + i.ToString();
                        }
                        else
                        {
                            finalHtml += " " + reader.Name + "='" + reader.Value + "'";
                        }
                    }
                    finalHtml += ">";
                }
                else
                {
                    finalHtml += "<" + reader.Name;
                    while (reader.MoveToNextAttribute())
                    {
                        finalHtml += " " + reader.Name + "='" + reader.Value + "'";
                    }
                    finalHtml += ">";
                }
            }

        }
        else if (reader.NodeType == XmlNodeType.Text)
        { //Display the text in each element.
            finalHtml += reader.Value;
        }
        else if (reader.NodeType == XmlNodeType.EndElement)
        {
            //Display the end of the element.
            finalHtml += "</" + reader.Name;
            finalHtml += ">";
        }

    }

    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(finalHtml, null, "text/html");
    LinkedResource[] logo = new LinkedResource[i + 1];
    for (int j = 0; j <= i; j++)
    {
        logo[j] = new LinkedResource(address[j]);
        logo[j].ContentId = "chartlogo" + j;
        htmlView.LinkedResources.Add(logo[j]);
    }
    mail.AlternateViews.Add(plainView);
    mail.AlternateViews.Add(htmlView);
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.Credentials = new NetworkCredential(
        "[email protected]", "Password");
    smtp.EnableSsl = true;
    Console.WriteLine();
    smtp.Send(mail);
}

Call PHP function from Twig template

I am surprised the code answer is not posted already, it's a one liner.

You could just {{ categeory_id | getVariations }}

It's a one-liner:

$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));

How do I convert date/time from 24-hour format to 12-hour AM/PM?

You can use date function to format it by using the code below:

echo date("g:i a", strtotime("13:30:30 UTC"));

output: 1:30 pm

Why is exception.printStackTrace() considered bad practice?

Throwable.printStackTrace() writes the stack trace to System.err PrintStream. The System.err stream and the underlying standard "error" output stream of the JVM process can be redirected by

  • invoking System.setErr() which changes the destination pointed to by System.err.
  • or by redirecting the process' error output stream. The error output stream may be redirected to a file/device
    • whose contents may be ignored by personnel,
    • the file/device may not be capable of log rotation, inferring that a process restart is required to close the open file/device handle, before archiving the existing contents of the file/device.
    • or the file/device actually discards all data written to it, as is the case of /dev/null.

Inferring from the above, invoking Throwable.printStackTrace() constitutes valid (not good/great) exception handling behavior, only

  • if you do not have System.err being reassigned throughout the duration of the application's lifetime,
  • and if you do not require log rotation while the application is running,
  • and if accepted/designed logging practice of the application is to write to System.err (and the JVM's standard error output stream).

In most cases, the above conditions are not satisfied. One may not be aware of other code running in the JVM, and one cannot predict the size of the log file or the runtime duration of the process, and a well designed logging practice would revolve around writing "machine-parseable" log files (a preferable but optional feature in a logger) in a known destination, to aid in support.

Finally, one ought to remember that the output of Throwable.printStackTrace() would definitely get interleaved with other content written to System.err (and possibly even System.out if both are redirected to the same file/device). This is an annoyance (for single-threaded apps) that one must deal with, for the data around exceptions is not easily parseable in such an event. Worse, it is highly likely that a multi-threaded application will produce very confusing logs as Throwable.printStackTrace() is not thread-safe.

There is no synchronization mechanism to synchronize the writing of the stack trace to System.err when multiple threads invoke Throwable.printStackTrace() at the same time. Resolving this actually requires your code to synchronize on the monitor associated with System.err (and also System.out, if the destination file/device is the same), and that is rather heavy price to pay for log file sanity. To take an example, the ConsoleHandler and StreamHandler classes are responsible for appending log records to console, in the logging facility provided by java.util.logging; the actual operation of publishing log records is synchronized - every thread that attempts to publish a log record must also acquire the lock on the monitor associated with the StreamHandler instance. If you wish to have the same guarantee of having non-interleaved log records using System.out/System.err, you must ensure the same - the messages are published to these streams in a serializable manner.

Considering all of the above, and the very restricted scenarios in which Throwable.printStackTrace() is actually useful, it often turns out that invoking it is a bad practice.


Extending the argument in the one of the previous paragraphs, it is also a poor choice to use Throwable.printStackTrace in conjunction with a logger that writes to the console. This is in part, due to the reason that the logger would synchronize on a different monitor, while your application would (possibly, if you don't want interleaved log records) synchronize on a different monitor. The argument also holds good when you use two different loggers that write to the same destination, in your application.

How to use GNU Make on Windows?

As an alternative, if you just want to install make, you can use the chocolatey package manager to install gnu make by using

choco install make -y

This deals with any path issues that you might have.

How to filter a dictionary according to an arbitrary condition function?

points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))

LaTeX source code listing like in professional books

And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.

Try setting fixed-width font with this:

\lstset{basicstyle=\ttfamily}

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

It's time to use jupyterlab

Finally, a much-needed upgrade has come to notebooks. By default, it uses the full width of your window like any other full-fledged native IDE.

All you have to do is:

pip install jupyterlab
# if you use conda
conda install -c conda-forge jupyterlab
# to run 
jupyter lab    # instead of jupyter notebook

Here is a screenshot from blog.Jupyter.org

Set the default value in dropdownlist using jQuery

One line of jQuery does it all!

$("#myCombobox option[text='it\'s me']").attr("selected","selected"); 

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Other solutions didn't work form me, here's mine. It applies only to Xcode 8 when running in Swift 2.3 legacy mode:

Looks like Interface Builder is trying to rename the method that should be hooked up to the button.

Here's a radar with more details.

The solution (workaround) is to manually replace the method parameter name to _:

@IBAction func editPictureTapped(sender: UIButton) {  // not working
    print("Tapped")
}

Change to this:

@IBAction func editPictureTapped(_: UIButton) {     // working OK
    print("Tapped")
}

C++ template constructor

There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:

Foo<int> f = Foo<int>();

The <int> is the template argument list for the type Foo, not for its constructor. There's nowhere for the constructor template's argument list to go.

Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.

Copy output of a JavaScript variable to the clipboard

Nowadays there is a new(ish) API to do this directly. It works on modern browsers and on HTTPS (and localhost) only. Not supported by IE11.

IE11 has its own API.

And the workaround in the accepted answer can be used for unsecure hosts.

function copyToClipboard (text) {
  if (navigator.clipboard) { // default: modern asynchronous API
    return navigator.clipboard.writeText(text);
  } else if (window.clipboardData && window.clipboardData.setData) {     // for IE11
    window.clipboardData.setData('Text', text);
    return Promise.resolve();
  } else {
    // workaround: create dummy input
    const input = h('input', { type: 'text' });
    input.value = text;
    document.body.append(input);
    input.focus();
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }
}

Note: it uses Hyperscript to create the input element (but should be easy to adapt)

There is no need to make the input invisible, as it is added and removed so fast. Also when hidden (even using some clever method) some browsers will detect it and prevent the copy operation.

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

What does the variable $this mean in PHP?

It refers to the instance of the current class, as meder said.

See the PHP Docs. It's explained under the first example.

How to generate class diagram from project in Visual Studio 2013?

Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"

Wait for Angular 2 to load/resolve model before rendering view/template

A nice solution that I've found is to do on UI something like:

<div *ngIf="vendorServicePricing && quantityPricing && service">
 ...Your page...
</div

Only when: vendorServicePricing, quantityPricing and service are loaded the page is rendered.

The requested URL /about was not found on this server

That's not a typical Wordpress rewrite block. This is:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

See http://codex.wordpress.org/Using_Permalinks#Where.27s_my_.htaccess_file.3F

Where's my .htaccess file? WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page. Since the name of the file begins with a dot, the file may not be visible through an FTP client unless you change the preferences of the FTP tool to show all files, including the hidden files. Some hosts (e.g. Godaddy) may not show or allow you to edit .htaccess if you install WordPress through the Godaddy Hosting Connection installation.

Creating and editing (.htaccess) If you do not already have a .htaccess file, create one. If you have shell or ssh access to the server, a simple touch .htaccess command will create the file. If you are using FTP to transfer files, create a file on your local computer, call it 1.htaccess, upload it to the root of your WordPress folder, and then rename it to .htaccess.

You can edit the .htaccess file by FTP, shell, or (possibly) your host's control panel.

The easiest and fastest thing to do it reset your permalinks in Dashboard>>Settings>>Permalinks and make sure .htaccess is writable so WordPress can write the rules itself.

And: are you aware you are calling index.cgi as your default document rather than index.php? That's wrong. Remove index.cgi. Or try removing the whole line, too, because defining a default doc on your server may not be needed.

Get last field using awk substr

Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename

How to check not in array element

I think everything that you need is array_key_exists:

if (!array_key_exists('id', $access_data['Privilege'])) {
                $this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
                return $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
            }

Does C# have extension properties?

No, they don't exist.

I know that the C# team was considering them at one point (or at least Eric Lippert was) - along with extension constructors and operators (those may take a while to get your head around, but are cool...) However, I haven't seen any evidence that they'll be part of C# 4.


EDIT: They didn't appear in C# 5, and as of July 2014 it doesn't look like it's going to be in C# 6 either.

Eric Lippert, the Principal Developer on the C# compiler team at Microsoft thru November 2012, blogged about this in October of 2009:

How to export data from Excel spreadsheet to Sql Server 2008 table

There are several tools which can import Excel to SQL Server.

I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...

I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.

How to remove the character at a given index from a string in C?

Use strcat() to concatenate strings.

But strcat() doesn't allow overlapping so you'd need to create a new string to hold the output.

Animate element to auto height with jQuery

  1. Save the current height:

    var curHeight = $('#first').height();
    
  2. Temporarily switch the height to auto:

    $('#first').css('height', 'auto');
    
  3. Get the auto height:

    var autoHeight = $('#first').height();
    
  4. Switch back to curHeight and animate to autoHeight:

    $('#first').height(curHeight).animate({height: autoHeight}, 1000);
    

And together:

var el = $('#first'),
    curHeight = el.height(),
    autoHeight = el.css('height', 'auto').height();
el.height(curHeight).animate({height: autoHeight}, 1000);

Using 24 hour time in bootstrap timepicker

The below code is correct answer for me.

 $('#datetimepicker6').datetimepicker({
                    format : 'YYYY-MM-DD HH:mm'
                });

Getting the "real" Facebook profile picture URL from graph API

For anyone else looking to get the profile pic in iOS:

I just did this to get the user's Facebook pic:

NSString *profilePicURL = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", fbUserID];

where 'fbUserID' is the Facebook user's profile ID.

This way I can always just call the url in profilePicURL to get the image, and I always get it, no problem. If you've already got the user ID, you don't need any API requests, just stick the ID into the url after facebook.com/.

FYI to anyone looking who needs the fbUserID in iOS:

if (FBSession.activeSession.isOpen) {
    [[FBRequest requestForMe] startWithCompletionHandler:
     ^(FBRequestConnection *connection,
       NSDictionary<FBGraphUser> *user,
       NSError *error) {
         if (!error) {
             self.userName = user.name;
             self.fbUserID = user.id;
         }
     }];
}

You'll need an active FBSession for that to work (see Facebook's docs, and the "Scrumptious" example).

How to use 'cp' command to exclude a specific directory?

The easiest way I found, where you can copy all the files excluding files and folders just by adding their names in the parentheses:

shopt -s extglob
cp -r !(Filename1 | FoldernameX | Filename2) Dest/

How to switch activity without animation in Android?

This is not an example use or an explanation of how to use FLAG_ACTIVITY_NO_ANIMATION, however it does answer how to disable the Activity switching animation, as asked in the question title:

Android, how to disable the 'wipe' effect when starting a new activity?

Why does the Google Play store say my Android app is incompatible with my own device?

I ran into this as well - I did all of my development on a Lenovo IdeaTab A2107A-F and could run development builds on it, and even release signed APKs (installed with adb install) with no issues. Once it was published in Alpha test mode and available on Google Play I received the "incompatible with your device" error message.

It turns out I had placed in my AndroidManifest.xml the following from a tutorial:

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />

Well, the Lenovo IdeaTab A2107A-F doesn't have an autofocusing camera on it (which I learned from http://www.phonearena.com/phones/Lenovo-IdeaTab-A2107_id7611, under Cons: lacks autofocus camera). Regardless of whether I was using that feature, Google Play said no. Once that was removed I rebuilt my APK, uploaded it to Google Play, and sure enough my IdeaTab was now in the compatible devices list.

So, double-check every <uses-feature> and if you've been doing some copy-paste from the web check again. Odds are you requested some feature you aren't even using.

Get installed applications in a system

I used Nicks approach - I needed to check whether the Remote Tools for Visual Studio are installed or not, it seems a bit slow, but in a seperate thread this is fine for me. - here my extended code:

    private bool isRdInstalled() {
        ManagementObjectSearcher p = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
        foreach (ManagementObject program in p.Get()) {
            if (program != null && program.GetPropertyValue("Name") != null && program.GetPropertyValue("Name").ToString().Contains("Microsoft Visual Studio 2012 Remote Debugger")) {
                return true;
            }
            if (program != null && program.GetPropertyValue("Name") != null) {
                Trace.WriteLine(program.GetPropertyValue("Name"));
            }
        }
        return false;
    }

How to copy selected files from Android with adb pull

Pull multiple files using regex:

Create pullFiles.sh:

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"

for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
    file=$(echo -e $file | tr -d "\r\n"); # EOL fix
    adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done

Run it:

Make it executable: chmod +x pullFiles.sh

Run it: ./pullFiles.sh

Notes:

  • as is, won't work when filenames have spaces
  • includes a fix for end-of-line (EOL) on Android, which is a "\r\n"

Sound effects in JavaScript / HTML5

Here's one method for making it possible to play even same sound simultaneously. Combine with preloader, and you're all set. This works with Firefox 17.0.1 at least, haven't tested it with anything else yet.

// collection of sounds that are playing
var playing={};
// collection of sounds
var sounds={step:"knock.ogg",throw:"swing.ogg"};

// function that is used to play sounds
function player(x)
{
    var a,b;
    b=new Date();
    a=x+b.getTime();
    playing[a]=new Audio(sounds[x]);
    // with this we prevent playing-object from becoming a memory-monster:
    playing[a].onended=function(){delete playing[a]};
    playing[a].play();
}

Bind this to a keyboard key, and enjoy:

player("step");

Resizing an image in an HTML5 canvas

I just ran a page of side by sides comparisons and unless something has changed recently, I could see no better downsizing (scaling) using canvas vs. simple css. I tested in FF6 Mac OSX 10.7. Still slightly soft vs. the original.

I did however stumble upon something that did make a huge difference and that was using image filters in browsers that support canvas. You can actually manipulate images much like you can in Photoshop with blur, sharpen, saturation, ripple, grayscale, etc.

I then found an awesome jQuery plug-in which makes application of these filters a snap: http://codecanyon.net/item/jsmanipulate-jquery-image-manipulation-plugin/428234

I simply apply the sharpen filter right after resizing the image which should give you the desired effect. I didn't even have to use a canvas element.

Remove the title bar in Windows Forms

 Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None

Sending data back to the Main Activity in Android

All these answers are explaining the scenario of your second activity needs to be finish after sending the data.

But in case if you don't want to finish the second activity and want to send the data back in to first then for that you can use BroadCastReceiver.

In Second Activity -

Intent intent = new Intent("data");
intent.putExtra("some_data", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

In First Activity-

private BroadcastReceiver tempReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do some action
    }
};

Register the receiver in onCreate()-

 LocalBroadcastManager.getInstance(this).registerReceiver(tempReceiver,new IntentFilter("data"));

Unregister it in onDestroy()

Path.Combine for URLs?

Path.Combine does not work for me because there can be characters like "|" in QueryString arguments and therefore the URL, which will result in an ArgumentException.

I first tried the new Uri(Uri baseUri, string relativeUri) approach, which failed for me because of URIs like http://www.mediawiki.org/wiki/Special:SpecialPages:

new Uri(new Uri("http://www.mediawiki.org/wiki/"), "Special:SpecialPages")

will result in Special:SpecialPages, because of the colon after Special that denotes a scheme.

So I finally had to take mdsharpe/Brian MacKays route and developed it a bit further to work with multiple URI parts:

public static string CombineUri(params string[] uriParts)
{
    string uri = string.Empty;
    if (uriParts != null && uriParts.Length > 0)
    {
        char[] trims = new char[] { '\\', '/' };
        uri = (uriParts[0] ?? string.Empty).TrimEnd(trims);
        for (int i = 1; i < uriParts.Length; i++)
        {
            uri = string.Format("{0}/{1}", uri.TrimEnd(trims), (uriParts[i] ?? string.Empty).TrimStart(trims));
        }
    }
    return uri;
}

Usage: CombineUri("http://www.mediawiki.org/", "wiki", "Special:SpecialPages")

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

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

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

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

...

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

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

You need to set it up to something like this:

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

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

sys.path is initialized from these locations:

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

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

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

man1.py:

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

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

man1test.py

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

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

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

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

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

Creating a DateTime in a specific Time Zone in c#

The DateTimeOffset structure was created for exactly this type of use.

See: http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx

Here's an example of creating a DateTimeOffset object with a specific time zone:

DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Browser scrollbars don't work at all on iPhone/iPad. At work we are using custom JavaScript scrollbars like jScrollPane to provide a consistent cross-browser UI: http://jscrollpane.kelvinluck.com/

It works very well for me - you can make some really beautiful custom scrollbars that fit the design of your site.

JQuery, select first row of table

late in the game , but this worked for me:

$("#container>table>tbody>tr:first").trigger('click');

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')

Get ID of element that called a function

For others unexpectedly getting the Window element, a common pitfall:

<a href="javascript:myfunction(this)">click here</a>

which actually scopes this to the Window object. Instead:

<a href="javascript:nop()" onclick="myfunction(this)">click here</a>

passes the a object as expected. (nop() is just any empty function.)

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

Oleg Cherrs answer led me to a solution. As he mentioned

Go to /.android/avd/ and open config.ini. Find the >image.sysdir.1 property. It points at the directory inside SDK containing system >images. Make sure that this directory exists and contains files like build.prop, >system.img, etc. If it doesn't, then you have to open the SDK Manager and >download system images your AVD requires (see below).

I found the corresponding emulator *.ini file in the avd directory. There I modified the "image.sysdir.1" entry. I replaced the relative with an absolute path (append the ANDROID_SDK_ROOT in front). After that the emulator started from the command line as expected.

Using number as "index" (JSON)

First off, it's not JSON: JSON mandates that all keys must be strings.

Secondly, regular arrays do what you want:

var Game = {
  status: [
    [
      "val",
      "val",
      "val"
    ],
    [
      "val",
      "val",
      "val"
    ]
  }

will work, if you use Game.status[0][0]. You cannot use numbers with the dot notation (.0).

Alternatively, you can quote the numbers (i.e. { "0": "val" }...); you will have plain objects instead of Arrays, but the same syntax will work.

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

jQuery: If this HREF contains

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

How do I get next month date from today's date and insert it in my database?

You can use PHP's strtotime() function:

// One month from today
$date = date('Y-m-d', strtotime('+1 month'));

// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2015-01-01')));

Just note that +1 month is not always calculated intuitively. It appears to always add the number of days that exist in the current month.

Current Date  | +1 month
-----------------------------------------------------
2015-01-01    | 2015-02-01   (+31 days)
2015-01-15    | 2015-02-15   (+31 days)
2015-01-30    | 2015-03-02   (+31 days, skips Feb)
2015-01-31    | 2015-03-03   (+31 days, skips Feb)
2015-02-15    | 2015-03-15   (+28 days)
2015-03-31    | 2015-05-01   (+31 days, skips April)
2015-12-31    | 2016-01-31   (+31 days)

Some other date/time intervals that you can use:

$date = date('Y-m-d'); // Initial date string to use in calculation

$date = date('Y-m-d', strtotime('+1 day', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+2 week', strtotime($date)));
$date = date('Y-m-d', strtotime('+1 month', strtotime($date)));
$date = date('Y-m-d', strtotime('+30 days', strtotime($date)));

Ineligible Devices section appeared in Xcode 6.x.x

Fixed in Xcode version 6.3.1 (6D1002) published April 21, 2015.

At least the problem magically went away for me after installing this Xcode version.

Git submodule update

This GitPro page does summarize the consequence of a git submodule update nicely

When you run git submodule update, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference.
The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes.
If you do an initial submodule update, commit in that submodule directory without creating a branch to work in, and then run git submodule update again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve.


Note March 2013:

As mentioned in "git submodule tracking latest", a submodule now (git1.8.2) can track a branch.

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 
# or (with rebase)
git submodule update --rebase --remote

See "git submodule update --remote vs git pull".

MindTooth's answer illustrate a manual update (without local configuration):

git submodule -q foreach git pull -q origin master

In both cases, that will change the submodules references (the gitlink, a special entry in the parent repo index), and you will need to add, commit and push said references from the main repo.
Next time you will clone that parent repo, it will populate the submodules to reflect those new SHA1 references.

The rest of this answer details the classic submodule feature (reference to a fixed commit, which is the all point behind the notion of a submodule).


To avoid this issue, create a branch when you work in a submodule directory with git checkout -b work or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to.

Switching branches with submodules in them can also be tricky. If you create a new branch, add a submodule there, and then switch back to a branch without that submodule, you still have the submodule directory as an untracked directory:


So, to answer your questions:

can I create branches/modifications and use push/pull just like I would in regular repos, or are there things to be cautious about?

You can create a branch and push modifications.

WARNING (from Git Submodule Tutorial): Always publish (push) the submodule change before publishing (push) the change to the superproject that references it. If you forget to publish the submodule change, others won't be able to clone the repository.

how would I advance the submodule referenced commit from say (tagged) 1.0 to 1.1 (even though the head of the original repo is already at 2.0)

The page "Understanding Submodules" can help

Git submodules are implemented using two moving parts:

  • the .gitmodules file and
  • a special kind of tree object.

These together triangulate a specific revision of a specific repository which is checked out into a specific location in your project.


From the git submodule page

you cannot modify the contents of the submodule from within the main project

100% correct: you cannot modify a submodule, only refer to one of its commits.

This is why, when you do modify a submodule from within the main project, you:

  • need to commit and push within the submodule (to the upstream module), and
  • then go up in your main project, and re-commit (in order for that main project to refer to the new submodule commit you just created and pushed)

A submodule enables you to have a component-based approach development, where the main project only refers to specific commits of other components (here "other Git repositories declared as sub-modules").

A submodule is a marker (commit) to another Git repository which is not bound by the main project development cycle: it (the "other" Git repo) can evolves independently.
It is up to the main project to pick from that other repo whatever commit it needs.

However, should you want to, out of convenience, modify one of those submodules directly from your main project, Git allows you to do that, provided you first publish those submodule modifications to its original Git repo, and then commit your main project refering to a new version of said submodule.

But the main idea remains: referencing specific components which:

  • have their own lifecycle
  • have their own set of tags
  • have their own development

The list of specific commits you are refering to in your main project defines your configuration (this is what Configuration Management is all about, englobing mere Version Control System)

If a component could really be developed at the same time as your main project (because any modification on the main project would involve modifying the sub-directory, and vice-versa), then it would be a "submodule" no more, but a subtree merge (also presented in the question Transferring legacy code base from cvs to distributed repository), linking the history of the two Git repo together.

Does that help understanding the true nature of Git Submodules?

Make scrollbars only visible when a Div is hovered over?

I think something like

$("#leftDiv").mouseover(function(){$(this).css("overflow","scroll");});
$("#leftDiv").mouseout(function(){$(this).css("overflow","hidden");});

Array to Hash Ruby

Enumerator includes Enumerable. Since 2.1, Enumerable also has a method #to_h. That's why, we can write :-

a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}

Because #each_slice without block gives us Enumerator, and as per the above explanation, we can call the #to_h method on the Enumerator object.

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

Order discrete x scale by frequency/value

Hadley has been developing a package called forcats. This package makes the task so much easier. You can exploit fct_infreq() when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars example in this post, you want to reorder levels of cyl by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

If you wanna go the other way around, you can use fct_rev() along with fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

How do you create a dropdownlist from an enum in ASP.NET MVC?

In ASP.NET MVC 5.1, they added the EnumDropDownListFor() helper, so no need for custom extensions:

Model:

public enum MyEnum
{
    [Display(Name = "First Value - desc..")]
    FirstValue,
    [Display(Name = "Second Value - desc...")]
    SecondValue
}

View:

@Html.EnumDropDownListFor(model => model.MyEnum)

Using Tag Helper (ASP.NET MVC 6):

<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">

How can I stop Chrome from going into debug mode?

If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.

I suggest you "Disable all break points":

Enter image description here

Source:

https://javascript.info/debugging-chrome

Click events on Pie Charts in Chart.js

I was facing the same issues since several days, Today i have found the solution. I have shown the complete file which is ready to execute.

<html>
<head><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js">
</script>
</head>
<body>
<canvas id="myChart" width="200" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
    }]
},
options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }]
    },
onClick:function(e){
    var activePoints = myChart.getElementsAtEvent(e);
    var selectedIndex = activePoints[0]._index;
    alert(this.data.datasets[0].data[selectedIndex]);


}
}
});
</script>
</body>
</html>

How to get base url with jquery or javascript?

window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"

almost same as Jenish answer but a little shorter.

Setting Icon for wpf application (VS 08)

You can try this also:

private void Page_Loaded_1(object sender, RoutedEventArgs e)
    {
        Uri iconUri = new Uri(@"C:\Apps\R&D\WPFNavigation\WPFNavigation\Images\airport.ico", UriKind.RelativeOrAbsolute);
        (this.Parent as Window).Icon = BitmapFrame.Create(iconUri);
    }

Detect change to selected date with bootstrap-datepicker

Here is my code for that:

$('#date-daily').datepicker().on('changeDate', function(e) {
    //$('#other-input').val(e.format(0,"dd/mm/yyyy"));
    //alert(e.date);
    //alert(e.format(0,"dd/mm/yyyy"));
    //console.log(e.date); 
});

Just uncomment the one you prefer. The first option changes the value of other input element. The second one alerts the date with datepicker default format. The third one alerts the date with your own custom format. The last option outputs to log (default format date).

It's your choice to use the e.date , e.dates (for múltiple date input) or e.format(...).

here some more info

disable all form elements inside div

    $(document).ready(function () {
        $('#chkDisableEnableElements').change(function () {
            if ($('#chkDisableEnableElements').is(':checked')) {
                enableElements($('#divDifferentElements').children());
            }
            else {
                disableElements($('#divDifferentElements').children());
            }
        });
    });

    function disableElements(el) {
        for (var i = 0; i < el.length; i++) {
            el[i].disabled = true;

            disableElements(el[i].children);
        }
    }

    function enableElements(el) {
        for (var i = 0; i < el.length; i++) {
            el[i].disabled = false;

            enableElements(el[i].children);
        }
    }

Does Python have an argc argument?

I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:

[filename] = sys.argv[1:]

in_file = open(filename)   # Don't need the "r"

This will assign the one argument to filename and raise an exception if there isn't exactly one argument.

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Increasing nesting function calls limit

Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.

Output errors and see where this is being triggered.

Converting xml to string using C#

   public string GetXMLAsString(XmlDocument myxml)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
               myxml.WriteTo(xmlTextWriter);
               return stringWriter.ToString();
            }

        }    
}

Could not reserve enough space for object heap

Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:

Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M

How to remove all null elements from a ArrayList or String Array?

The Objects class has a nonNull Predicate that can be used with filter.

For example:

tourists.stream().filter(Objects::nonNull).collect(Collectors.toList());

PostgreSQL: how to convert from Unix epoch to date?

On Postgres 10:

SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

How can I find all *.js file in directory recursively in Linux?

find /abs/path/ -name '*.js'

Edit: As Brian points out, add -type f if you want only plain files, and not directories, links, etc.

Initialising an array of fixed size in python

Well I would like to help you by posting a sample program and its output

Program:

t = input("")
x = [None]*t
y = [[None]*t]*t

for i in range(1, t+1):
    x[i-1] = i;

    for j in range(1, t+1):
        y[i-1][j-1] = j;

print x
print y

Output :-

2
[1, 2]
[[1, 2], [1, 2]]

I hope this clears some very basic concept of yours regarding their declaration. To initialize them with some other specific values, like initializing them with 0.. you can declare them as:

x = [0]*10

Hope it helps..!! ;)

How to solve npm install throwing fsevents warning on non-MAC OS?

I got the same error. In my case, I was using a mapped drive to edit code off of a second computer, that computer was running linux. Not sure exactly why gulp-watch relies on operating system compatibility prior to install (I would assume it has to do with security purposes). Essentially the error is checking against your operating system and the operating system calling the node module, in my case the two operating systems were not the same so it threw it error. Which from the looks of your error is the same as mine.

The Error

Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

How I fixed it?

I logged into the linux computer directly and ran

npm install --save-dev <module-name>

Then went back into my coding environment and everything was fine after that.

Hope that helps!

How can I get the count of milliseconds since midnight for the current?

I tried a few ones above but they seem to reset @ 1000

This one definately works, and should also take year into consideration

long millisStart = Calendar.getInstance().getTimeInMillis();

and then do the same for end time if needed.

How can I find non-ASCII characters in MySQL?

One missing character from everyone's examples above is the termination character (\0). This is invisible to the MySQL console output and is not discoverable by any of the queries heretofore mentioned. The query to find it is simply:

select * from TABLE where COLUMN like '%\0%';

bootstrap 4 file input doesn't show the file name

If you want you can use the recommended Bootstrap plugin to dynamize your custom file input: https://www.npmjs.com/package/bs-custom-file-input

This plugin can be use with or without jQuery and works with React an Angular

Getting a slice of keys from a map

Visit https://play.golang.org/p/dx6PTtuBXQW

package main

import (
    "fmt"
    "sort"
)

func main() {
    mapEg := map[string]string{"c":"a","a":"c","b":"b"}
    keys := make([]string, 0, len(mapEg))
    for k := range mapEg {
        keys = append(keys, k)
    }
    sort.Strings(keys)
    fmt.Println(keys)
}

LaTeX beamer: way to change the bullet indentation?

I use the package enumitem. You may then set such margins when you declare your lists (enumerate, description, itemize):

\begin{itemize}[leftmargin=0cm]
    \item Foo
    \item Bar
\end{itemize}

Naturally, the package provides lots of other nice customizations for lists (use 'label=' to change the bullet, use 'itemsep=' to change the spacing between items, etc...)

Why are Python's 'private' methods not actually private?

From http://www.faqs.org/docs/diveintopython/fileinfo_private.html

Strictly speaking, private methods are accessible outside their class, just not easily accessible. Nothing in Python is truly private; internally, the names of private methods and attributes are mangled and unmangled on the fly to make them seem inaccessible by their given names. You can access the __parse method of the MP3FileInfo class by the name _MP3FileInfo__parse. Acknowledge that this is interesting, then promise to never, ever do it in real code. Private methods are private for a reason, but like many other things in Python, their privateness is ultimately a matter of convention, not force.

How to detect escape key press with pure JS or jQuery?

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Your Button2Click and Button3Click functions pass klad.xls and smimime.txt. These files most likely aren't actual executables indeed.

In order to open arbitrary files using the application associated with them, use ShellExecute

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

  1. Please check current version of your Kotlin in below path,

    C:\Program Files\Android\Android Studio\gradle\m2repository\org\jetbrains\kotlin\kotlin-stdlib\1.0.5

change to that version (1.0.5) in project level gradle file.

You can see in your above path does not mentioned any Java - jre version, so remove in your app level gradle file as below,

compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

How to serialize a JObject without the formatting?

You can also do the following;

string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Whilst you certainly can use MySQL's IF() control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE expression instead:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
         ELSE A
       END
WHERE  A IS NOT NULL

Of course, in this specific example it's a little wasteful to set A to itself in the ELSE clause—better entirely to filter such conditions from the UPDATE, via the WHERE clause:

UPDATE Table
SET    A = CASE
         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
       END
WHERE  (A > 0 AND A < 1) OR (A > 1 AND A < 2)

(The inequalities entail A IS NOT NULL).

Or, if you want the intervals to be closed rather than open (note that this would set values of 0 to 1—if that is undesirable, one could explicitly filter such cases in the WHERE clause, or else add a higher precedence WHEN condition):

UPDATE Table
SET    A = CASE
         WHEN A BETWEEN 0 AND 1 THEN 1
         WHEN A BETWEEN 1 AND 2 THEN 2
       END
WHERE  A BETWEEN 0 AND 2

Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL() instead:

UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2

Is it possible to change the package name of an Android app on Google Play?

Complete guide : https://developer.android.com/studio/build/application-id.html

As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html

We can say that:

  • If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.

  • If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.

As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en

Update your apps

Prepare your APK

When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.

Use the following checklist to make sure your new APK is ready to update your existing users:

  • The package name of the updated APK needs to be the same as the current version.
  • The version code needs to be greater than that current version. Learn more about versioning your applications.
  • The updated APK needs to be signed with the same signature as the current version.

To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:

$ jarsigner -verify -verbose -certs my_application.apk

If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.

Learn more about signing your applications

Upload your APK Once your APK is ready, you can create a new release.

Where does SVN client store user authentication data?

I know I'm uprising a very old topic, but after a couple of hours struggling with this very problem and not finding a solution anywhere else, I think this is a good place to put an answer.

We have some Build Servers WindowsXP based and found this very problem: svn command line client is not caching auth credentials.

We finally found out that we are using Cygwin's svn client! not a "native" Windows. So... this client stores all the auth credentials in /home/<user>/.subversion/auth

This /home directory in Cygwin, in our installation is in c:\cygwin\home. AND: the problem was that the Windows user that is running svn did never ever "logged in" in Cygwin, and so there was no /home/<user> directory.

A simple "bash -ls" from a Windows command terminal created the directory, and after the first access to our SVN server with interactive prompting for access credentials, alás, they got cached.

So if you are using Cygwin's svn client, be sure to have a "home" directory created for the local Windows user.

SQL WHERE ID IN (id1, id2, ..., idn)

Doing the SELECT * FROM MyTable where id in () command on an Azure SQL table with 500 million records resulted in a wait time of > 7min!

Doing this instead returned results immediately:

select b.id, a.* from MyTable a
join (values (250000), (2500001), (2600000)) as b(id)
ON a.id = b.id

Use a join.

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

How do I add 24 hours to a unix timestamp in php?

Unix timestamp is in seconds, so simply add the corresponding number of seconds to the timestamp:

$timeInFuture = time() + (60 * 60 * 24);

Replacing all non-alphanumeric characters with empty strings

Guava's CharMatcher provides a concise solution:

output = CharMatcher.javaLetterOrDigit().retainFrom(input);

hidden field in php

Yes, you can access it through GET and POST (trying this simple task would have made you aware of that).

Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.

C# Collection was modified; enumeration operation may not execute

The problem is where you are executing:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.

Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.

How to install and use "make" in Windows?

Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".

You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.

SSRS chart does not show all labels on Horizontal axis

image: reporting services line chart horizontal axis properties

To see all dates on the report; Set Axis Type to Scalar, Set Interval to 1 -Jump Labels section Set disable auto-fit set label rotation angle as you desire.

These would help.

GZIPInputStream reading line by line

GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();

Find (and kill) process locking port 3000 on Mac

Easiest solution:

kill $(lsof -ti:3000,3001,8080)

For single port:

kill $(lsof -ti:3000)

#3000 is the port to be freed

Kill multiple ports with single line command:

kill $(lsof -ti:3000,3001)

#here multiple ports 3000 and 3001 are the ports to be freed

lsof -ti:3000

82500 (Process ID)

lsof -ti:3001

82499

lsof -ti:3001,3000

82499 82500

kill $(lsof -ti:3001,3000)

Terminates both 82499 and 82500 processes in a single command.

For using this in package.json scripts:

"scripts": { "start": "kill $(lsof -ti:3000,3001) && npm start" }

How to download all files (but not HTML) from a website using wget?

Try this. It always works for me

wget --mirror -p --convert-links -P ./LOCAL-DIR WEBSITE-URL

Preferred way of loading resources in Java

Well, it partly depends what you want to happen if you're actually in a derived class.

For example, suppose SuperClass is in A.jar and SubClass is in B.jar, and you're executing code in an instance method declared in SuperClass but where this refers to an instance of SubClass. If you use this.getClass().getResource() it will look relative to SubClass, in B.jar. I suspect that's usually not what's required.

Personally I'd probably use Foo.class.getResourceAsStream(name) most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo, that's the most robust way of doing it IMO.

Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.

Detecting attribute change of value of an attribute I made

You would have to watch the DOM node changes. There is an API called MutationObserver, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.

One way you could get around this problem is to have the part of the code that modifies the data-select-content-val attribute dispatch an event that you can listen to.

For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.

The code here is

$(function() {  
  // Here you register for the event and do whatever you need to do.
  $(document).on('data-attribute-changed', function() {
    var data = $('#contains-data').data('mydata');
    alert('Data changed to: ' + data);
  });

  $('#button').click(function() {
    $('#contains-data').data('mydata', 'foo');
    // Whenever you change the attribute you will user the .trigger
    // method. The name of the event is arbitrary
    $(document).trigger('data-attribute-changed');
  });

   $('#getbutton').click(function() {
    var data = $('#contains-data').data('mydata');
    alert('Data is: ' + data);
  });
});

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

The Up Button is usually activated for Low-level Activities. In your manifest I only see the MainActivity. I don't think it makes sense to activate the up button for the main activity. Create an activity, then in the manifest add the parentActivityName attribute. Then activate the up button on the activity's onCreate method.
This should help.
https://developer.android.com/training/appbar/up-action.html

How to declare string constants in JavaScript?

Just declare variable outside of scope of any js function. Such variables will be global.

Make $JAVA_HOME easily changable in Ubuntu

Take a look at bash(1), you need a login shell to pickup the ~/.profile, i.e. the -l option.

ORA-01882: timezone region not found

Update the file oracle/jdbc/defaultConnectionProperties.properties in whatever version of the library (i.e. inside your jar) you are using to contain the line below:

oracle.jdbc.timezoneAsRegion=false

How to make a Python script run like a service or daemon in Linux

You can also make the python script run as a service using a shell script. First create a shell script to run the python script like this (scriptname arbitary name)

#!/bin/sh
script='/home/.. full path to script'
/usr/bin/python $script &

now make a file in /etc/init.d/scriptname

#! /bin/sh

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/home/.. path to shell script scriptname created to run python script
PIDFILE=/var/run/scriptname.pid

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

case "$1" in
  start)
     log_daemon_msg "Starting feedparser"
     start_daemon -p $PIDFILE $DAEMON
     log_end_msg $?
   ;;
  stop)
     log_daemon_msg "Stopping feedparser"
     killproc -p $PIDFILE $DAEMON
     PID=`ps x |grep feed | head -1 | awk '{print $1}'`
     kill -9 $PID       
     log_end_msg $?
   ;;
  force-reload|restart)
     $0 stop
     $0 start
   ;;
  status)
     status_of_proc -p $PIDFILE $DAEMON atd && exit 0 || exit $?
   ;;
 *)
   echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload|status}"
   exit 1
  ;;
esac

exit 0

Now you can start and stop your python script using the command /etc/init.d/scriptname start or stop.

Batch files: How to read a file?

Under NT-style cmd.exe, you can loop through the lines of a text file with

FOR /F %i IN (file.txt) DO @echo %i

Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

String split on new line, tab and some number of spaces

You can use this

string.strip().split(":")

nil detection in Go

The language spec mentions comparison operators' behaviors:

comparison operators

In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.


Assignability

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

  • x's type is identical to T.
  • x's type V and T have identical underlying types and at least one of V or T is not a named type.
  • T is an interface type and x implements T.
  • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
  • x is an untyped constant representable by a value of type T.

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

Adding an identity to an existing column

To modify the identity properties for a column:

  • In Server Explorer, right-click the table with identity properties you want to modify and click Open Table Definition. The table opens in Table Designer.
  • Clear the Allow nulls check box for the column you want to change.
  • In the Column Properties tab, expand the Identity Specification property.
  • Click the grid cell for the Is Identity child property and choose Yes from the drop-down list.
  • Type a value in the Identity Seed cell. This value will be assigned to the first row in the table. The value 1 will be assigned by default.

That's it, and it worked for me

Tainted canvases may not be exported

In my case I was drawing onto a canvas tag from a video. To address the tainted canvas error I had to do two things:

<video id="video_source" crossorigin="anonymous">
    <source src="http://crossdomain.example.com/myfile.mp4">
</video>
  • Ensure Access-Control-Allow-Origin header is set in the video source response (proper setup of crossdomain.example.com)
  • Set the video tag to have crossorigin="anonymous"

How to change font size in Eclipse for Java text editors?

If you are using windows then try with CTRL,SHIFT,+ and for decreasing font size you can use CTRL,SHIFT,-

php_network_getaddresses: getaddrinfo failed: Name or service not known

You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.

If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.

If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:

$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n"); 

That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.

How to get complete current url for Cakephp

I know this post is a little dated, and CakePHP versions have flourished since. In the current (2.1.x) version of CakePHP and even in 1.3.x if I am not mistaken, one can get the current controller/view url like this:

$this->params['url'];

While this method does NOT return the parameters, it is handy if you want to append parameters to a link when building new URL's. For example, we have the current URL:

projects/edit/6

And we want to append a custom parameter action called c_action with a value of remove_image, one could make use of $this->params['url]; and merge it with an array of custom parameter key => value pairs:

echo $this->Html->link('remove image', array_merge($this->params['url'], array('c_action' => 'remove_image'));

Using the above method we are able to append our custom parameters to the link and not cause a long chain on parameters to build up on the URL, because $this->params['url] only ever returns the controll action URL.

In the above example we'd need to manually add the ID of 6 back into the URL, so perahaps the final link build would be like this:

echo $this->Html->link('remove image', array_merge($this->params['url'], array($id,'c_action' => 'remove_image'));

Where $is is a the ID of the project and you would have assigned it to the variable $id at controller level. The new URL will then be:

projects/edit/6/c_action:remove_image

Sorry if this is in the slightest unrelated, but I ran across this question when searching for a method to achieve the above and thought others may benefit from it.

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

TL;DR

For JDK 11 try this:

To handle this problem in a clean way, I suggest to use brew and jenv.

For Java 11 follow this 2 steps, first :

JAVA_VERSION=11
brew reinstall jenv 
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}

And add this at end of your shell config scripts
~/.bashrc or ~/.zshrc

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Problem solved!

Then restart your shell and try to execute java -version

Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).

How to get 2 digit year w/ Javascript?

another version:

var yy = (new Date().getFullYear()+'').slice(-2);

MySql Inner Join with WHERE clause

You are using two WHERE clauses but only one is allowed. Use it like this:

SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
  table1.f_com_id = '430'
  AND table1.f_status = 'Submitted'
  AND table2.f_type = 'InProcess'

How can I set a UITableView to grouped style

I give you my solution, I am working in "XIB mode", here the code of a subclass of a UITableViewController :

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    return self;
}

JavaScript, Node.js: is Array.forEach asynchronous?

Use Promise.each of bluebird library.

Promise.each(
Iterable<any>|Promise<Iterable<any>> input,
function(any item, int index, int length) iterator
) -> Promise

This method iterates over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (value, index, length) where the value is the resolved value of a respective promise in the input array. Iteration happens serially. If the iterator function returns a promise or a thenable, then the result of the promise is awaited before continuing with next iteration. If any promise in the input array is rejected, then the returned promise is rejected as well.

If all of the iterations resolve successfully, Promise.each resolves to the original array unmodified. However, if one iteration rejects or errors, Promise.each ceases execution immediately and does not process any further iterations. The error or rejected value is returned in this case instead of the original array.

This method is meant to be used for side effects.

var fileNames = ["1.txt", "2.txt", "3.txt"];

Promise.each(fileNames, function(fileName) {
    return fs.readFileAsync(fileName).then(function(val){
        // do stuff with 'val' here.  
    });
}).then(function() {
console.log("done");
});

Method to get all files within folder and subfolders that will return a list

private List<String> DirSearch(string sDir)
{
    List<String> files = new List<String>();
    try
    {
        foreach (string f in Directory.GetFiles(sDir))
        {
            files.Add(f);
        }
        foreach (string d in Directory.GetDirectories(sDir))
        {
            files.AddRange(DirSearch(d));
        }
    }
    catch (System.Exception excpt)
    {
        MessageBox.Show(excpt.Message);
    }

    return files;
}

and if you don't want to load the entire list in memory and avoid blocking you may take a look at the following answer.

Difference between __getattr__ vs __getattribute__

In reading through Beazley & Jones PCB, I have stumbled on an explicit and practical use-case for __getattr__ that helps answer the "when" part of the OP's question. From the book:

"The __getattr__() method is kind of like a catch-all for attribute lookup. It's a method that gets called if code tries to access an attribute that doesn't exist." We know this from the above answers, but in PCB recipe 8.15, this functionality is used to implement the delegation design pattern. If Object A has an attribute Object B that implements many methods that Object A wants to delegate to, rather than redefining all of Object B's methods in Object A just to call Object B's methods, define a __getattr__() method as follows:

def __getattr__(self, name):
    return getattr(self._b, name)

where _b is the name of Object A's attribute that is an Object B. When a method defined on Object B is called on Object A, the __getattr__ method will be invoked at the end of the lookup chain. This would make code cleaner as well, since you do not have a list of methods defined just for delegating to another object.

C++ Erase vector element by value rather than by position?

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

2
4
6
8
10
-----
2
4
6
10

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

/**
 * Navbar styling.
 */
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

http://lesscss.org

How can I pass a username/password in the header to a SOAP WCF Service

I got a better method from here: WCF: Creating Custom Headers, How To Add and Consume Those Headers

Client Identifies Itself
The goal here is to have the client provide some sort of information which the server can use to determine who is sending the message. The following C# code will add a header named ClientId:

var cl = new ActiveDirectoryClient();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( AddressHeader.CreateAddressHeader("ClientId",       // Header Name
                                                   string.Empty,     // Namespace
                                                    "OmegaClient")); // Header Value
cl.Endpoint.Address = eab.ToEndpointAddress();

// Now do an operation provided by the service.
cl.ProcessInfo("ABC");

What that code is doing is adding an endpoint header named ClientId with a value of OmegaClient to be inserted into the soap header without a namespace.

Custom Header in Client’s Config File
There is an alternate way of doing a custom header. That can be achieved in the Xml config file of the client where all messages sent by specifying the custom header as part of the endpoint as so:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IActiveDirectory" />
            </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://localhost:41863/ActiveDirectoryService.svc"
              binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IActiveDirectory"
              contract="ADService.IActiveDirectory" name="BasicHttpBinding_IActiveDirectory">
            <headers>
              <ClientId>Console_Client</ClientId>
            </headers>
          </endpoint>
        </client>
    </system.serviceModel>
</configuration>

Table 'performance_schema.session_variables' doesn't exist

As sixty4bit question, if your mysql root user looks to be misconfigured, try to install the configurator extension from mysql official source:

https://dev.mysql.com/downloads/repo/apt/

It will help you to set up a new root user password.

Make sure to update your repository (debian/ubuntu) :

apt-get update

Why would you use String.Equals over ==?

I've just been banging my head against a wall trying to solve a bug because I read this page and concluded there was no meaningful difference when in practice there is so I'll post this link here in case anyone else finds they get different results out of == and equals.

Object == equality fails, but .Equals succeeds. Does this make sense?

string a = "x";
string b = new String(new []{'x'});

Console.WriteLine("x == x " + (a == b));//True
Console.WriteLine("object x == x " + ((object)a == (object)b));//False
Console.WriteLine("x equals x " + (a.Equals(b)));//True
Console.WriteLine("object x equals x " + (((object)a).Equals((object)b)));//True

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

Propagation Delay vs Transmission delay

Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.

Propagation delay : It's the amount of time needed for a packet to reach the destination.

If propagation delay is very high than transmission delay the chance of losing the packet is high.

Variable not accessible when initialized outside function

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.

How to manage startActivityForResult on Android?

First you use startActivityForResult() with parameters in first Activity and if you want to send data from second Activity to first Activity then pass value using Intent with setResult() method and get that data inside onActivityResult() method in first Activity.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

You can use the DATEDIFF function to get the difference in minutes, seconds, days etc.

SELECT DATEDIFF(MINUTE,job_start,job_end)

MINUTE obviously returns the difference in minutes, you can also use DAY, HOUR, SECOND, YEAR (see the books online link for the full list).

If you want to get fancy you can show this differently for example 75 minutes could be displayed like this: 01:15:00:0

Here is the code to do that for both SQL Server 2005 and 2008

-- SQL Server 2005
SELECT CONVERT(VARCHAR(10),DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000'),114)

-- SQL Server 2008
SELECT CAST(DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000') AS TIME)

Convert Time DataType into AM PM Format:

> SELECT CONVERT(VARCHAR(30), GETDATE(), 100) as date_n_time
> SELECT CONVERT(VARCHAR(20),convert(time,GETDATE()),100) as req_time
> select convert(varchar(20),GETDATE(),103)+' '+convert(varchar(20),convert(time,getdate()),100)

> Result (1):- Jun  9 2018 11:36AM
> result(2):-  11:35AM
> Result (3):-  06/10/2018 11:22AM

How to reload current page without losing any form data?

window.location.reload() // without passing true as argument

works for me.

How to pass command line argument to gnuplot?

You can also pass information in through the environment as is suggested here. The example by Ismail Amin is repeated here:

In the shell:

export name=plot_data_file

In a Gnuplot script:

#! /usr/bin/gnuplot

name=system("echo $name")
set title name
plot name using ($16 * 8):20 with linespoints notitle
pause -1

Merge / convert multiple PDF files into one PDF

Try the good ghostscript:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=merged.pdf mine1.pdf mine2.pdf

or even this way for an improved version for low resolution PDFs (thanks to Adriano for pointing this out):

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=merged.pdf mine1.pdf mine2.pdf

In both cases the ouput resolution is much higher and better than this way using convert:

convert -density 300x300 -quality 100 mine1.pdf mine2.pdf merged.pdf

In this way you wouldn't need to install anything else, just work with what you already have installed in your system (at least both come by default in my box).

Hope this helps,

UPDATE: first of all thanks for all your nice comments!! just a tip that may work for you guys, after googleing, I found a superb trick to shrink the size of PDFs, I reduced with it one PDF of 300 MB to just 15 MB with an acceptable resolution! and all of this with the good ghostscript, here it is:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default -dNOPAUSE -dQUIET -dBATCH -dDetectDuplicateImages -dCompressFonts=true -r150 -sOutputFile=output.pdf input.pdf

cheers!!

How do I get the n-th level parent of an element in jQuery?

Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

$('#element').parents().eq(0);  // "Father".
$('#element').parents().eq(2);  // "Great-grandfather".

Sending POST data in Android

This is an example of how to POST multi-part data WITHOUT using external Apache libraries:

byte[] buffer = getBuffer();

if(buffer.length > 0) {
   String lineEnd = "\r\n"; 
   String twoHyphens = "--"; 
   String boundary =  "RQdzAAihJq7Xp1kjraqf"; 

   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   DataOutputStream dos = new DataOutputStream(baos);

   // Send parameter #1
   dos.writeBytes(twoHyphens + boundary + lineEnd); 
   dos.writeBytes("Content-Disposition: form-data; name=\"param1\"" + lineEnd);
   dos.writeBytes("Content-Type: text/plain; charset=US-ASCII" + lineEnd);
   dos.writeBytes("Content-Transfer-Encoding: 8bit" + lineEnd);
   dos.writeBytes(lineEnd);
   dos.writeBytes(myStringData + lineEnd);

   // Send parameter #2
   //dos.writeBytes(twoHyphens + boundary + lineEnd); 
   //dos.writeBytes("Content-Disposition: form-data; name=\"param2\"" + lineEnd + lineEnd);
   //dos.writeBytes("foo2" + lineEnd);

   // Send a binary file
   dos.writeBytes(twoHyphens + boundary + lineEnd); 
   dos.writeBytes("Content-Disposition: form-data; name=\"param3\";filename=\"test_file.dat\"" + lineEnd); 
   dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
   dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
   dos.writeBytes(lineEnd); 
   dos.write(buffer);
   dos.writeBytes(lineEnd); 
   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
   dos.flush(); 
   dos.close();

   ByteArrayInputStream content = new ByteArrayInputStream(baos.toByteArray());
   BasicHttpEntity entity = new BasicHttpEntity();
   entity.setContent(content);

   HttpPost httpPost = new HttpPost(myURL);
   httpPost.addHeader("Connection", "Keep-Alive");
   httpPost.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);

   //MultipartEntity entity = new MultipartEntity();
   //entity.addPart("param3", new ByteArrayBody(buffer, "test_file.dat"));
   //entity.addPart("param1", new StringBody(myStringData));

   httpPost.setEntity(entity);

   /*
   String httpData = "";
   ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
   entity.writeTo(baos1);
   httpData = baos1.toString("UTF-8");
   */

   /*
   Header[] hdrs = httpPost.getAllHeaders();
   for(Header hdr: hdrs) {
     httpData += hdr.getName() + " | " + hdr.getValue() + " |_| ";
   }
   */

   //Log.e(TAG, "httpPost data: " + httpData);
   response = httpClient.execute(httpPost);
}

What is the difference between a "function" and a "procedure"?

A function returns a value and a procedure just executes commands.

The name function comes from math. It is used to calculate a value based on input.

A procedure is a set of commands which can be executed in order.

In most programming languages, even functions can have a set of commands. Hence the difference is only returning a value.

But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.

How to use Visual Studio Code as Default Editor for Git

In the most recent release (v1.0, released in March 2016), you are now able to use VS Code as the default git commit/diff tool. Quoted from the documentations:

  1. Make sure you can run code --help from the command line and you get help.

    • if you do not see help, please follow these steps:

      • Mac: Select Shell Command: Install 'Code' command in path from the Command Palette.

        • Command Palette is what pops up when you press shift + ? + P while inside VS Code. (shift + ctrl + P in Windows)
      • Windows: Make sure you selected Add to PATH during the installation.
      • Linux: Make sure you installed Code via our new .deb or .rpm packages.
  2. From the command line, run git config --global core.editor "code --wait"

Now you can run git config --global -e and use VS Code as editor for configuring Git. enter image description here Add the following to enable support for using VS Code as diff tool:

[diff]
    tool = default-difftool
[difftool "default-difftool"]
    cmd = code --wait --diff $LOCAL $REMOTE

This leverages the new --diff option you can pass to VS Code to compare two files side by side.

To summarize, here are some examples of where you can use Git with VS Code:

  • git rebase HEAD~3 -i allows to interactive rebase using VS Code
  • git commit allows to use VS Code for the commit message
  • git add -p followed by e for interactive add
  • git difftool <commit>^ <commit> allows to use VS Code as diff editor for changes

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

If you install the IIS after the installation of .Net FrameWork. You need install the .net framework again for IIS. So all we need to do is run aspnet_regiis -i. Hope it is helpful.

Get index of current item in a PowerShell loop

I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:

$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}

Or use a for loop instead...

for ($counter=0; $counter -lt $letters.Length; $counter++){...}

How to update array value javascript?

So I had a problem I needed solved. I had an array object with values. One of those values I needed to update if the value == X.I needed X value to be updated to the Y value. Looking over examples here none of them worked for what I needed or wanted. I finally figured out a simple solution to the problem and was actually surprised it worked. Now normally I like to put the full code solution into these answers but due to its complexity I wont do that here. If anyone finds they cant make this solution work or need more code let me know and I will attempt to update this at some later date to help. For the most part if the array object has named values this solution should work.

            $scope.model.ticketsArr.forEach(function (Ticket) {
                if (Ticket.AppointmentType == 'CRASH_TECH_SUPPORT') {
                    Ticket.AppointmentType = '360_SUPPORT'
                }
            });

Full example below _____________________________________________________

   var Students = [
        { ID: 1, FName: "Ajay", LName: "Test1", Age: 20 },
        { ID: 2, FName: "Jack", LName: "Test2", Age: 21 },
        { ID: 3, FName: "John", LName: "Test3", age: 22 },
        { ID: 4, FName: "Steve", LName: "Test4", Age: 22 }
    ]

    Students.forEach(function (Student) {
        if (Student.LName == 'Test1') {
            Student.LName = 'Smith'
        }
        if (Student.LName == 'Test2') {
            Student.LName = 'Black'
        }
    });

    Students.forEach(function (Student) {
        document.write(Student.FName + " " + Student.LName + "<BR>");
    });

Android emulator: How to monitor network traffic?

You can monitor network traffic from Android Studio. Go to Android Monitor and open Network tab.

http://developer.android.com/tools/debugging/ddms.html

UPDATE: ?? Android Device Monitor was deprecated in Android Studio 3.1. See more in https://developer.android.com/studio/profile/monitor

How to correctly use the extern keyword in C

Many years later, I discover this question. After reading every answer and comment, I thought I could clarify a few details... This could be useful for people who get here through Google search.

The question is specifically about using "extern" functions, so I will ignore the use of "extern" with global variables.

Let's define 3 function prototypes:

//--------------------------------------
//Filename: "my_project.H"
extern int function_1(void);
static int function_2(void);
       int function_3(void);

The header file can be used by the main source code as follows:

//--------------------------------------
//Filename: "my_project.C"
#include "my_project.H"

void main(void){
    int v1 = function_1();
    int v2 = function_2();
    int v3 = function_3();
}

int function_2(void) return 1234;

In order to compile and link, we must define "function_2" in the same source code file where we call that function. The two other functions could be defined in different source code ".C" or they may be located in any binary file (.OBJ, *.LIB, *.DLL), for which we may not have the source code.

Let's include again the header "my_project.H" in a different "*.C" file to understand better the difference. In the same project, we add the following file:

//--------------------------------------
//Filename: "my_big_project_splitted.C"
#include "my_project.H"

void old_main_test(void){
    int v1 = function_1();
    int v2 = function_2();
    int v3 = function_3();
}

int function_2(void) return 5678;

int function_1(void) return 12;
int function_3(void) return 34;

Important features to notice:

  • When a function is defined as "static" in a header file, the compiler/linker must find an instance of a function with that name in each module which uses that include file.

  • A function which is part of the C library can be replaced in only one module by redefining a prototype with "static" only in that module. For example, replace any call to "malloc" and "free" to add memory leak detection feature.

  • The specifier "extern" is not really needed for functions. When "static" is not found, a function is always assumed to be "extern'.

  • However, "extern" is not the default for variables. Normally, any header file that defines variables to be visible across many modules needs to use "extern". The only exception would be if a header file is guaranteed to be included from one and only one module.

    Many project manager would then require that such variable be placed at the beginning of the module, not inside any header file. Some large projects, such as the video game emulator "Mame" even require that such variable appears only above the first function using them.

How to get parameters from a URL string?

To get parameters from URL string, I used following function.

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};
var email = getUrlParameter('email');

If there are many URL strings, then you can use loop to get parameter 'email' from all those URL strings and store them in array.

Constructor overloading in Java - best practice

Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.

The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.

For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

Gradle, Android and the ANDROID_HOME SDK location

In my case settings.gradle was missing.

Save the file and put it at the top level folder in your project, even you can copy from another project too.

Screenshot reference:

enter image description here

Hope this would save your time.

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

Links not going back a directory?

There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.

Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:

  • /pages/en/faqs/faq-page1.html

Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them

  • index.html is:
    • /pages/en/faqs/index.html if called from /pages/en/faqs/faq-page1.html
    • /pages/index.html if called from /pages/example.html
    • etc.

There are also two special directory names: . and ..:

  • . means "current directory"
  • .. means "parent directory"

You can use them to build relative paths:

  • ../index.html is /pages/en/index.html if called from /pages/en/faqs/faq-page1.html
  • ../../index.html is /pages/index.html if called from /pages/en/faqs/faq-page1.html

Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:

  • Use absolute paths
  • Fix your relative paths

How to round a number to significant figures in Python

https://stackoverflow.com/users/1391441/gabriel, does the following address your concern about rnd(.075, 1)? Caveat: returns value as a float

def round_to_n(x, n):
    fmt = '{:1.' + str(n) + 'e}'    # gives 1.n figures
    p = fmt.format(x).split('e')    # get mantissa and exponent
                                    # round "extra" figure off mantissa
    p[0] = str(round(float(p[0]) * 10**(n-1)) / 10**(n-1))
    return float(p[0] + 'e' + p[1]) # convert str to float

>>> round_to_n(750, 2)
750.0
>>> round_to_n(750, 1)
800.0
>>> round_to_n(.0750, 2)
0.075
>>> round_to_n(.0750, 1)
0.08
>>> math.pi
3.141592653589793
>>> round_to_n(math.pi, 7)
3.141593

How do I configure PyCharm to run py.test tests?

PyCharm 2017.3

  1. Preference -> Tools -> Python integrated Tools - Choose py.test as Default test runner.
  2. If you use Django Preference -> Languages&Frameworks -> Django - Set tick on Do not use Django Test runner
  3. Clear all previously existing test configurations from Run/Debug configuration, otherwise tests will be run with those older configurations.
  4. To set some default additional arguments update py.test default configuration. Run/Debug Configuration -> Defaults -> Python tests -> py.test -> Additional Arguments

How does Python manage int and long?

Interesting. On my 64-bit (i7 Ubuntu) box:

>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'int'>

Guess it steps up to 64 bit ints on a larger machine.

Why is __init__() always called after __new__()?

However, I'm a bit confused as to why __init__ is always called after __new__.

I think the C++ analogy would be useful here:

  1. __new__ simply allocates memory for the object. The instance variables of an object needs memory to hold it, and this is what the step __new__ would do.

  2. __init__ initialize the internal variables of the object to specific values (could be default).

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

ImportError: No module named model_selection

I encountered this problem when I import GridSearchCV.

Just changed sklearn.model_selection to sklearn.grid_search.

Does Eclipse have line-wrap

Ctrl+Shift+F will format a file in Eclipse, breaking long lines into multiple lines and nicely word-wrapping comments. You can also highlight just a section of text and format that.

I realize this is not an automatic soft/hard word wrap like the other answers, but I don't think the question was asking for anything fancy.

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

How to remove the first and the last character of a string

url=url.substring(1,url.Length-1);

This way you can use the directories if it is like .../.../.../... etc.

Encoding conversion in java

I would just like to add that if the String is originally encoded using the wrong encoding it might be impossible to change it to another encoding without errors. The question does not state that the conversion here is made from wrong encoding to correct encoding but I personally stumbled to this question just because of this situation so just a heads up for others as well.

This answer in other question gives an explanation why the conversion does not always yield correct results https://stackoverflow.com/a/2623793/4702806

How is "mvn clean install" different from "mvn install"?

clean is its own build lifecycle phase (which can be thought of as an action or task) in Maven. mvn clean install tells Maven to do the clean phase in each module before running the install phase for each module.

What this does is clear any compiled files you have, making sure that you're really compiling each module from scratch.

What's the difference between an argument and a parameter?

As my background and main environment is C, I will provide some statements/citations to that topic from the actual C standard and an important reference book, from also one of the developers of C, which is often cited and common treated as the first unofficial standard of C:


The C Programming Language (2nd Edition) by Brian W. Kernighan and Dennis M. Ritchie (April 1988):

Page 25, Section 1.7 - Functions

We will generally use parameter for a variable named in the parenthesized list in a function definition, and argument for the value used in the call of the function. The terms formal argument and actual argument are sometimes used for the same distinction.

ISO/IEC 9899:2018 (C18):

3.3

argument

actual argument

DEPRECATED: actual parameter

expression in the comma-separated list bounded by the parentheses in a function call expression, or a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation.


3.16

parameter

formal parameter

DEPRECATED: formal argument

object declared as part of a function declaration or definition that acquires a value on entry to the function, or an identifier from the comma-separated list bounded by the parentheses immediately following the macro name in a function-like macro definition.

Google Maps setCenter()

I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.

map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });

<div id="map_canvas2" style="width: 850px; height: 600px">
</div>

"unexpected token import" in Nodejs5 and babel?

babel-preset-es2015 is now deprecated and you'll get a warning if you try to use Laurence's solution.

To get this working with Babel 6.24.1+, use babel-preset-env instead:

npm install babel-preset-env --save-dev

Then add env to your presets in your .babelrc:

{
  "presets": ["env"]
}

See the Babel docs for more info.

Joining two lists together

As long as they are of the same type, it's very simple with AddRange:

list2.AddRange(list1);

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Vue template or render function not defined yet I am using neither?

When used with storybook and typescirpt, I had to add

.storybook/webpack.config.js

const path = require('path');

module.exports = async ({ config, mode }) => {

    config.module.rules.push({
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
            {
                loader: 'ts-loader',
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                    transpileOnly: true
                },
            }
        ],
    });

    return config;
};

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Using two values for one switch case statement

Just do

case text1: case text4: 
     do stuff;
     break;

Terminating a script in PowerShell

May be it is better to use "trap". A PowerShell trap specifies a codeblock to run when a terminating or error occurs. Type

Get-Help about_trap

to learn more about the trap statement.

How does paintComponent work?

The (very) short answer to your question is that paintComponent is called "when it needs to be." Sometimes it's easier to think of the Java Swing GUI system as a "black-box," where much of the internals are handled without too much visibility.

There are a number of factors that determine when a component needs to be re-painted, ranging from moving, re-sizing, changing focus, being hidden by other frames, and so on and so forth. Many of these events are detected auto-magically, and paintComponent is called internally when it is determined that that operation is necessary.

I've worked with Swing for many years, and I don't think I've ever called paintComponent directly, or even seen it called directly from something else. The closest I've come is using the repaint() methods to programmatically trigger a repaint of certain components (which I assume calls the correct paintComponent methods downstream.

In my experience, paintComponent is rarely directly overridden. I admit that there are custom rendering tasks that require such granularity, but Java Swing does offer a (fairly) robust set of JComponents and Layouts that can be used to do much of the heavy lifting without having to directly override paintComponent. I guess my point here is to make sure that you can't do something with native JComponents and Layouts before you go off trying to roll your own custom-rendered components.

Initialization of all elements of an array to one default value in C++?

Using std::array, we can do this in a fairly straightforward way in C++14. It is possible to do in C++11 only, but slightly more complicated.

Our interface is a compile-time size and a default value.

template<typename T>
constexpr auto make_array_n(std::integral_constant<std::size_t, 0>, T &&) {
    return std::array<std::decay_t<T>, 0>{};
}

template<std::size_t size, typename T>
constexpr auto make_array_n(std::integral_constant<std::size_t, size>, T && value) {
    return detail::make_array_n_impl<size>(std::forward<T>(value), std::make_index_sequence<size - 1>{});
}


template<std::size_t size, typename T>
constexpr auto make_array_n(T && value) {
    return make_array_n(std::integral_constant<std::size_t, size>{}, std::forward<T>(value));
}

The third function is mainly for convenience, so the user does not have to construct a std::integral_constant<std::size_t, size> themselves, as that is a pretty wordy construction. The real work is done by one of the first two functions.

The first overload is pretty straightforward: It constructs a std::array of size 0. There is no copying necessary, we just construct it.

The second overload is a little trickier. It forwards along the value it got as the source, and it also constructs an instance of make_index_sequence and just calls some other implementation function. What does that function look like?

namespace detail {

template<std::size_t size, typename T, std::size_t... indexes>
constexpr auto make_array_n_impl(T && value, std::index_sequence<indexes...>) {
    // Use the comma operator to expand the variadic pack
    // Move the last element in if possible. Order of evaluation is well-defined
    // for aggregate initialization, so there is no risk of copy-after-move
    return std::array<std::decay_t<T>, size>{ (static_cast<void>(indexes), value)..., std::forward<T>(value) };
}

}   // namespace detail

This constructs the first size - 1 arguments by copying the value we passed in. Here, we use our variadic parameter pack indexes just as something to expand. There are size - 1 entries in that pack (as we specified in the construction of make_index_sequence), and they have values of 0, 1, 2, 3, ..., size - 2. However, we do not care about the values (so we cast it to void, to silence any compiler warnings). Parameter pack expansion expands out our code to something like this (assuming size == 4):

return std::array<std::decay_t<T>, 4>{ (static_cast<void>(0), value), (static_cast<void>(1), value), (static_cast<void>(2), value), std::forward<T>(value) };

We use those parentheses to ensure that the variadic pack expansion ... expands what we want, and also to ensure we are using the comma operator. Without the parentheses, it would look like we are passing a bunch of arguments to our array initialization, but really, we are evaluating the index, casting it to void, ignoring that void result, and then returning value, which is copied into the array.

The final argument, the one we call std::forward on, is a minor optimization. If someone passes in a temporary std::string and says "make an array of 5 of these", we would like to have 4 copies and 1 move, instead of 5 copies. The std::forward ensures that we do this.

The full code, including headers and some unit tests:

#include <array>
#include <type_traits>
#include <utility>

namespace detail {

template<std::size_t size, typename T, std::size_t... indexes>
constexpr auto make_array_n_impl(T && value, std::index_sequence<indexes...>) {
    // Use the comma operator to expand the variadic pack
    // Move the last element in if possible. Order of evaluation is well-defined
    // for aggregate initialization, so there is no risk of copy-after-move
    return std::array<std::decay_t<T>, size>{ (static_cast<void>(indexes), value)..., std::forward<T>(value) };
}

}   // namespace detail

template<typename T>
constexpr auto make_array_n(std::integral_constant<std::size_t, 0>, T &&) {
    return std::array<std::decay_t<T>, 0>{};
}

template<std::size_t size, typename T>
constexpr auto make_array_n(std::integral_constant<std::size_t, size>, T && value) {
    return detail::make_array_n_impl<size>(std::forward<T>(value), std::make_index_sequence<size - 1>{});
}

template<std::size_t size, typename T>
constexpr auto make_array_n(T && value) {
    return make_array_n(std::integral_constant<std::size_t, size>{}, std::forward<T>(value));
}



struct non_copyable {
    constexpr non_copyable() = default;
    constexpr non_copyable(non_copyable const &) = delete;
    constexpr non_copyable(non_copyable &&) = default;
};

int main() {
    constexpr auto array_n = make_array_n<6>(5);
    static_assert(std::is_same<std::decay_t<decltype(array_n)>::value_type, int>::value, "Incorrect type from make_array_n.");
    static_assert(array_n.size() == 6, "Incorrect size from make_array_n.");
    static_assert(array_n[3] == 5, "Incorrect values from make_array_n.");

    constexpr auto array_non_copyable = make_array_n<1>(non_copyable{});
    static_assert(array_non_copyable.size() == 1, "Incorrect array size of 1 for move-only types.");

    constexpr auto array_empty = make_array_n<0>(2);
    static_assert(array_empty.empty(), "Incorrect array size for empty array.");

    constexpr auto array_non_copyable_empty = make_array_n<0>(non_copyable{});
    static_assert(array_non_copyable_empty.empty(), "Incorrect array size for empty array of move-only.");
}

error MSB6006: "cmd.exe" exited with code 1

error MSB6006: "cmd.exe" exited with code -Solved

I also face this problem . In my case it is due to output exe already running .I solved my problem simply close the application instance before building.

Coarse-grained vs fine-grained

In the context of services:

http://en.wikipedia.org/wiki/Service_Granularity_Principle

By definition a coarse-grained service operation has broader scope than a fine-grained service, although the terms are relative. The former typically requires increased design complexity but can reduce the number of calls required to complete a task.

A fine grained service interface is about the same like chatty interface.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

PHP String to Float

I was running in to a problem with the standard way to do this:

$string = "one";

$float = (float)$string;

echo $float; : ( Prints 0 )

If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)

To fix this I have done the following:

$string = "one";

$float = is_numeric($string) ? (float)$string : null;

echo $float; : ( Prints nothing )

Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.

How to calculate percentage with a SQL statement

I have tested the following and this does work. The answer by gordyii was close but had the multiplication of 100 in the wrong place and had some missing parenthesis.

Select Grade, (Count(Grade)* 100 / (Select Count(*) From MyTable)) as Score
From MyTable
Group By Grade

Page vs Window in WPF?

A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.

How to pass a user / password in ansible command

As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.

read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"

Are there constants in JavaScript?

I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I've come up with a viable solution to this.

It seems that most of the answers that I've come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts' answer that the constants object can not be accessed by the outside, but only from the functions on the inside.

So I came up with this solution:

Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the 'real' functions by having other functions call the 'real' functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are 'protected' on the inside and cannot be changed.

/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/

(function(){
  /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST).
    They're the same just as he did them, the only things I changed are the variable names and the text
    of the error messages.
  */

  //object literal to hold the constants
  var j = {};

  /*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants.
    The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has
    to exist. If there is already a property with the same name in the object holder, then we throw an error.
    If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't
    see any of your coding call this function. You call the _makeDef() in your code and that function calls
    this function.    -    You can change the error messages to whatever you want them to say.
  */
  self._define = function(h,m) {
      if (typeof h !== 'string') { throw new Error('I don\'t know what to do.'); }
      if (!m) { throw new Error('I don\'t know what to do.'); }
      else if ((h in j) ) { throw new Error('We have a problem!'); }
      else {
          j[h] = m;
          return true;
    }
  };

  /*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this
    function. The argument 't' is the name of the const and doesn't need to be all caps because I set it
    to upper case within the function, 'y' is the value of the value of the const and has to exist. I
    make different variables to make it harder for a user to figure out whats going on. We then call the
    _define function with the two new variables. You call this function in your code to set the constant.
    You can change the error message to whatever you want it to say.
  */
  self._makeDef = function(t, y) {
      if(!y) { throw new Error('I don\'t know what to do.'); return false; }
      q = t.toUpperCase();
      w = y;
      _define(q, w);
  };

  /*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The
    argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case
    within the function. I make a different variable to make it harder for a user to figure out whats going
    on. The function returns the _access function call. I pass the new variable and the original string
    along to the _access function. I do this because if a user is trying to get the value of something, if
    there is an error the argument doesn't get displayed with upper case in the error message. You call this
    function in your code to get the constant.
  */
  self._getDef = function(s) {
      z = s.toUpperCase();
      return _access(z, s);
  };

  /*Global function _access(String g, String f). I named it access because we 'access' the constant through
    this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name
    of the const, but its the original string that was passed to the _getDef() function. If there is an
    error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the
    constants are being stored. If there is a property with the same name in the object holder, we return
    the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and
    throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this
    function. You call the _getDef() function in your code and that function calls this function.
    You can change the error messages to whatever you want them to say.
  */
  self._access = function(g, f) {
      if (typeof g !== 'string') { throw new Error('I don\'t know what to do.'); }
      if ( g in j ) { return j[g]; }
      else { if(!f) { f = g; } throw new Error('I don\'t know what to do. I have no idea what \''+f+'\' is.'); }
  };

  /*The four variables below are private and cannot be accessed from the outside script except for the
    functions inside this anonymous function. These variables are strings of the four above functions and
    will be used by the all-dreaded eval() function to set them back to their original if any of them should
    be changed by a user trying to hack your code.
  */
  var _define_func_string = "function(h,m) {"+"      if (typeof h !== 'string') { throw new Error('I don\\'t know what to do.'); }"+"      if (!m) { throw new Error('I don\\'t know what to do.'); }"+"      else if ((h in j) ) { throw new Error('We have a problem!'); }"+"      else {"+"          j[h] = m;"+"          return true;"+"    }"+"  }";
  var _makeDef_func_string = "function(t, y) {"+"      if(!y) { throw new Error('I don\\'t know what to do.'); return false; }"+"      q = t.toUpperCase();"+"      w = y;"+"      _define(q, w);"+"  }";
  var _getDef_func_string = "function(s) {"+"      z = s.toUpperCase();"+"      return _access(z, s);"+"  }";
  var _access_func_string = "function(g, f) {"+"      if (typeof g !== 'string') { throw new Error('I don\\'t know what to do.'); }"+"      if ( g in j ) { return j[g]; }"+"      else { if(!f) { f = g; } throw new Error('I don\\'t know what to do. I have no idea what \\''+f+'\\' is.'); }"+"  }";

  /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions'
    The argument 'u' is the name of any of the four above function names you want to check. This function will
    check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then
    we use the eval() function to set the function back to its original coding using the function string
    variables above. This function will also throw an error depending upon the doError variable being set to true
    This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the
    doCodeCheck() function and that function calls this function.    -    You can change the error messages to
    whatever you want them to say.
  */
  self._doFunctionCheck = function(u) {
      var errMsg = 'We have a BIG problem! You\'ve changed my code.';
      var doError = true;
      d = u;
      switch(d.toLowerCase())
      {
           case "_getdef":
               if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) { /*do nothing*/ }
               else { eval("_getDef = "+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           case "_makedef":
               if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1) { /*do nothing*/ }
               else { eval("_makeDef = "+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           case "_define":
               if(_define.toString().indexOf("else if((h in j) ) {") != -1) { /*do nothing*/ }
               else { eval("_define = "+_define_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           case "_access":
               if(_access.toString().indexOf("else { if(!f) { f = g; }") != -1) { /*do nothing*/ }
               else { eval("_access = "+_access_func_string); if(doError === true) { throw new Error(errMsg); } }
               break;
           default:
                if(doError === true) { throw new Error('I don\'t know what to do.'); }
      }
  };

  /*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument
    'v' is the name of one of the first four functions in this script that you want to check. I make a different
    variable to make it harder for a user to figure out whats going on. You call this function in your code to check
    if any of the functions has been changed by the user.
  */
  self._doCodeCheck = function(v) {
      l = v;
      _doFunctionCheck(l);
  };
}())

It also seems that security is really a problem and there is not way to 'hide' you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: http://javascriptcompressor.com/. (This is not my site, don't worry I'm not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.

  1. Copy all the code in the above script and paste it into the top textarea on the javascriptcompressor.com page.
  2. Check the Base62 encode checkbox, check the Shrink Variables checkbox.
  3. Press the Compress button.
  4. Paste and save it all in a .js file and add it to your page in the head of your page.

CSS property to pad text inside of div

I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:

<div id="container">
    <p id="text">Find Agents</p>
</div>

All you need to do is apply this CSS:

#text {
    padding: 10px;
}

Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/

Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:

.container * {
    padding: 5px 10px;
}

Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/

Android Push Notifications: Icon not displaying in notification, white square shown instead

I have resolved the problem by adding below code to manifest,

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_name" />

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/black" />

where ic_stat_name created on Android Studio Right Click on res >> New >>Image Assets >> IconType(Notification)

And one more step I have to do on server php side with notification payload

$message = [
    "message" => [
        "notification" => [
            "body"  => $title , 
            "title" => $message
        ],

        "token" => $token,

    "android" => [
           "notification" => [
            "sound"  => "default",
            "icon"  => "ic_stat_name"
            ]
        ],

       "data" => [
            "title" => $title,
            "message" => $message
         ]


    ]
];

Note the section

    "android" => [
           "notification" => [
            "sound"  => "default",
            "icon"  => "ic_stat_name"
            ]
        ]

where icon name is "icon" => "ic_stat_name" should be the same set on manifest.

How to use format() on a moment.js duration?

I use:

var duration = moment.duration("09:30");
var str = moment(duration._data).format("HH:mm");

And I get "09:30" in var str.

Authenticate with GitHub using a token

Automation / Git automation with OAuth tokens

$ git clone https://github.com/username/repo.git
  Username: your_token
  Password:

It also works in the git push command.

Reference: https://help.github.com/articles/git-automation-with-oauth-tokens/

Why does my sorting loop seem to append an element where it shouldn't?

Starting from Java 8, you can also use parallelSort which is useful if you have arrays containing a lot of elements.

Example:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "b", "y" };
    Arrays.parallelSort(strings);
    System.out.println(Arrays.toString(strings));   // [a, b, c, x, y]
}

If you want to ignore the case, you can use:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "B", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.compareToIgnoreCase(o2);
        }
    });
    System.out.println(Arrays.toString(strings));   // [a, B, c, x, y]
}

otherwise B will be before a.

If you want to ignore the trailing spaces during the comparison, you can use trim():

public static void main(String[] args) {
    String[] strings = { "x", "  a", "c ", " b", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.trim().compareTo(o2.trim());
        }
    });
    System.out.println(Arrays.toString(strings)); // [  a,  b, c , x, y]
}

See:

Java: Get last element after split

You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

Force re-download of release dependency using Maven

I just deleted my ~/.m2/repository and that forced a re-download ;)

Setting Camera Parameters in OpenCV/Python

I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was

import time
import cv2


cap = cv2.VideoCapture(0)

cap.set(3,1280)

cap.set(4,1024)

time.sleep(2)

cap.set(15, -8.0)

the time you have to use can be different

The most efficient way to implement an integer based power function pow(int, int)

My case is a little different, I'm trying to create a mask from a power, but I thought I'd share the solution I found anyway.

Obviously, it only works for powers of 2.

Mask1 = 1 << (Exponent - 1);
Mask2 = Mask1 - 1;
return Mask1 + Mask2;

How do I convert a number to a letter in Java?

if you define a/A as 0

char res;
if (i>25 || i<0){
    res = null;
}
    res = (i) + 65
}
return res;

65 for captitals; 97 for non captitals

How can I get the current time in C#?

DateTime.Now.ToShortTimeString().ToString()

This Will give you DateTime as 10:50PM

How do I set the selenium webdriver get timeout?

I had the same problem and thanks to this forum and some other found the answer. Initially I also thought of separate thread but it complicates the code a bit. So I tried to find an answer that aligns with my principle "elegance and simplicity".

Please have a look at such forum: https://sqa.stackexchange.com/questions/2606/what-is-seleniums-default-timeout-for-page-loading

#

SOLUTION: In the code, before the line with 'get' method you can use for example:

driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
#

One thing is that it throws timeoutException so you have to encapsulate it in the try catch block or wrap in some method.

I haven't found the getter for the pageLoadTimeout so I don't know what is the default value, but probably very high since my script was frozen for many hours and nothing moved forward.

#

NOTICE: 'pageLoadTimeout' is NOT implemented for Chrome driver and thus causes exception. I saw by users comments that there are plans to make it.

Import txt file and having each line as a list

Create a list of lists:

with open("/path/to/file") as file:
    lines = []
    for line in file:
        # The rstrip method gets rid of the "\n" at the end of each line
        lines.append(line.rstrip().split(","))

How to get div height to auto-adjust to background size?

There is a very nice and cool way to make a background image work like an img element so it adjust its height automatically. You need to know the image width and height ratio. Set the height of the container to 0 and set the padding-top as percentage based upon the image ratio.

It will look like the following:

div {
    background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: 0;
    padding-top: 66.64%; /* (img-height / img-width * container-width) */
                /* (853 / 1280 * 100) */
}

You just got a background image with auto height which will work just like an img element. Here is a working prototype (you can resize and check the div height): http://jsfiddle.net/TPEFn/2/

Django - "no module named django.core.management"

Most probably in your manage.py the first line starts with !/usr/bin/python which means you are using the system global python rather than the one in your virtual environment.

so replace

/usr/bin/python

with

~/projectpath/venv/bin/python

and you should be good.

psql - save results of command to a file

Use the below query to store the result in a CSV file

\copy (your query) to 'file path' csv header;

Example

\copy (select name,date_order from purchase_order) to '/home/ankit/Desktop/result.csv' cvs header;

Hope this helps you.

How to extract Month from date in R

Without the need of an external package:

if your date is in the following format:

myDate = as.POSIXct("2013-01-01")

Then to get the month number:

format(myDate,"%m")

And to get the month string:

format(myDate,"%B")