Programs & Examples On #Delphi units

Delphi units are source code modules (text files with .pas extension) that are compiled individually to form an application.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Create a template file and use a template engine to read/update the file. It will increase your code's maintainability in the future as well as separate display from logic.

An example using Smarty:

Template File

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>{$title}</title></head>
<body>{$string}</body>
</html>

Code

function TestBlockHTML(){
  $smarty = new Smarty();
  $smarty->assign('title', 'My Title');
  $smarty->assign('string', $replStr);
  return $smarty->render('template.tpl');
}

Mask for an Input to allow phone numbers?

<input type="text" formControlName="gsm" (input)="formatGsm($event.target.value)">

formatGsm(inputValue: String): String {
  const value = inputValue.replace(/[^0-9]/g, ''); // remove except digits
  let format = '(***) *** ** **'; // You can change format

  for (let i = 0; i < value.length; i++) {
    format = format.replace('*', value.charAt(i));
  }

  if (format.indexOf('*') >= 0) {
    format = format.substring(0, format.indexOf('*'));
  }

  return format.trim();
}

How to change button background image on mouseOver?

In the case of winforms:

If you include the images to your resources you can do it like this, very simple and straight forward:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

I would not recommend hardcoding image paths.

As you have altered your question ...

There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

To add images to your resources: Projectproperties/resources/add/existing file

How to determine if a type implements an interface with C# reflection

As someone else already mentioned: Benjamin Apr 10 '13 at 22:21"

It sure was easy to not pay attention and get the arguments for IsAssignableFrom backwards. I will go with GetInterfaces now :p –

Well, another way around is just to create a short extension method that fulfills, to some extent, the "most usual" way of thinking (and agreed this is a very little personal choice to make it slightly "more natural" based on one's preferences):

public static class TypeExtensions
{
    public static bool IsAssignableTo(this Type type, Type assignableType)
    {
        return assignableType.IsAssignableFrom(type);
    }
}

And why not going a bit more generic (well not sure if it is really that interesting, well I assume I'm just passing another pinch of 'syntaxing' sugar):

public static class TypeExtensions
{
    public static bool IsAssignableTo(this Type type, Type assignableType)
    {
        return assignableType.IsAssignableFrom(type);
    }

    public static bool IsAssignableTo<TAssignable>(this Type type)
    {
        return IsAssignableTo(type, typeof(TAssignable));
    }
}

I think it might be much more natural that way, but once again just a matter of very personal opinions:

var isTrue = michelleType.IsAssignableTo<IMaBelle>();

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.

Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.

Just my 2 cents worth.

How to run a shell script at startup

Just have a line added to your crontab..

Make sure the file is executable:

chmod +x /path_to_you_file/your_file

To edit crontab file:

crontab -e

Line you have to add:

@reboot  /path_to_you_file/your_file

That simple!

Spring-Security-Oauth2: Full authentication is required to access this resource

I had the same problem, but I solve this with the following class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class OAuthSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Making Enter key on an HTML form submit instead of activating button

You can use jQuery:

$(function() {
    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('button[type=submit] .default').click();
            return false;
        } else {
            return true;
        }
    });
});

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

How to import a jar in Eclipse

first of all you will go to your project what you are created and next right click in your mouse and select properties in the bottom and select build in path in the left corner and add external jar file add click apply .that's it

How to add external fonts to android application

To implement you need use Typeface go through with sample below

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
   if (view instanceof TextView) 
   {
      TextView textView = (TextView) view;
      textView.setTypeface(typeface);
      }
   }
}

How to maintain aspect ratio using HTML IMG tag

The poster is showing a dimension constrained by height in most cases he posted >>> (256x256, 1024x768, 500x400, 205x246, etc.) but fitting a 64px max height pixel dimension, typical of most landscape "photos". So my guess is he wants an image that is always 64 pixels in height. To achieve that, do the following:

<img id="photo1" style="height:64px;width:auto;" src="photo.jpg" height="64" />

This solution guarantees the images are all 64 pixels max in height and allows width to extend or shrink based on each image's aspect ratio. Setting height to 64 in the img height attribute reserves a space in the browser's Rendertree layout as images download, so the content doesn't shift waiting for images to download. Also, the new HTML5 standard does not always honor width and height attributes. They are dimensional "hints" only, not final dimensions of the image. If in your style sheet you reset or change the image height and width, the actual values in the images attributes get reset to either your CSS value or the images native default dimensions. Setting the CSS height to "64px" and the width to "auto" forces width to start with the native image width (not image attribute width) and then calculate a new aspect-ratio using the CSS style for height. That gets you a new width. So the height and width "img" attributes are really not needed here and just force the browser to do extra calculations.

package javax.mail and javax.mail.internet do not exist

You need the javax.mail.jar library. Download it from the Java EE JavaMail GitHub page and add it to your IntelliJ project:

  1. Download javax.mail.jar
  2. Navigate to File > Project Structure...
  3. Go to the Libraries tab
  4. Click on the + button (Add New Project Library)
  5. Browse to the javax.mail.jar file
  6. Click OK to apply the changes

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Java converting Image to BufferedImage

From a Java Game Engine:

/**
 * Converts a given Image into a BufferedImage
 *
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
public static BufferedImage toBufferedImage(Image img)
{
    if (img instanceof BufferedImage)
    {
        return (BufferedImage) img;
    }

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

MySQL SELECT only not null values

MYSQL IS NOT NULL WITH JOINS AND SELECT, INSERT INTO, DELETE & LOGICAL OPERATOR LIKE OR , NOT

Using IS NOT NULL On Join Conditions

 SELECT * FROM users 
 LEFT JOIN posts ON post.user_id = users.id 
 WHERE user_id IS NOT NULL;

 Using IS NOT NULL With AND Logical Operator

 SELECT * FROM users 
 WHERE email_address IS NOT NULL 
 AND mobile_number IS NOT NULL;

Using IS NOT NULL With OR Logical Operator

 SELECT * FROM users 
 WHERE email_address IS NOT NULL 
 OR mobile_number IS NOT NULL;

What's your most controversial programming opinion?

Sometimes it's appropriate to swallow an exception.

For UI bells and wistles, prompting the user with an error message is interuptive, and there is ussually nothing for them to do anyway. In this case, I just log it, and deal with it when it shows up in the logs.

String to HtmlDocument

For those who don't want to use HTML agility pack and want to get HtmlDocument from string using native .net code only here is a good article on how to convert string to HtmlDocument

Here is the code block to use

public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
        {
            WebBrowser browser = new WebBrowser();
            browser.ScriptErrorsSuppressed = true;
            browser.DocumentText = html;
            browser.Document.OpenNew(true);
            browser.Document.Write(html);
            browser.Refresh();
            return browser.Document;
        }

Catching FULL exception message

The following worked well for me

try {
    asdf
} catch {
    $string_err = $_ | Out-String
}

write-host $string_err

The result of this is the following as a string instead of an ErrorRecord object

asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+     asdf
+     ~~~~
    + CategoryInfo          : ObjectNotFound: (asdf:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Best way to access a control on another form in Windows Forms?

Instead of making the control public, you can create a property that controls its visibility:

public bool ControlIsVisible
{
     get { return control.Visible; }
     set { control.Visible = value; }
}

This creates a proper accessor to that control that won't expose the control's whole set of properties.

How to delete files/subfolders in a specific directory at the command prompt in Windows

@ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q

Are there .NET implementation of TLS 1.2?

I fixed my problem by switching to the latest .Net Framework. So your target Framework sets your Security Protocol.

when you have this in Web.config

<system.web>
  <httpRuntime targetFramework="4.5"/>
</system.web>

you will get this by default:

ServicePointManager.SecurityProtocol = Ssl3 | Tls

when you have this in Web.config

<system.web>
  <httpRuntime targetFramework="4.6.1"/>
</system.web>

you will get this by default:

ServicePointManager.SecurityProtocol = Tls12 | Tls11 | Tls

Python conversion from binary string to hexadecimal

 x = int(input("press 1 for dec to oct,bin,hex \n press 2 for bin to dec,hex,oct \n press 3 for oct to bin,hex,dec \n press 4 for hex to bin,dec,oct \n"))


   if x is 1:

  decimal =int(input('Enter the decimal number: '))

  print(bin(decimal),"in binary.")
 print(oct(decimal),"in octal.")
    print(hex(decimal),"in hexadecimal.")

      if x is 2:

       binary = input("Enter number in Binary Format: ");

  decimal = int(binary, 2);
  print(binary,"in Decimal =",decimal);
  print(binary,"in Hexadecimal =",hex(decimal));
  print(binary,"in octal =",oct(decimal));

    if x is 3:

      octal = input("Enter number in Octal Format: ");

      decimal = int(octal, 8);
      print(octal,"in Decimal =",decimal);
      print(octal,"in Hexadecimal =",hex(decimal));
      print(octal,"in Binary =",bin(decimal));

          if x is 4:

         hex = input("Enter number in hexa-decimal Format: ");

      decimal = int(hex, 16);
        print(hex,"in Decimal =",decimal);
      print(hex,"in octal =",oct(decimal));
        print(hex,"in Binary =",bin(decimal));

HTML5 Canvas background image

Make sure that in case your image is not in the dom, and you get it from local directory or server, you should wait for the image to load and just after that to draw it on the canvas.

something like that:

function drawBgImg() {
    let bgImg = new Image();
    bgImg.src = '/images/1.jpg';
    bgImg.onload = () => {
        gCtx.drawImage(bgImg, 0, 0, gElCanvas.width, gElCanvas.height);
    }
}

iPhone UIView Animation Best Practice

The difference seems to be the amount of control you need over the animation.

The CATransition approach gives you more control and therefore more things to set up, eg. the timing function. Being an object, you can store it for later, refactor to point all your animations at it to reduce duplicated code, etc.

The UIView class methods are convenience methods for common animations, but are more limited than CATransition. For example, there are only four possible transition types (flip left, flip right, curl up, curl down). If you wanted to do a fade in, you'd have to either dig down to CATransition's fade transition, or set up an explicit animation of your UIView's alpha.

Note that CATransition on Mac OS X will let you specify an arbitrary CoreImage filter to use as a transition, but as it stands now you can't do this on the iPhone, which lacks CoreImage.

Show git diff on file in staging area

You can show changes that have been staged with the --cached flag:

$ git diff --cached

In more recent versions of git, you can also use the --staged flag (--staged is a synonym for --cached):

$ git diff --staged

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

change html input type by JS?

Here is what I have for mine.

Essentially you are utilizing the onfocus and onblur commands in the tag to trigger the appropriate javascript. It could be as simple as:

<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>

An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:

    <script type="text/javascript">
        function password_set_attribute() {
            if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" || document.getElementsByName[0].value == null) {
                document.getElementsByName("login_text_password")[0].setAttribute('type','text')
                document.getElementsByName("login_text_password")[0].value = 'Password';
            }
            else {
                document.getElementsByName("login_text_password")[0].setAttribute('type','password')
            }
        }
    </script> 

Where HTML looks like:

<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>

OTP (token) should be automatically read from the message

You can try using a simple library like

After installing via gradle and adding permissions initiate SmsVerifyCatcher in method like onCreate activity:

    smsVerifyCatcher = new SmsVerifyCatcher(this, new OnSmsCatchListener<String>() {
    @Override
    public void onSmsCatch(String message) {
        String code = parseCode(message);//Parse verification code
        etCode.setText(code);//set code in edit text
        //then you can send verification code to server
    }
});

Also, override activity lifecicle methods:

  @Override
protected void onStart() {
    super.onStart();
    smsVerifyCatcher.onStart();
}

@Override
protected void onStop() {
    super.onStop();
    smsVerifyCatcher.onStop();
}

/**
 * need for Android 6 real time permissions
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    smsVerifyCatcher.onRequestPermissionsResult(requestCode, permissions, grantResults);
}


public String parseCode(String message) {
    Pattern p = Pattern.compile("\\b\\d{4}\\b");
    Matcher m = p.matcher(message);
    String code = "";
    while (m.find()) {
        code = m.group(0);
    }
    return code;
}

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

I had this problem after I installed Visual Studio 2017 and .NET Framework 4.6 on the machine that previously had Visual Studio 2010.

The problem was that after such an installation the file msvcr100_clr0400.dll from C:\Windows\System32 was overwritten with the new one with a very small size ~19 Kb, however the former one was ~800 Kb.

After I restored the file manually from another build machine cvtres.exe started working properly again.

R cannot be resolved - Android error

I just had this problem for the millionth time and realized what was causing it: I created an XML file with uppercase letters in the name. All your XML filenames in /res must match [a-z0-9\\._].

Attach IntelliJ IDEA debugger to a running Java process

Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).

  • Go to Java tab:

    enter image description here

  • Set your Java properties, for example:

    Java virtual machine

    C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll

    Java virtual machine

    C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar

    Java Options:

    -Dcatalina.home=C:\tomcat

    -Dcatalina.base=C:\tomcat

    -Djava.io.tmpdir=C:\tomcat\temp

    -Djava.util.logging.config.file=C:\tomcat\conf\logging.properties

    -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000

    Java 9 options:

    --add-opens=java.base/java.lang=ALL-UNNAMED

    --add-opens=java.base/java.io=ALL-UNNAMED

    --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED

Where to place $PATH variable assertions in zsh?

Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.

   Commands  are  first  read from /etc/zshenv this cannot be overridden.
   Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
   former  affects all startup files, while the second only affects global
   startup files (those shown here with an path starting with  a  /).   If
   one  of  the  options  is  unset  at  any point, any subsequent startup
   file(s) of the corresponding type will not be read.  It is also  possi-
   ble  for  a  file  in  $ZDOTDIR  to  re-enable GLOBAL_RCS. Both RCS and
   GLOBAL_RCS are set by default.

   Commands are then read from $ZDOTDIR/.zshenv.  If the shell is a  login
   shell,  commands  are  read from /etc/zprofile and then $ZDOTDIR/.zpro-
   file.  Then, if the  shell  is  interactive,  commands  are  read  from
   /etc/zshrc  and then $ZDOTDIR/.zshrc.  Finally, if the shell is a login
   shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.

From this we can see the order files are read is:

/etc/zshenv    # Read for every shell
~/.zshenv      # Read for every shell except ones started with -f
/etc/zprofile  # Global config for login shells, read before zshrc
~/.zprofile    # User config for login shells
/etc/zshrc     # Global config for interactive shells
~/.zshrc       # User config for interactive shells
/etc/zlogin    # Global config for login shells, read after zshrc
~/.zlogin      # User config for login shells
~/.zlogout     # User config for login shells, read upon logout
/etc/zlogout   # Global config for login shells, read after user logout file

You can get more information here.

function to remove duplicate characters in a string

Well I came up with the following solution. Keeping in mind that S and s are not duplicates. Also I have just one hard coded value.. But the code works absolutely fine.

public static String removeDuplicate(String str) {

    StringBuffer rev = new StringBuffer();  
    rev.append(str.charAt(0));

    for(int i=0; i< str.length(); i++)
    {
        int flag = 0;
        for(int j=0; j < rev.length(); j++)
        {
            if(str.charAt(i) == rev.charAt(j))
            {
                flag = 0;
                break;
            }
            else
            {
                flag = 1;
            }
        }
        if(flag == 1)
        {
            rev.append(str.charAt(i));
        }
    }

    return rev.toString();
}

How to use an output parameter in Java?

Thank you. I use passing in an object as a parameter. My Android code is below

    String oPerson= null;
    if (CheckAddress("5556", oPerson))
    {
        Toast.makeText(this, 
                "It's Match! " + oPerson,                   
                Toast.LENGTH_LONG).show();
    }

    private boolean CheckAddress(String iAddress, String oPerson)
{
    Cursor cAddress = mDbHelper.getAllContacts();
    String address = "";        
    if (cAddress.getCount() > 0) {
        cAddress.moveToFirst();
        while (cAddress.isAfterLast() == false) {
            address = cAddress.getString(2).toString();
            oPerson = cAddress.getString(1).toString(); 
            if(iAddress.indexOf(address) != -1)
            {
                Toast.makeText(this, 
                        "Person : " + oPerson,                  
                        Toast.LENGTH_LONG).show();
                System.out.println(oPerson);
                cAddress.close();
                return true;                    
            }
            else cAddress.moveToNext();
        }
    }
    cAddress.close();
    return false;
}

The result is

Person : John

It's Match! null

Actually, "It's Match! John"

Please check my mistake.

Is there a way to change the spacing between legend items in ggplot2?

From Koshke's work on ggplot2 and his blog (Koshke's blog)

... + theme(legend.key.height=unit(3,"line")) # Change 3 to X
... + theme(legend.key.width=unit(3,"line")) # Change 3 to X

Type theme_get() in the console to see other editable legend attributes.

Passing a 2D array to a C++ function

You can do something like this...

#include<iostream>

using namespace std;

//for changing values in 2D array
void myFunc(double *a,int rows,int cols){
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            *(a+ i*rows + j)+=10.0;
        }
    }
}

//for printing 2D array,similar to myFunc
void printArray(double *a,int rows,int cols){
    cout<<"Printing your array...\n";
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            cout<<*(a+ i*rows + j)<<"  ";
        }
    cout<<"\n";
    }
}

int main(){
    //declare and initialize your array
    double a[2][2]={{1.5 , 2.5},{3.5 , 4.5}};

    //the 1st argument is the address of the first row i.e
    //the first 1D array
    //the 2nd argument is the no of rows of your array
    //the 3rd argument is the no of columns of your array
    myFunc(a[0],2,2);

    //same way as myFunc
    printArray(a[0],2,2);

    return 0;
}

Your output will be as follows...

11.5  12.5
13.5  14.5

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

The example URLs for standard gmail, above, return a google error.

The February 2014 post to thread 2583928 recommends replacing view=cm&fs=1&tf=1 with &v=b&cs=wh.

Note: It also no longer seems possible to autopopulate the mail body.

How can I copy the content of a branch to a new local branch?

With Git 2.15 (Q4 2017), "git branch" learned "-c/-C" to create a new branch by copying an existing one.

See commit c8b2cec (18 Jun 2017) by Ævar Arnfjörð Bjarmason (avar).
See commit 52d59cc, commit 5463caa (18 Jun 2017) by Sahil Dua (sahildua2305).
(Merged by Junio C Hamano -- gitster -- in commit 3b48045, 03 Oct 2017)

branch: add a --copy (-c) option to go with --move (-m)

Add the ability to --copy a branch and its reflog and configuration, this uses the same underlying machinery as the --move (-m) option except the reflog and configuration is copied instead of being moved.

This is useful for e.g. copying a topic branch to a new version, e.g. work to work-2 after submitting the work topic to the list, while preserving all the tracking info and other configuration that goes with the branch, and unlike --move keeping the other already-submitted branch around for reference.

Note: when copying a branch, you remain on your current branch.
As Junio C Hamano explains, the initial implementation of this new feature was modifying HEAD, which was not good:

When creating a new branch B by copying the branch A that happens to be the current branch, it also updates HEAD to point at the new branch.
It probably was made this way because "git branch -c A B" piggybacked its implementation on "git branch -m A B",

This does not match the usual expectation.
If I were sitting on a blue chair, and somebody comes and repaints it to red, I would accept ending up sitting on a chair that is now red (I am also OK to stand, instead, as there no longer is my favourite blue chair).

But if somebody creates a new red chair, modelling it after the blue chair I am sitting on, I do not expect to be booted off of the blue chair and ending up on sitting on the new red one.

Generate PDF from HTML using pdfMake in Angularjs

Okay, I figured this out.

  1. You will need html2canvas and pdfmake. You do NOT need to do any injection in your app.js to either, just include in your script tags

  2. On the div that you want to create the PDF of, add an ID name like below:

     <div id="exportthis">
    
  3. In your Angular controller use the id of the div in your call to html2canvas:

  4. change the canvas to an image using toDataURL()

  5. Then in your docDefinition for pdfmake assign the image to the content.

  6. The completed code in your controller will look like this:

           html2canvas(document.getElementById('exportthis'), {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    var docDefinition = {
                        content: [{
                            image: data,
                            width: 500,
                        }]
                    };
                    pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
                }
            });
    

I hope this helps someone else. Happy coding!

How to input matrix (2D list) in Python?

no_of_rows = 3  # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)

Sorting JSON by values

Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.

$scope.sortMyData = function (a, b)
{
  var retVal = 0, key;
  for (var i = 0; i < $scope.sortKeys.length; i++)
  {
    if (retVal !== 0)
    {
      break;
    }
    else
    {
      key = $scope.sortKeys[i];
      if ('asc' === key.direction)
      {
        retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
      }
      else
      {
        retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
      }
    }
  }
  return retVal;
};

Date formatting in WPF datagrid

If your bound property is DateTime, then all you need is

Binding={Property, StringFormat=d}

If statement in aspx page

Normally you'd just stick the code in Page_Load in your .aspx page's code-behind.

if (someVar) {
    Item1.Visible = true;
    Item2.Visible = false;
} else {
    Item1.Visible = false;
    Item2.Visible = true;
}

This assumes you've got Item1 and Item2 laid out on the page already.

GitLab remote: HTTP Basic: Access denied and fatal Authentication

Open command prompt as administrator then run this command:

git config --system --unset credential.helper

Java: splitting a comma-separated string but ignoring commas in quotes

what about a one-liner using String.split()?

String s = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String[] split = s.split( "(?<!\".{0,255}[^\"]),|,(?![^\"].*\")" );

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I came across this when upgrading from 5.8 to 6.x.

I had str_slug() in config/cache.php and config/session.php.

I have changed it to Str::slug() and the error has disappeared.

See https://laravel.com/docs/6.x/upgrade#helpers.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Small correction, unescape and escape are deprecated, so:

function utf8_to_b64( str ) {
    return window.btoa(decodeURIComponent(encodeURIComponent(str)));
}

function b64_to_utf8( str ) {
     return decodeURIComponent(encodeURIComponent(window.atob(str)));
}


function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(encodeURIComponent(window.atob(str)));
}

How to Decrease Image Brightness in CSS

The feature you're looking for is filter. It is capable of doing a range of image effects, including brightness:

#myimage {
    filter: brightness(50%);
}

You can find a helpful article about it here: http://www.html5rocks.com/en/tutorials/filters/understanding-css/

An another: http://davidwalsh.name/css-filters

And most importantly, the W3C specs: https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html

Note this is something that's only very recently coming into CSS as a feature. It is available, but a large number of browsers out there won't support it yet, and those that do support it will require a vendor prefix (ie -webkit-filter:, -moz-filter, etc).

It is also possible to do filter effects like this using SVG. SVG support for these effects is well established and widely supported (the CSS filter specs have been taken from the existing SVG specs)

Also note that this is not to be confused with the proprietary filter style available in old versions of IE (although I can predict a problem with the namespace clash when the new style drops its vendor prefix).

If none of that works for you, you could still use the existing opacity feature, but not the way you're thinking: simply create a new element with a solid dark colour, place it on top of your image, and fade it out using opacity. The effect will be of the image behind being darkened.

Finally you can check the browser support of filter here.

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

Centering both horizontally and vertically

Actually, having the height and width in percents makes centering it even easier. You just offset the left and top by half of the area not occupied by the div.

So if you height is 40%, 100% - 40% = 60%. So you want 30% above and below. Then top: 30% does the trick.

See the example here: http://dabblet.com/gist/5957545

Centering only horizontally

Use inline-block. The other answer here will not work for IE 8 and below, however. You must use a CSS hack or conditional styles for that. Here is the hack version:

See the example here: http://dabblet.com/gist/5957591

.inlineblock { 
    display: inline-block;
    zoom: 1;
    display*: inline; /* ie hack */
}

EDIT

By using media queries you can combine two techniques to achive the effect you want. The only complication is height. You use a nested div to switch between % width and

http://dabblet.com/gist/5957676

@media (max-width: 1000px) {
    .center{}
    .center-inner{left:25%;top:25%;position:absolute;width:50%;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
}
@media (min-width: 1000px) {
    .center{left:50%;top:25%;position:absolute;}
    .center-inner{width:500px;height:100%;margin-left:-250px;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
}

How to combine class and ID in CSS selector?

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

Error in eval(expr, envir, enclos) : object not found

This can happen if you don't attach your dataset.

How can I list the scheduled jobs running in my database?

I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)

see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm

UIImage resize (Scale proportion)

This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.

- (UIImage *) scaleProportionalToSize: (CGSize)size
{
    float widthRatio = size.width/self.size.width;
    float heightRatio = size.height/self.size.height;

    if(widthRatio > heightRatio)
    {
        size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
    } else {
        size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
    }

    return [self scaleToSize:size];
}

How can I test an AngularJS service from the console?

First of all, a modified version of your service.

a )

var app = angular.module('app',[]);

app.factory('ExampleService',function(){
    return {
        f1 : function(world){
            return 'Hello' + world;
        }
    };
});

This returns an object, nothing to new here.

Now the way to get this from the console is

b )

var $inj = angular.injector(['app']);
var serv = $inj.get('ExampleService');
serv.f1("World");

c )

One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do

app.factory('ExampleService',function(){
        return function(){
            this.f1 = function(world){
                return 'Hello' + world;
            }
        };
    });

This returns an ExampleService constructor which you will next have to do a 'new' on.

Or alternatively,

app.service('ExampleService',function(){
            this.f1 = function(world){
                return 'Hello' + world;
            };
    });

This returns new ExampleService() on injection.

I want to get the type of a variable at runtime

So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:

val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x

But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:

val x: Any = 5
def f[T](v: T) = v match {
  case _: Int    => "Int"
  case _: String => "String"
  case _         => "Unknown"
}
f(x)

Here it doesn't matter what is the type of the variable, Any. What matters, what is checked is the type of 5, the value. In fact, T is useless -- you might as well have written it def f(v: Any) instead. Also, this uses either ClassTag or a value's Class, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_] (List of something), but not whether it is, for example, a List[Int] or List[String].

Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag or a TypeTag. For example:

val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"

A ClassTag will also let you use type parameters you received on match. This won't work:

def f[A, B](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}

But this will:

val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)

Here I'm using the context bounds syntax, B : ClassTag, which works just like the implicit parameter in the previous ClassTag example, but uses an anonymous variable.

One can also get a ClassTag from a value's Class, like this:

val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
  val B = ClassTag(b.getClass)
  ClassTag(a.getClass) match {
    case B => "a is the same class as b"
    case _ => "a is not the same class as b"
  }
}
f(x, y) == f(y, x) // true, a is the same class as b

A ClassTag is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag for List[Int] and List[String] is the same, List. If you need type parameters, then you must use a TypeTag instead. A TypeTag however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.

Examples with TypeTag can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:

import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int

Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag, so I'll stop here.

Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:

val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it

It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.

How to change the project in GCP using CLI commands

You can change the project using the gcloud command:

gcloud config set project <your_project_name>

Writing a VLOOKUP function in vba

Have you tried:

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

Manually type in a value in a "Select" / Drop-down HTML list?

I love the Shadow Wizard answer, which accually answers the question pretty nicelly. My jQuery twist on this which i use is here. http://jsfiddle.net/UJAe4/

After typing new value, the form is ready to send, just need to handle new values on the back end.

jQuery is:

(function ($) 
{
 $.fn.otherize = function (option_text, texts_placeholder_text) {
    oSel = $(this);
    option_id = oSel.attr('id') + '_other';
    textbox_id = option_id + "_tb";

    this.append("<option value='' id='" + option_id + "' class='otherize' >" + option_text + "</option>");
    this.after("<input type='text' id='" + textbox_id + "' style='display: none; border-bottom: 1px solid black' placeholder='" + texts_placeholder_text + "'/>");
    this.change(

    function () {
        oTbox = oSel.parent().children('#' + textbox_id);
        oSel.children(':selected').hasClass('otherize') ? oTbox.show() : oTbox.hide();
    });

    $("#" + textbox_id).change(

    function () {
        $("#" + option_id).val($("#" + textbox_id).val());
    });
};
}(jQuery));

So you apply this to the below html:

<form>
    <select id="otherize_me">
        <option value=1>option 1</option>
        <option value=2>option 2</option>
        <option value=3>option 3</option>
    </select>
</form>

Just like this:

$(function () {

   $("#otherize_me").otherize("other..", "put new option vallue here");

});

Is it possible to send a variable number of arguments to a JavaScript function?

The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:

var arr = ['quick', 'brown', 'lazy'];

var sprintf = function(str, ...args)
{
    for (arg of args) {
        str = str.replace(/%s/, arg);
    }
    return str;
}

sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');

Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr); is not yet supported. You can find an ES6 compatibility table here.

Note also the use of for...of, another ES6 addition. Using for...in for arrays is a bad idea.

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

How to convert hex to rgb using Java?

If you don't want to use the AWT Color.decode, then just copy the contents of the method:

int i = Integer.decode("#FFFFFF");
int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};

Integer.decode handles the # or 0x, depending on how your string is formatted

Path.Combine absolute with relative path strings

This will give you exactly what you need (path does NOT have to exist for this to work)

DirectoryInfo di = new DirectoryInfo(@"C:\blah\..\bling");
string cleanPath = di.FullName;

Google Maps: How to create a custom InfoWindow?

I found InfoBox perfect for advanced styling.

An InfoBox behaves like a google.maps.InfoWindow, but it supports several additional properties for advanced styling. An InfoBox can also be used as a map label. An InfoBox also fires the same events as a google.maps.InfoWindow.

Include http://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/infobox/src/infobox.js in your page

Laravel view not found exception

As @deanchiu said it may happen when you move the whole project to another path or server.

But in my case I had no access to command line on server and running following commands BEFORE I upload my project helped me.

> php artisan route:clear
> php artisan config:clear

Adding ASP.NET MVC5 Identity Authentication to an existing project

Configuring Identity to your existing project is not hard thing. You must install some NuGet package and do some small configuration.

First install these NuGet packages with Package Manager Console:

PM> Install-Package Microsoft.AspNet.Identity.Owin 
PM> Install-Package Microsoft.AspNet.Identity.EntityFramework
PM> Install-Package Microsoft.Owin.Host.SystemWeb 

Add a user class and with IdentityUser inheritance:

public class AppUser : IdentityUser
{
    //add your custom properties which have not included in IdentityUser before
    public string MyExtraProperty { get; set; }  
}

Do same thing for role:

public class AppRole : IdentityRole
{
    public AppRole() : base() { }
    public AppRole(string name) : base(name) { }
    // extra properties here 
}

Change your DbContext parent from DbContext to IdentityDbContext<AppUser> like this:

public class MyDbContext : IdentityDbContext<AppUser>
{
    // Other part of codes still same 
    // You don't need to add AppUser and AppRole 
    // since automatically added by inheriting form IdentityDbContext<AppUser>
}

If you use the same connection string and enabled migration, EF will create necessary tables for you.

Optionally, you could extend UserManager to add your desired configuration and customization:

public class AppUserManager : UserManager<AppUser>
{
    public AppUserManager(IUserStore<AppUser> store)
        : base(store)
    {
    }

    // this method is called by Owin therefore this is the best place to configure your User Manager
    public static AppUserManager Create(
        IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        var manager = new AppUserManager(
            new UserStore<AppUser>(context.Get<MyDbContext>()));

        // optionally configure your manager
        // ...

        return manager;
    }
}

Since Identity is based on OWIN you need to configure OWIN too:

Add a class to App_Start folder (or anywhere else if you want). This class is used by OWIN. This will be your startup class.

namespace MyAppNamespace
{
    public class IdentityConfig
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new MyDbContext());
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
                new RoleManager<AppRole>(
                    new RoleStore<AppRole>(context.Get<MyDbContext>())));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Login"),
            });
        }
    }
}

Almost done just add this line of code to your web.config file so OWIN could find your startup class.

<appSettings>
    <!-- other setting here -->
    <add key="owin:AppStartup" value="MyAppNamespace.IdentityConfig" />
</appSettings>

Now in entire project you could use Identity just like any new project had already installed by VS. Consider login action for example

[HttpPost]
public ActionResult Login(LoginViewModel login)
{
    if (ModelState.IsValid)
    {
        var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
        var authManager = HttpContext.GetOwinContext().Authentication;

        AppUser user = userManager.Find(login.UserName, login.Password);
        if (user != null)
        {
            var ident = userManager.CreateIdentity(user, 
                DefaultAuthenticationTypes.ApplicationCookie);
            //use the instance that has been created. 
            authManager.SignIn(
                new AuthenticationProperties { IsPersistent = false }, ident);
            return Redirect(login.ReturnUrl ?? Url.Action("Index", "Home"));
        }
    }
    ModelState.AddModelError("", "Invalid username or password");
    return View(login);
}

You could make roles and add to your users:

public ActionResult CreateRole(string roleName)
{
    var roleManager=HttpContext.GetOwinContext().GetUserManager<RoleManager<AppRole>>();

    if (!roleManager.RoleExists(roleName))
        roleManager.Create(new AppRole(roleName));
    // rest of code
} 

You could also add a role to a user, like this:

UserManager.AddToRole(UserManager.FindByName("username").Id, "roleName");

By using Authorize you could guard your actions or controllers:

[Authorize]
public ActionResult MySecretAction() {}

or

[Authorize(Roles = "Admin")]]
public ActionResult MySecretAction() {}

You can also install additional packages and configure them to meet your requirement like Microsoft.Owin.Security.Facebook or whichever you want.

Note: Don't forget to add relevant namespaces to your files:

using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

You could also see my other answers like this and this for advanced use of Identity.

Regex in JavaScript for validating decimal numbers

Regex

/^\d+(\.\d{1,2})?$/

Demo

_x000D_
_x000D_
var regexp = /^\d+(\.\d{1,2})?$/;_x000D_
_x000D_
console.log("'.74' returns " + regexp.test('.74'));_x000D_
console.log("'7' returns " + regexp.test('7'));_x000D_
console.log("'10.5' returns " + regexp.test('10.5'));_x000D_
console.log("'115.25' returns " + regexp.test('115.25'));_x000D_
console.log("'1535.803' returns " + regexp.test('1535.803'));_x000D_
console.log("'153.14.5' returns " + regexp.test('153.14.5'));_x000D_
console.log("'415351108140' returns " + regexp.test('415351108140'));_x000D_
console.log("'415351108140.5' returns " + regexp.test('415351108140.5'));_x000D_
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));_x000D_
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));
_x000D_
_x000D_
_x000D_


Explanation

  1. / / : the beginning and end of the expression
  2. ^ : whatever follows should be at the beginning of the string you're testing
  3. \d+ : there should be at least one digit
  4. ( )? : this part is optional
  5. \. : here goes a dot
  6. \d{1,2} : there should be between one and two digits here
  7. $ : whatever precedes this should be at the end of the string you're testing

Tip

You can use regexr.com or regex101.com for testing regular expressions directly in the browser!

Can't resolve module (not found) in React.js

I think it may help you-

Read your error carefully-./src/App.js Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

just write- ./header/header instead ./src/components/header/header in App.js

if it doesnt work try to change header file name may be head

How can I create a self-signed cert for localhost?

I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.

Swift how to sort array of custom objects by property value

Swift 3

people = people.sorted(by: { $0.email > $1.email })

How to pass a variable to the SelectCommand of a SqlDataSource?

You need to define a valid type of SelectParameter. This MSDN article describes the various types and how to use them.

Trying to get property of non-object MySQLi result

Just thought I would expand on this a bit.

If you perform a MYSQLI SELECT query that returns 0 results, it returns FALSE.

However, if you get this error and you have written your own MYSQLI Query function, then you can also get this error if the query you are running is not a select but an update. An update query will return either TRUE or FALSE. So if you just assume that any non false result will have records returned, then you will trip up when you run an update or anything other than select.

The easiest solution, once you have checked that its not false, is to first check that the result of the query is an object.

    $sqlResult = $connection->query($sql);
    if (!$sqlResult)
    {
     ... 
    }
    else if (is_object($sqlResult))
    {
        $sqlRowCount = $sqlResult->num_rows;
    }
    else
    {
        $sqlRowCount = 0;
    }

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

for the maven users, comment the scope provided in the following dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <!--<scope>provided</scope>-->
    </dependency>

UPDATE

As feed.me mentioned you have to uncomment the provided part depending on what kind of app you are deploying.

Here is a useful link with the details: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging

What does FETCH_HEAD in Git mean?

FETCH_HEAD is a short-lived ref, to keep track of what has just been fetched from the remote repository. git pull first invokes git fetch, in normal cases fetching a branch from the remote; FETCH_HEAD points to the tip of this branch (it stores the SHA1 of the commit, just as branches do). git pull then invokes git merge, merging FETCH_HEAD into the current branch.

The result is exactly what you'd expect: the commit at the tip of the appropriate remote branch is merged into the commit at the tip of your current branch.

This is a bit like doing git fetch without arguments (or git remote update), updating all your remote branches, then running git merge origin/<branch>, but using FETCH_HEAD internally instead to refer to whatever single ref was fetched, instead of needing to name things.

window.close() doesn't work - Scripts may close only the windows that were opened by it

Error messages don't get any clearer than this:

"Scripts may close only the windows that were opened by it."

If your script did not initiate opening the window (with something like window.open), then the script in that window is not allowed to close it. Its a security to prevent a website taking control of your browser and closing windows.

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Remove all child elements of a DOM node in JavaScript

Other ways in jQuery

var foo = $("#foo");
foo.children().remove();
//or
$("*", foo ).remove();
//or
foo.html("");
//or
foo.empty();

What is the best open-source java charting library? (other than jfreechart)

There aren't a lot of them because they would be in competition with JFreeChart, and it's awesome. You can get documentation and examples by downloading the developer's guide. There are also tons of free online tutorials if you search for them.

How to gettext() of an element in Selenium Webdriver

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();
System.out.println(Txt);

AngularJS access scope from outside js function

This is how I did for my CRUDManager class initialized in Angular controller, which later passed over to jQuery button-click event defined outside the controller:

In Angular Controller:

        // Note that I can even pass over the $scope to my CRUDManager's constructor.
        var crudManager = new CRUDManager($scope, contextData, opMode);

        crudManager.initialize()
            .then(() => {
                crudManager.dataBind();
                $scope.crudManager = crudManager;
                $scope.$apply();
            })
            .catch(error => {
                alert(error);
            });

In jQuery Save button click event outside the controller:

    $(document).on("click", "#ElementWithNgControllerDefined #btnSave", function () {
        var ngScope = angular.element($("#ElementWithNgControllerDefined")).scope();
        var crudManager = ngScope.crudManager;
        crudManager.saveData()
            .then(finalData => {
               alert("Successfully saved!");
            })
            .catch(error => {
               alert("Failed to save.");
            });
    });

This is particularly important and useful when your jQuery events need to be placed OUTSIDE OF CONTROLLER in order to prevent it from firing twice.

How can a file be copied?

For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file.

for line in open("file.txt", "r"):
    list.append(line)
    if len(list) == 1000000: 
        output.writelines(list)
        del list[:]

Numpy where function multiple conditions

The best way in your particular case would just be to change your two criteria to one criterion:

dists[abs(dists - r - dr/2.) <= dr/2.]

It only creates one boolean array, and in my opinion is easier to read because it says, is dist within a dr or r? (Though I'd redefine r to be the center of your region of interest instead of the beginning, so r = r + dr/2.) But that doesn't answer your question.


The answer to your question:
You don't actually need where if you're just trying to filter out the elements of dists that don't fit your criteria:

dists[(dists >= r) & (dists <= r+dr)]

Because the & will give you an elementwise and (the parentheses are necessary).

Or, if you do want to use where for some reason, you can do:

 dists[(np.where((dists >= r) & (dists <= r + dr)))]

Why:
The reason it doesn't work is because np.where returns a list of indices, not a boolean array. You're trying to get and between two lists of numbers, which of course doesn't have the True/False values that you expect. If a and b are both True values, then a and b returns b. So saying something like [0,1,2] and [2,3,4] will just give you [2,3,4]. Here it is in action:

In [230]: dists = np.arange(0,10,.5)
In [231]: r = 5
In [232]: dr = 1

In [233]: np.where(dists >= r)
Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),)

In [234]: np.where(dists <= r+dr)
Out[234]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

In [235]: np.where(dists >= r) and np.where(dists <= r+dr)
Out[235]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

What you were expecting to compare was simply the boolean array, for example

In [236]: dists >= r
Out[236]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True], dtype=bool)

In [237]: dists <= r + dr
Out[237]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

In [238]: (dists >= r) & (dists <= r + dr)
Out[238]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

Now you can call np.where on the combined boolean array:

In [239]: np.where((dists >= r) & (dists <= r + dr))
Out[239]: (array([10, 11, 12]),)

In [240]: dists[np.where((dists >= r) & (dists <= r + dr))]
Out[240]: array([ 5. ,  5.5,  6. ])

Or simply index the original array with the boolean array using fancy indexing

In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. ,  5.5,  6. ])

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

Pagination on a list using ng-repeat

I've built a module that makes in-memory pagination incredibly simple.

It allows you to paginate by simply replacing ng-repeat with dir-paginate, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>

To take the original example asked by Tomarto, it would look like this:

<ul class='phones'>
    <li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
            <a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
            <a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
            <p>{{phone.snippet}}</p>
    </li>
</ul>

<dir-pagination-controls></dir-pagination-controls>

There is no need for any special pagination code in your controller. It's all handled internally by the module.

Demo: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview

Source: dirPagination of GitHub

Using XPATH to search text containing &nbsp;

I found I can make the match when I input a hard-coded non-breaking space (U+00A0) by typing Alt+0160 on Windows between the two quotes...

//table[@id='TableID']//td[text()=' ']

worked for me with the special char.

From what I understood, the XPath 1.0 standard doesn't handle escaping Unicode chars. There seems to be functions for that in XPath 2.0 but it looks like Firefox doesn't support it (or I misunderstood something). So you have to do with local codepage. Ugly, I know.

Actually, it looks like the standard is relying on the programming language using XPath to provide the correct Unicode escape sequence... So, somehow, I did the right thing.

Localhost not working in chrome and firefox

For Firefox:

  1. Go to LAN Settings: Options->Advanced->Network. In the "Connection" section of the "Network" tab press "Settings" button to open "Connection Settings" dialog box.
  2. Select "Manual proxy configuration:" radio button
  3. The "No proxy for:" textbox should contain the following text: "localhost, 127.0.0.1"

How can I make a JUnit test wait?

Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.

If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.

To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.

It has a nice fluent api as well

await().until(() -> 
{
    return yourConditionIsMet();
});  

https://github.com/jayway/awaitility

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

size of struct in C

As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.

PySpark: withColumn() with two conditions and three outcomes

You'll want to use a udf as below

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def func(fruit1, fruit2):
    if fruit1 == None or fruit2 == None:
        return 3
    if fruit1 == fruit2:
        return 1
    return 0

func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))

Visual Studio 2015 or 2017 does not discover unit tests

  1. Update nunit.framework to latest version.
  2. Download nunit test adapter from nuget
  3. Restart Visual studio

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

In SQL Server, what does "SET ANSI_NULLS ON" mean?

SET ANSI_NULLS ON

IT Returns all values including null values in the table

SET ANSI_NULLS off

it Ends when columns contains null values

Google reCAPTCHA: How to get user response and validate in the server side?

The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.

But that does not keep your site safe from HTTP client request forgery.

Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.

In human speech it would be like,

  • Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as a proof of that.
  • Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
  • Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
  • Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.

Validating the response is really easy. Just make a GET Request to

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

And replace the response_string with the value that you earlier got by the g-recaptcha-response field.

You will get a JSON Response with a success field.

More information here: https://developers.google.com/recaptcha/docs/verify

Edit: It's actually a POST, as per documentation here.

Difference between @Mock and @InjectMocks

Though the above answers have covered, I have just tried to add minute detail s which i see missing. The reason behind them(The Why).

enter image description here


Illustration:

Sample.java
---------------
    public class Sample{
        DependencyOne dependencyOne;
        DependencyTwo dependencyTwo;


        public SampleResponse methodOfSample(){
            dependencyOne.methodOne();
            dependencyTwo.methodTwo();

            ...

            return sampleResponse;
        }
    }

SampleTest.java
-----------------------
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassA.class})
public class SampleTest{

    @InjectMocks
    Sample sample;

    @Mock
    DependencyOne dependencyOne;

    @Mock
    DependencyTwo dependencyTwo;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    public void sampleMethod1_Test(){
        //Arrange the dependencies
        DependencyResponse dependencyOneResponse = Mock(sampleResponse.class);
        Mockito.doReturn(dependencyOneResponse).when(dependencyOne).methodOne();

        DependencyResponse dependencyTwoResponse = Mock(sampleResponse.class);
        Mockito.doReturn(dependencyOneResponse).when(dependencyTwo).methodTwo();

        //call the method to be tested
        SampleResponse sampleResponse = sample.methodOfSample() 

        //Assert
        <assert the SampleResponse here>
    }
}

Reference

What's the fastest way to do a bulk insert into Postgres?

One way to speed things up is to explicitly perform multiple inserts or copy's within a transaction (say 1000). Postgres's default behavior is to commit after each statement, so by batching the commits, you can avoid some overhead. As the guide in Daniel's answer says, you may have to disable autocommit for this to work. Also note the comment at the bottom that suggests increasing the size of the wal_buffers to 16 MB may also help.

Open links in new window using AngularJS

I wrote a small gist which I think can be very helpful to anybody seeking a solution to that problem: external link

What it does is it adds target="_blank" attributes to anchor elements that would link to a domain different than the current one. You can patch it up to whatever you see fit.

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

Call apply-like function on each row of dataframe with multiple arguments from each row

Here is an alternate approach. It is more intuitive.

One key aspect I feel some of the answers did not take into account, which I point out for posterity, is apply() lets you do row calculations easily, but only for matrix (all numeric) data

operations on columns are possible still for dataframes:

as.data.frame(lapply(df, myFunctionForColumn()))

To operate on rows, we make the transpose first.

tdf<-as.data.frame(t(df))
as.data.frame(lapply(tdf, myFunctionForRow()))

The downside is that I believe R will make a copy of your data table. Which could be a memory issue. (This is truly sad, because it is programmatically simple for tdf to just be an iterator to the original df, thus saving memory, but R does not allow pointer or iterator referencing.)

Also, a related question, is how to operate on each individual cell in a dataframe.

newdf <- as.data.frame(lapply(df, function(x) {sapply(x, myFunctionForEachCell()}))

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

For completness sake I included what my issue was and how I solved it:

If your like me and have httphandlers via web.config and you have redirects from your global.asax.cs (maybe in Session_Start() ) like in my case you get this error if your startup project does not have a reference defined which points to the target where your httphandler is pointing!! (but you wont get build errors, just runtime errors)

So:

  1. Double check your web.config for any external items
  2. Double check your startup project has all the references it needs.

Cheers.

In C - check if a char exists in a char array

strchr for searching a char from start (strrchr from the end):

  char str[] = "This is a sample string";

  if (strchr(str, 'h') != NULL) {
      /* h is in str */
  }

Writing data into CSV file in C#

enter code here

string string_value= string.Empty;

        for (int i = 0; i < ur_grid.Rows.Count; i++)
        {
            for (int j = 0; j < ur_grid.Rows[i].Cells.Count; j++)
            {
                if (!string.IsNullOrEmpty(ur_grid.Rows[i].Cells[j].Text.ToString()))
                {
                    if (j > 0)
                        string_value= string_value+ "," + ur_grid.Rows[i].Cells[j].Text.ToString();
                    else
                    {
                        if (string.IsNullOrEmpty(string_value))
                            string_value= ur_grid.Rows[i].Cells[j].Text.ToString();
                        else
                            string_value= string_value+ Environment.NewLine + ur_grid.Rows[i].Cells[j].Text.ToString();
                    }
                }
            }
        }


        string where_to_save_file = @"d:\location\Files\sample.csv";
        File.WriteAllText(where_to_save_file, string_value);

        string server_path = "/site/Files/sample.csv";
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(server_path));
        Response.WriteFile(server_path);
        Response.End();

Problems installing the devtools package

I hit this issue with Ubuntu 18.04 and none of the previous answers solved it. Eventually I succeeded by installing devtools with the package manager itself:

sudo apt install r-cran-devtools

How to get the first five character of a String

Try below code

 string Name = "Abhishek";
 string firstfour = Name.Substring(0, 4);
 Response.Write(firstfour);

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

In windows , [Similar scenario]

I was facing the same problem But It was during requesting for Certificate Signing Request.

I did the below , It Worked for me.

Once OpenSSL installed, Ran command prompt as administrator after the system reboot.[for the best I did both.. run as admin and system reboot]

did, 1.[Error Case]

C:\OpenSSL-Win64\bin>openssl req -new -key server.key -out server.csr

WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf AND Unable to load config info from C:\OpenSSL-Win64\bin\openssl.cnf

2.[Worked with Warning]

C:\OpenSSL-Win64\bin> openssl req -new -key server.key -out server.csr -config C:\OpenSSL-Win64\bin\openssl.cfg

[Warning message]: WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf

But prompted me for the Pass Phrase for server.key It worked for me.

I referred,This link for my assistance.

Thank you.

How to check if image exists with given url?

Use the error handler like this:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Update:

I think using:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

would be enough to check for a 404.

More Readings:

Update 2:

Your code should be like this:

$(this).error(function() {
  alert('Image does not exist !!');
});

No need for these lines and that won't check if the remote file exists anyway:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

MessageBodyWriter not found for media type=application/json

I was able to fix it by install jersey-media-json-jackson

Add the dependency to pom.xml

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <scope>runtime</scope>
</dependency>

How to get an isoformat datetime string including the default timezone?

With arrow:

>>> import arrow
>>> arrow.now().isoformat()
'2015-04-17T06:36:49.463207-05:00'
>>> arrow.utcnow().isoformat()
'2015-04-17T11:37:17.042330+00:00'

Git 'fatal: Unable to write new index file'

I had/have this problem too. In my case, none of the explanations applied:

  • enough disk room
  • I had sufficient privileges, I can write the index file, I can rename it, I can create it, the workaround did nothing
  • restarting windows didn't work
  • index not locked by processes

Until I found out that once I accessed the windows folder via another (linux) computer, git worked without complaints. It must have something to do with the git version I use from my normal debian buster computer: git 1.2.20 is giving me the 'unable to write new index' error, whereas from a ubuntu fuzzy virtualbox (git 1.2.2) adds the file without problems.

Trying to add adb to PATH variable OSX

If anyone can't seem to get there .bash_profile file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.

That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.

Moment get current date

Just call moment as a function without any arguments:

moment()

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

Jenkins: Is there any way to cleanup Jenkins workspace?

Beside above solutions, there is a more "COMMON" way - directly delete the largest space consumer from Linux machine. You can follow the below steps:

  1. Login to Jenkins machine (Putty) enter image description here
  2. cd to the Jenkins installation path

Using ls -lart to list out hidden folder also, normally jenkin installation is placed in .jenkins/ folder

[xxxxx ~]$ ls -lart

drwxrwxr-x 12 xxxx  4096 Feb  8 02:08 .jenkins/
  1. list out the folders spaces

Use df -h to show Disk space in high level

du -sh ./*/ to list out total memory for each subfolder in current path.

du -a /etc/ | sort -n -r | head -n 10 will list top 10 directories eating disk space in /etc/

  1. Delete old build or other large size folder

Normally ./job/ folder or ./workspace/ folder can be the largest folder. Please go inside and delete base on you need (DO NOT delete entire folder).

rm -rf theFolderToDelete

enter image description here

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

How get data from material-ui TextField, DropDownMenu components?

Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :

      create(e) {
        e.preventDefault();
        let name = this.refs.name.input.value;
        alert(name);
      }

      constructor(){
        super();
        this.create = this.create.bind(this);
      }

      render() {
        return (
              <form>
                <TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
                <RaisedButton label="Create" onClick={this.create} primary={true} />
              </form>
        )}

hope this helps.

Single quotes vs. double quotes in Python

I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.

Best way to encode text data for XML

XmlTextWriter.WriteString() does the escaping.

No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

$ brew install lua

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

convert epoch time to date

EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(1318386508000L);
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        String formatted = format.format(date);
        System.out.println(formatted);
        format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
        formatted = format.format(date);
        System.out.println(formatted);
    }
}

Output:

12/10/2011 02:28:28
12/10/2011 13:28:28

I would also suggest you start using Joda Time which is simply a much nicer date/time API...

EDIT: Note that if your system doesn't know about the Australia/Sydney time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah") it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName() and see what it says... and check your code for typos too :)

What's the best way to store a group of constants that my program uses?

This is the best way IMO. No need for properties, or readonly:

public static class Constants
{
   public const string SomeConstant = "Some value";
}

Printing an array in C++?

May I suggest using the fish bone operator?

for (auto x = std::end(a); x != std::begin(a); )
{
    std::cout <<*--x<< ' ';
}

(Can you spot it?)

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I am just answering here with the formatted version of the final sql I needed based on Bob Jarvis answer as posted in my comment above:

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select author_id, count(1) as total_count
              from names
              group by author_id) n2
  on (n2.author_id = n1.author_id)

Test if element is present using Selenium WebDriver?

Write the following function/methos using Java:

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

Call the method with appropriate parameter during assertion.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Vuejs: Event on route change

Watcher with the deep option didn't work for me.

Instead, I use updated() lifecycle hook which gets executed everytime the component's data changes. Just use it like you do with mounted().

mounted() {
   /* to be executed when mounted */
},
updated() {
   console.log(this.$route)
}

For your reference, visit the documentation.

VBA collection: list of keys

I don't thinks that possible with a vanilla collection without storing the key values in an independent array.

The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead:

Dim dict As Dictionary
Set dict = New Dictionary

dict.Add "key1", "value1"
dict.Add "key2", "value2"

Dim key As Variant
For Each key In dict.Keys
    Debug.Print "Key: " & key, "Value: " & dict.Item(key)
Next

Set disable attribute based on a condition for Html.TextBoxFor

I like the extension method approach so you don't have to pass through all possible parameters.
However using Regular expressions can be quite tricky (and somewhat slower) so I used XDocument instead:

public static MvcHtmlString SetDisabled(this MvcHtmlString html, bool isDisabled)
{
    var xDocument = XDocument.Parse(html.ToHtmlString());
    if (!(xDocument.FirstNode is XElement element))
    {
        return html;
    }

    element.SetAttributeValue("disabled", isDisabled ? "disabled" : null);
    return MvcHtmlString.Create(element.ToString());
}

Use the extension method like this:
@Html.EditorFor(m => m.MyProperty).SetDisabled(Model.ExpireDate == null)

How to add days to the current date?

This will give total number of days including today in the current month.

select day(getDate())

How can I limit ngFor repeat to some number of items in Angular?

For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:

<ul>
     <li *ngFor="let item of items | slice:0:10">
      {{ item }}
     </li>
</ul>

Zip lists in Python

I don't think zip returns a list. zip returns a generator. You have got to do list(zip(a, b)) to get a list of tuples.

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

How to close IPython Notebook properly?

Try killing the pythonw process from the Task Manager (if Windows) if nothing else works.

Apache redirect to another port

This is working in ISPConfig too. In website list get inside a domain, click to Options tab, add these lines: ;

ProxyPass / http://localhost:8181/
ProxyPassReverse / http://localhost:8181/

Then go to website and wolaa :) This is working HTTPS protocol too.

How to insert new cell into UITableView in Swift

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

First of all, append data in your tableview array

Yourarray.append([labeltext])  

Then update your table and insert a new row

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()

Objective-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];

How do I get an element to scroll into view, using jQuery?

After trying to find a solution that handled every circumstance (options for animating the scroll, padding around the object once it scrolls into view, works even in obscure circumstances such as in an iframe), I finally ended up writing my own solution to this. Since it seems to work when many other solutions failed, I thought I'd share it:

function scrollIntoViewIfNeeded($target, options) {

    var options = options ? options : {},
    $win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
    $container = options.$container ? options.$container : $win,        
    padding = options.padding ? options.padding : 20,
    elemTop = $target.offset().top,
    elemHeight = $target.outerHeight(),
    containerTop = $container.scrollTop(),
    //Everything past this point is used only to get the container's visible height, which is needed to do this accurately
    containerHeight = $container.outerHeight(),
    winTop = $win.scrollTop(),
    winBot = winTop + $win.height(),
    containerVisibleTop = containerTop < winTop ? winTop : containerTop,
    containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
    containerVisibleHeight = containerVisibleBottom - containerVisibleTop;

    if (elemTop < containerTop) {
        //scroll up
        if (options.instant) {
            $container.scrollTop(elemTop - padding);
        } else {
            $container.animate({scrollTop: elemTop - padding}, options.animationOptions);
        }
    } else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
        //scroll down
        if (options.instant) {
            $container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
        } else {
            $container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
        }
    }
}

$target is a jQuery object containing the object you wish to scroll into view if needed.

options (optional) can contain the following options passed in an object:

options.$container - a jQuery object pointing to the containing element of $target (in other words, the element in the dom with the scrollbars). Defaults to the window that contains the $target element and is smart enough to select an iframe window. Remember to include the $ in the property name.

options.padding - the padding in pixels to add above or below the object when it is scrolled into view. This way it is not right against the edge of the window. Defaults to 20.

options.instant - if set to true, jQuery animate will not be used and the scroll will instantly pop to the correct location. Defaults to false.

options.animationOptions - any jQuery options you wish to pass to the jQuery animate function (see http://api.jquery.com/animate/). With this, you can change the duration of the animation or have a callback function executed when the scrolling is complete. This only works if options.instant is set to false. If you need to have an instant animation but with a callback, set options.animationOptions.duration = 0 instead of using options.instant = true.

React Native: Getting the position of an element

I had a similar problem and solved it by combining the answers above

class FeedPost extends React.Component {
  constructor(props) {
    ...
    this.handleLayoutChange = this.handleLayoutChange.bind(this);
  }


handleLayoutChange() {
    this.feedPost.measure( (fx, fy, width, height, px, py) => {
      console.log('Component width is: ' + width)
      console.log('Component height is: ' + height)
      console.log('X offset to page: ' + px)
      console.log('Y offset to page: ' + py)
    })
  }

  render {
    return(
      <View onLayout={(event) => {this.handleLayoutChange(event) }} 
      ref={view => { this.feedPost = view; }} >
...

Now I can see the position of my feedPost element in the logs:

08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component width is: 156
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component height is: 206
08-24 11:15:36.838  3727 27838 I ReactNativeJS: X offset to page: 188
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Y offset to page: 870

2D arrays in Python

>>> a = []

>>> for i in xrange(3):
...     a.append([])
...     for j in xrange(3):
...             a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>

Polymorphism vs Overriding vs Overloading

what is polymorphism?

From java tutorial

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

By considering the examples and definition, overriding should be accepted answer.

Regarding your second query:

IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?

It should be called overriding.

Have a look at this example to understand different types of overriding.

  1. Base class provides no implementation and sub-class has to override complete method - (abstract)
  2. Base class provides default implementation and sub-class can change the behaviour
  3. Sub-class adds extension to base class implementation by calling super.methodName() as first statement
  4. Base class defines structure of the algorithm (Template method) and sub-class will override a part of algorithm

code snippet:

import java.util.HashMap;

abstract class Game implements Runnable{

    protected boolean runGame = true;
    protected Player player1 = null;
    protected Player player2 = null;
    protected Player currentPlayer = null;

    public Game(){
        player1 = new Player("Player 1");
        player2 = new Player("Player 2");
        currentPlayer = player1;
        initializeGame();
    }

    /* Type 1: Let subclass define own implementation. Base class defines abstract method to force
        sub-classes to define implementation    
    */

    protected abstract void initializeGame();

    /* Type 2: Sub-class can change the behaviour. If not, base class behaviour is applicable */
    protected void logTimeBetweenMoves(Player player){
        System.out.println("Base class: Move Duration: player.PlayerActTime - player.MoveShownTime");
    }

    /* Type 3: Base class provides implementation. Sub-class can enhance base class implementation by calling
        super.methodName() in first line of the child class method and specific implementation later */
    protected void logGameStatistics(){
        System.out.println("Base class: logGameStatistics:");
    }
    /* Type 4: Template method: Structure of base class can't be changed but sub-class can some part of behaviour */
    protected void runGame() throws Exception{
        System.out.println("Base class: Defining the flow for Game:");  
        while ( runGame) {
            /*
            1. Set current player
            2. Get Player Move
            */
            validatePlayerMove(currentPlayer);  
            logTimeBetweenMoves(currentPlayer);
            Thread.sleep(500);
            setNextPlayer();
        }
        logGameStatistics();
    }
    /* sub-part of the template method, which define child class behaviour */
    protected abstract void validatePlayerMove(Player p);

    protected void setRunGame(boolean status){
        this.runGame = status;
    }
    public void setCurrentPlayer(Player p){
        this.currentPlayer = p;
    }
    public void setNextPlayer(){
        if ( currentPlayer == player1) {
            currentPlayer = player2;
        }else{
            currentPlayer = player1;
        }
    }
    public void run(){
        try{
            runGame();
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

class Player{
    String name;
    Player(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}

/* Concrete Game implementation  */
class Chess extends Game{
    public Chess(){
        super();
    }
    public void initializeGame(){
        System.out.println("Child class: Initialized Chess game");
    }
    protected void validatePlayerMove(Player p){
        System.out.println("Child class: Validate Chess move:"+p.getName());
    }
    protected void logGameStatistics(){
        super.logGameStatistics();
        System.out.println("Child class: Add Chess specific logGameStatistics:");
    }
}
class TicTacToe extends Game{
    public TicTacToe(){
        super();
    }
    public void initializeGame(){
        System.out.println("Child class: Initialized TicTacToe game");
    }
    protected void validatePlayerMove(Player p){
        System.out.println("Child class: Validate TicTacToe move:"+p.getName());
    }
}

public class Polymorphism{
    public static void main(String args[]){
        try{

            Game game = new Chess();
            Thread t1 = new Thread(game);
            t1.start();
            Thread.sleep(1000);
            game.setRunGame(false);
            Thread.sleep(1000);

            game = new TicTacToe();
            Thread t2 = new Thread(game);
            t2.start();
            Thread.sleep(1000);
            game.setRunGame(false);

        }catch(Exception err){
            err.printStackTrace();
        }       
    }
}

output:

Child class: Initialized Chess game
Base class: Defining the flow for Game:
Child class: Validate Chess move:Player 1
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Child class: Validate Chess move:Player 2
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Base class: logGameStatistics:
Child class: Add Chess specific logGameStatistics:
Child class: Initialized TicTacToe game
Base class: Defining the flow for Game:
Child class: Validate TicTacToe move:Player 1
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Child class: Validate TicTacToe move:Player 2
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Base class: logGameStatistics:

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):

https://login.minecraft.net?user=<username>&password=<password>&version=13

You'll get a response like this:

1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98

The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to minecraft.net in C#.

Returning value that was passed into a method

You can use a lambda with an input parameter, like so:

.Returns((string myval) => { return myval; });

Or slightly more readable:

.Returns<string>(x => x);

Get underlined text with Markdown

In GitHub markdown <ins>text</ins>works just fine.

How to find my Subversion server version number?

Browse the repository with Firefox and inspect the element with Firebug. Under the NET tab, you can check the Header of the page. It will have something like:

Server: Apache/2.2.14 (Win32) DAV/2 SVN/1.X.X

Java converting int to hex and back again

Hehe, curious. I think this is an "intentianal bug", so to speak.

The underlying reason is how the Integer class is written. Basically, parseInt is "optimized" for positive numbers. When it parses the string, it builds the result cumulatively, but negated. Then it flips the sign of the end-result.

Example:

66 = 0x42

parsed like:

4*(-1) = -4
-4 * 16 = -64 (hex 4 parsed)

-64 - 2 = -66 (hex 2 parsed)

return -66 * (-1) = 66

Now, let's look at your example FFFF8000

16*(-1) = -16 (first F parsed)
-16*16 = -256 

-256 - 16 = -272 (second F parsed)
-272 * 16 = -4352 

-4352 - 16 = -4368 (third F parsed)
-4352 * 16 = -69888

-69888 - 16 = -69904 (forth F parsed)
-69904 * 16 = -1118464 

-1118464 - 8 = -1118472 (8 parsed)
-1118464 * 16 = -17895552 

-17895552 - 0 = -17895552 (first 0 parsed)
Here it blows up since -17895552 < -Integer.MAX_VALUE / 16 (-134217728). 
Attempting to execute the next logical step in the chain (-17895552 * 16)
would cause an integer overflow error.

Edit (addition): in order for the parseInt() to work "consistently" for -Integer.MAX_VALUE <= n <= Integer.MAX_VALUE, they would have had to implement logic to "rotate" when reaching -Integer.MAX_VALUE in the cumulative result, starting over at the max-end of the integer range and continuing downwards from there. Why they did not do this, one would have to ask Josh Bloch or whoever implemented it in the first place. It might just be an optimization.

However,

Hex=Integer.toHexString(Integer.MAX_VALUE);
System.out.println(Hex);
System.out.println(Integer.parseInt(Hex.toUpperCase(), 16));

works just fine, for just this reason. In the sourcee for Integer you can find this comment.

// Accumulating negatively avoids surprises near MAX_VALUE

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

If you are receiving that error even after creating a new user and assigning them the database previledges, then the one last thing to look at is to check if the users have been assigned the preiveledges in the database.

To do this log into to your mysql(This is presumably its the application that has restricted access to the database but you as a root can be ablr to access your database table via mysql -u user -p)

commands to apply

mysql -u root -p 

password: (provide your database credentials)

on successful login

type

use mysql;

from this point check each users priveledges if it is enabled from the db table as follows

select User,Grant_priv,Host from db;

if the values of the Grant_priv col for the created user is N update that value to Y with the following command

UPDATE db SET Grant_priv = "Y" WHERE User= "your user";

with that now try accessing the app and making a transaction with the database.

How to configure log4j.properties for SpringJUnit4ClassRunner?

The new tests you wrote (directly or indirectly) use classes that log using Log4j.

Log4J needs to be configured for this logging to work properly.

Put a log4j.properties (or log4j.xml) file in the root of your test classpath.

It should have some basic configuration such as

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

An appender outputs to the console by default, but you can also explicitly set the target like this:

log4j.appender.A1.Target=System.out

This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,

Log4J Logging will then be properly configured and this warning will disappear.

How to float 3 divs side by side using CSS?

Here's how I managed to do something similar to this inside a <footer> element:

<div class="content-wrapper">

    <div style="float:left">
        <p>&copy; 2012 - @DateTime.Now.Year @Localization.ClientName</p>
    </div>

    <div style="float:right">
        <p>@Localization.DevelopedBy <a href="http://leniel.net" target="_blank">Leniel Macaferi</a></p>
    </div>

    <div style="text-align:center;">
        <p>? (24) 3347-3110 | (24) 8119-1085&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;? @Html.ActionLink(Localization.Contact, MVC.Home.ActionNames.Contact, MVC.Home.Name)</p>
    </div>

</div>

CSS:

.content-wrapper
{
    margin: 0 auto;
    max-width: 1216px;
}

The action or event has been blocked by Disabled Mode

Try and see if this works:

  1. Click on 'External Data' tab
  2. There should be a Security Warning that states "Certain content in the database has been disabled"
  3. Click the 'Options' button
  4. Select 'Enable this content' and click the OK button

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

How do I check if a string contains another string in Swift?

Here you go! Ready for Xcode 8 and Swift 3.

import UIKit

let mString = "This is a String that contains something to search."
let stringToSearchUpperCase = "String"
let stringToSearchLowerCase = "string"

mString.contains(stringToSearchUpperCase) //true
mString.contains(stringToSearchLowerCase) //false
mString.lowercased().contains(stringToSearchUpperCase) //false
mString.lowercased().contains(stringToSearchLowerCase) //true

How to create PDF files in Python

I have done this quite a bit in PyQt and it works very well. Qt has extensive support for images, fonts, styles, etc and all of those can be written out to pdf documents.

Cross field validation with Hibernate Validator (JSR 303)

I like the idea from Jakub Jirutka to use Spring Expression Language. If you don't want to add another library/dependency (assuming that you already use Spring), here is a simplified implementation of his idea.

The constraint:

@Constraint(validatedBy=ExpressionAssertValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpressionAssert {
    String message() default "expression must evaluate to true";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String value();
}

The validator:

public class ExpressionAssertValidator implements ConstraintValidator<ExpressionAssert, Object> {
    private Expression exp;

    public void initialize(ExpressionAssert annotation) {
        ExpressionParser parser = new SpelExpressionParser();
        exp = parser.parseExpression(annotation.value());
    }

    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return exp.getValue(value, Boolean.class);
    }
}

Apply like this:

@ExpressionAssert(value="pass == passVerify", message="passwords must be same")
public class MyBean {
    @Size(min=6, max=50)
    private String pass;
    private String passVerify;
}

How to update PATH variable permanently from Windows command line?

This Python-script[*] does exactly that:

"""
Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes.

First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and 
if not accessible due to admin-rights missing, fails-back 
to HKEY_CURRENT_USER.
Write and Delete operations do not proceed to user-tree if all-users succeed.

Syntax: 
    {prog}                  : Print all env-vars. 
    {prog}  VARNAME         : Print value for VARNAME. 
    {prog}  VARNAME   VALUE : Set VALUE for VARNAME. 
    {prog}  +VARNAME  VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`). 
    {prog}  -VARNAME        : Delete env-var value. 

Note that the current command-window will not be affected, 
changes would apply only for new command-windows.
"""

import winreg
import os, sys, win32gui, win32con

def reg_key(tree, path, varname):
    return '%s\%s:%s' % (tree, path, varname) 

def reg_entry(tree, path, varname, value):
    return '%s=%s' % (reg_key(tree, path, varname), value)

def query_value(key, varname):
    value, type_id = winreg.QueryValueEx(key, varname)
    return value

def yield_all_entries(tree, path, key):
    i = 0
    while True:
        try:
            n,v,t = winreg.EnumValue(key, i)
            yield reg_entry(tree, path, n, v)
            i += 1
        except OSError:
            break ## Expected, this is how iteration ends.

def notify_windows(action, tree, path, varname, value):
    win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
    print("---%s %s" % (action, reg_entry(tree, path, varname, value)), file=sys.stderr)

def manage_registry_env_vars(varname=None, value=None):
    reg_keys = [
        ('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
        ('HKEY_CURRENT_USER', r'Environment'),
    ]
    for (tree_name, path) in reg_keys:
        tree = eval('winreg.%s'%tree_name)
        try:
            with winreg.ConnectRegistry(None, tree) as reg:
                with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key:
                    if not varname:
                        for regent in yield_all_entries(tree_name, path, key):
                            print(regent)
                    else:
                        if not value:
                            if varname.startswith('-'):
                                varname = varname[1:]
                                value = query_value(key, varname)
                                winreg.DeleteValue(key, varname)
                                notify_windows("Deleted", tree_name, path, varname, value)
                                break  ## Don't propagate into user-tree.
                            else:
                                value = query_value(key, varname)
                                print(reg_entry(tree_name, path, varname, value))
                        else:
                            if varname.startswith('+'):
                                varname = varname[1:]
                                value = query_value(key, varname) + ';' + value
                            winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value)
                            notify_windows("Updated", tree_name, path, varname, value)
                            break  ## Don't propagate into user-tree.
        except PermissionError as ex:
            print("!!!Cannot access %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)
        except FileNotFoundError as ex:
            print("!!!Cannot find %s due to: %s" % 
                    (reg_key(tree_name, path, varname), ex), file=sys.stderr)

if __name__=='__main__':
    args = sys.argv
    argc = len(args)
    if argc > 3:
        print(__doc__.format(prog=args[0]), file=sys.stderr)
        sys.exit()

    manage_registry_env_vars(*args[1:])

Below are some usage examples, assuming it has been saved in a file called setenv.py somewhere in your current path. Note that in these examples i didn't have admin-rights, so the changes affected only my local user's registry tree:

> REM ## Print all env-vars
> setenv.py
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
HKEY_CURRENT_USER\Environment:PATH=...
...

> REM ## Query env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
!!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified

> REM ## Set env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo

> REM ## Append env-var:
> setenv.py +PATH D:\Bar
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar

> REM ## Delete env-var:
> setenv.py -PATH
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session   Manager\Environment:PATH due to: [WinError 5] Access is denied
---Deleted HKEY_CURRENT_USER\Environment:PATH

[*] Adapted from: http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/

How to correctly represent a whitespace character

Using regular expressions, you can represent any whitespace character with the metacharacter "\s"

MSDN Reference

mysql query order by multiple items

SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;

PHP Fatal error: Class 'PDO' not found

you can just find-out loaded config file by executing below command,

 php -i | grep 'php.ini'

Then add below lines to correct php.ini file

extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so

Then restart web server,

service httpd restart

How to get the current branch name in Git?

You can just type in command line (console) on Linux, in the repository directory:

$ git status

and you will see some text, among which something similar to:

...
On branch master
...

which means you are currently on master branch. If you are editing any file at that moment and it is located in the same local repository (local directory containing the files that are under Git version control management), you are editing file in this branch.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

There is very good package available to parse the email contents with proper documentation.

import mailparser

mail = mailparser.parse_from_file(f)
mail = mailparser.parse_from_file_obj(fp)
mail = mailparser.parse_from_string(raw_mail)
mail = mailparser.parse_from_bytes(byte_mail)

How to Use:

mail.attachments: list of all attachments
mail.body
mail.to

How to upload files to server using JSP/Servlet?

DiskFileUpload upload=new DiskFileUpload();

From this object you have to get file items and fields then yo can store into server like followed:

String loc="./webapps/prjct name/server folder/"+contentid+extension;
File uploadFile=new File(loc);
item.write(uploadFile);

How to make a Bootstrap accordion collapse when clicking the header div?

Actually my panel had this collapse state arrow icon and I tried other answers in this post , but icon position changed, so here is the solution with collapse state arrow icon.

Add this Custom CSS

 .panel-heading 
  {
   cursor: pointer;
   padding: 0;
  }

 a.accordion-toggle 
 {
  display: block;
  padding: 10px  15px;
 }

Credit's goes to this post answerer.

Hope helps.

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

Taskkill /f doesn't kill a process

I am going to suggest something here because I recently faced the same issue and I tried every possible thing in the answers but nothing worked. I was getting errors like

ERROR: The process with PID 23908 could not be terminated. Reason: There is no running instance of the task.

using command prompt. Power shell wasn't helpful either. it would simply execute the commands and no response with process still running.

Until I decided to delete the associated '.exe' file. Since the file was active, windows would not allow the deletion, but in that warning window it gave me the name of the process which was holding up the task I wanted to kill. I was able to kill the original task and thus the buggy process.

It is definitely worth a try if none of the solutions works out.

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Why is visible="false" not working for a plain html table?

For the best practice - use style="display:"

it will work every where..

Bash function to find newest file matching pattern

The combination of find and ls works well for

  • filenames without newlines
  • not very large amount of files
  • not very long filenames

The solution:

find . -name "my-pattern" -print0 |
    xargs -r -0 ls -1 -t |
    head -1

Let's break it down:

With find we can match all interesting files like this:

find . -name "my-pattern" ...

then using -print0 we can pass all filenames safely to the ls like this:

find . -name "my-pattern" -print0 | xargs -r -0 ls -1 -t

additional find search parameters and patterns can be added here

find . -name "my-pattern" ... -print0 | xargs -r -0 ls -1 -t

ls -t will sort files by modification time (newest first) and print it one at a line. You can use -c to sort by creation time. Note: this will break with filenames containing newlines.

Finally head -1 gets us the first file in the sorted list.

Note: xargs use system limits to the size of the argument list. If this size exceeds, xargs will call ls multiple times. This will break the sorting and probably also the final output. Run

xargs  --show-limits

to check the limits on you system.

Note 2: use find . -maxdepth 1 -name "my-pattern" -print0 if you don't want to search files through subfolders.

Note 3: As pointed out by @starfry - -r argument for xargs is preventing the call of ls -1 -t, if no files were matched by the find. Thank you for the suggesion.

How do I reverse a commit in git?

I think you need to push a revert commit. So pull from github again, including the commit you want to revert, then use git revert and push the result.

If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset: git push origin :master.

How to check if an element is off-screen

You could check the position of the div using $(div).position() and check if the left and top margin properties are less than 0 :

if($(div).position().left < 0 && $(div).position().top < 0){
    alert("off screen");
}

Uninstall old versions of Ruby gems

Way to clean out any old versions of gems.

sudo gem cleanup

If you just want to see a list of what would be removed you can use:

sudo gem cleanup -d

You can also cleanup just a specific gem by specifying its name:

sudo gem cleanup gemname

for remove specific version like 1.1.9 only

gem uninstall gemname --version 1.1.9

If you still facing some exception to install gem, like:

invalid gem: package is corrupt, exception while verifying: undefined method `size' for nil:NilClass (NoMethodError) in /home/rails/.rvm/gems/ruby-2.1.1@project/cache/nokogiri-1.6.6.2.gem

the, you can remove it from cache:

rm /home/rails/.rvm/gems/ruby-2.1.1@project/cache/nokogiri-1.6.6.2.gem

For more detail:

http://blog.grepruby.com/2015/04/way-to-clean-up-gem-or-remove-old.html

Entry point for Java applications: main(), init(), or run()?

The main method is the entry point of a Java application.

Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java application launcher), it will look for the main method with the signature of public static void main(String[]).

From Sun's java command page:

The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration must look like the following:

public static void main(String args[])

For additional resources on how an Java application is executed, please refer to the following sources:

  1. Chapter 12: Execution from the Java Language Specification, Third Edition.
  2. Chapter 5: Linking, Loading, Initializing from the Java Virtual Machine Specifications, Second Edition.
  3. A Closer Look at the "Hello World" Application from the Java Tutorials.

The run method is the entry point for a new Thread or an class implementing the Runnable interface. It is not called by the Java Virutal Machine when it is started up by the java command.

As a Thread or Runnable itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start() method. This can be accomplished by instantiating a Thread and calling its start method in the main method of the application:

public class MyRunnable implements Runnable
{
    public void run()
    {
        System.out.println("Hello World!");
    }

    public static void main(String[] args)
    {
        new Thread(new MyRunnable()).start();
    }
}

For more information and an example of how to start a subclass of Thread or a class implementing Runnable, see Defining and Starting a Thread from the Java Tutorials.


The init method is the first method called in an Applet or JApplet.

When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init method. Any initializations that are required to use the applet should be executed here. After the init method is complete, the start method is called.

For more information about when the init method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.

See also: How to Make Applets from the Java Tutorial.

How do I register a .NET DLL file in the GAC?

I tried just about everything in the comments and it didn't work. So I did gacutil /i "path to my dll" from Powershell and it worked.

Also remember the trick of pressing Shift when you right-click on a file in Windows Explorer to get the option of Copy path.

How to import/include a CSS file using PHP code and not HTML code?

you can use:

<?php
$css = file_get_contents('CSS/main.css');
echo $css;
?>

and assuming that css file doesn't have it already, wrap the above in:

<style type="text/css">
...
</style>

How to check for registry value using VbScript

Try something like this:

Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")

Try-catch block in Jenkins pipeline script

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

How to detect a remote side socket close?

The isConnected method won't help, it will return true even if the remote side has closed the socket. Try this:

public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}

Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.

The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException (broken pipe) will be thrown) on the associated Input/OutputStreams.

Replace all whitespace characters

Actually it has been worked but

just try this.

take the value /\s/g into a string variable like

String a = /\s/g;

str = str.replaceAll(a,"X");

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

UNC path to a folder on my local computer

I had to:

Query grants for a table in postgres

I already found it:

SELECT grantee, privilege_type 
FROM information_schema.role_table_grants 
WHERE table_name='mytable'

twitter bootstrap text-center when in xs mode

html

<div class="text-lg-right text-center">
  center in xs and right in lg devices
</div>

How to remove an HTML element using Javascript?

Try running this code in your script.

document.getElementById("dummy").remove();

And it will hopefully remove the element/button.

Get the current cell in Excel VB

If you're trying to grab a range with a dynamically generated string, then you just have to build the string like this:

Range(firstcol & firstrow & ":" & secondcol & secondrow).Select

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as state.abc will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => {
  previousState.abc.xyz = 'blurg';
  return previousState;
});

Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);

ESLint - "window" is not defined. How to allow global variables in package.json

Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.

{
  "env": {
    "browser": true,
    "node": true
  }                                                                      
}

git pull keeping local changes

Incase their is local uncommitted changes and avoid merge conflict while pulling.

git stash save
git pull
git stash pop

refer - https://happygitwithr.com/pull-tricky.html

checked = "checked" vs checked = true

checked attribute is a boolean value so "checked" value of other "string" except boolean false converts to true.

Any string value will be true. Also presence of attribute make it true:

<input type="checkbox" checked>

You can make it uncheked only making boolean change in DOM using JS.

So the answer is: they are equal.

w3c

PHP CURL Enable Linux

It dipends on which distribution you are in general but... You have to install the php-curl module and then enable it on php.ini like you did in windows. Once you are done remember to restart apache demon!

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

Just Remove the the Workstation Components from Add/Remove Programs - SQL Server 2005. Removing Workstation Components, SQL Server 2008 installation goes well.

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

Is there a command line utility for rendering GitHub flavored Markdown?

GitHub has (since) developed a nice modular text editor called Atom (based on Chromium and uses Node.js modules for packages).

A default preinstalled package Markdown Preview lets you display your preview in a separate tab using Ctrl + Shift + M.

I haven't tested its full syntax, but since it's coming from GitHub, I'd be highly surprised if the preview's syntax was different from theirs (fenced blocks using ~~~ work).

Now, while it's not technically command-line based, it uses Node.js and outputs to a DOM-based renderer, which might help anyone trying to render GitHub syntax-based HTML on a Node.js-based webserver, or just edit her/his README.md offline.