Programs & Examples On #Digraphs

A 'digraph' means 'one symbol written as two characters'. In printing it meant two letters cast as one piece of lead, e.g. ae, fi, ...

Java: how to represent graphs?

Time ago I had the same problem and did my own implementation. What I suggest you is to implement another class: Edge. Then, a Vertex will have a List of Edge.

public class Edge {
    private Node a, b;
    private directionEnum direction;     // AB, BA or both
    private int weight;
    ...
}

It worked for me. But maybe is so simple. There is this library that maybe can help you if you look into its code: http://jgrapht.sourceforge.net/

How to show imageView full screen on imageView click?

public class MainActivity extends Activity {

ImageView imgV;

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

    imgV= (ImageView) findViewById("your Image View Id");

    imgV.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
                imgV.setScaleType(ScaleType.FIT_XY);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getSupportActionBar().hide();
            }
        }
    });

}
}

Programmatically add new column to DataGridView

Keep it simple

dataGridView1.Columns.Add("newColumnName", "Column Name in Text");

To add rows

dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]

Given an RGB value, how do I create a tint (or shade)?

Among several options for shading and tinting:

  • For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade.

  • For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.component is a 8-bit integer).

Note that color manipulations (such as tints and other shading) should be done in linear RGB. However, RGB colors specified in documents or encoded in images and video are not likely to be in linear RGB, in which case a so-called inverse transfer function needs to be applied to each of the RGB color's components. This function varies with the RGB color space. For example, in the sRGB color space (which can be assumed if the RGB color space is unknown), this function is roughly equivalent to raising each sRGB color component (ranging from 0 through 1) to a power of 2.2. (Note that "linear RGB" is not an RGB color space.)

See also Violet Giraffe's comment about "gamma correction".

Handling errors in Promise.all

ES2020 introduces new method for the Promise type: Promise.allSettled()
Promise.allSettled gives you a signal when all the input promises are settled, which means they’re either fulfilled or rejected. This is useful in cases where you don’t care about the state of the promise, you just want to know when the work is done, regardless of whether it was successful.

const promises = [
  fetch('/api-call-1'),
  fetch('/api-call-2'),
  fetch('/api-call-3'),
];
// Imagine some of these requests fail, and some succeed.

const result = await Promise.allSettled(promises);
console.log(result.map(x=>x.status));
// ['fulfilled', 'fulfilled', 'rejected']

Read more in the v8 blog post https://v8.dev/features/promise-combinators

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

Non-static variable cannot be referenced from a static context

To be able to access them from your static methods they need to be static member variables, like this:

public class MyProgram7 {
  static Scanner scan = new Scanner(System.in);
  static int compareCount = 0;
  static int low = 0;
  static int high = 0;
  static int mid = 0;  
  static int key = 0;  
  static Scanner temp;  
  static int[]list;  
  static String menu, outputString;  
  static int option = 1;  
  static boolean found = false;

  public static void main (String[]args) throws IOException {
  ...

How to execute an external program from within Node.js?

From the Node.js documentation:

Node provides a tri-directional popen(3) facility through the ChildProcess class.

See http://nodejs.org/docs/v0.4.6/api/child_processes.html

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

Had this problem a number of times on our setup, so I've made a check list.

This assumes you want phpMyAdmin connecting locally to MySQL using a UNIX socket rather than TCP/IP.

UNIX sockets should be slightly faster as they have less overhead and can be more secure as they can only be accessed locally.

Service

  • Is the mysqld service running? service mysqld status
  • .. If not service mysqld start
  • Has config has changed since service started? service mysqld restart

MySQL Config (my.cnf)

  • Check that there isn't a non-socket client protocol set, e.g. protocol=tcp
  • Check that the socket location is accessible and has the right permissions

PHP Config (php.ini)

If you can connect locally from the command line, but not from phpMyAdmin, and the socket file is not in the default location:

  • Set the mysqli default sockets to the new location: mysqli.default_socket = *location*
  • ... I also set the pdo_myql.default_socket and mysql.default_socket just to be sure
  • Restart your web service (httpd in my case) service httpd restart

phpMyAdmin Config (config.inc.php)

  • Check that the host is set to localhost: $cfg['Servers'][$i]['host'] = 'localhost';
  • The socket location can also be set here: $cfg['Servers'][$i]['socket'] = '*location*';

N.B.

As pointed out by @chk; Setting the $cfg['Servers'][$i]['host'] from localhost to 127.0.0.1 just causes the connection to use TCP/IP rather than using the socket and is more of a workaround than a solution.

The MySQL config setting bind-address= also only affects TCP/IP connections.

If you don't need remote connections, it is recommended to turn off TCP/IP listening with skip-networking.

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Close window automatically after printing dialog closes

This works for me on Chrome (haven't tried on others)

$(function(){
    window.print();
    $("body").hover(function(){
        window.close();
    });
});

PreparedStatement setNull(..)

but watch out for this....

Long nullLong = null;

preparedStatement.setLong( nullLong );

-thows null pointer exception-

because the protype is

setLong( long )   

NOT

setLong( Long )

nice one to catch you out eh.

Using ffmpeg to encode a high quality video

A couple of things:

  • You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k to the command line to get more or less DVD video bitrate.

  • You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264 as part of the command line. Otherwise -vcodec mpeg4 will also do a better job than MPEG-1, but not as well as x264.

  • There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.

What does the Java assert keyword do, and when should it be used?

A lot of good answers explaining what the assert keyword does, but few answering the real question, "when should the assert keyword be used in real life?"

The answer: almost never.

Assertions, as a concept, are wonderful. Good code has lots of if (...) throw ... statements (and their relatives like Objects.requireNonNull and Math.addExact). However, certain design decisions have greatly limited the utility of the assert keyword itself.

The driving idea behind the assert keyword is premature optimization, and the main feature is being able to easily turn off all checks. In fact, the assert checks are turned off by default.

However, it is critically important that invariant checks continue to be done in production. This is because perfect test coverage is impossible, and all production code will have bugs which assertions should help to diagnose and mitigate.

Therefore, the use of if (...) throw ... should be preferred, just as it is required for checking parameter values of public methods and for throwing IllegalArgumentException.

Occasionally, one might be tempted to write an invariant check that does take an undesirably long time to process (and is called often enough for it to matter). However, such checks will slow down testing which is also undesirable. Such time-consuming checks are usually written as unit tests. Nevertheless, it may sometimes make sense to use assert for this reason.

Do not use assert simply because it is cleaner and prettier than if (...) throw ... (and I say that with great pain, because I like clean and pretty). If you just cannot help yourself, and can control how your application is launched, then feel free to use assert but always enable assertions in production. Admittedly, this is what I tend to do. I am pushing for a lombok annotation that will cause assert to act more like if (...) throw .... Vote for it here.

(Rant: the JVM devs were a bunch of awful, prematurely optimizing coders. That is why you hear about so many security issues in the Java plugin and JVM. They refused to include basic checks and assertions in production code, and we are continuing to pay the price.)

Can I use DIV class and ID together in CSS?

Yes, yes you can.

#y.x {
 /* will select element of id="y" that also has class="x" */
}

Similarly:

.x#y {
 /* will select elements of class="x" that also have an id="y" */
}

Incidentally this might be useful in some use cases (wherein classes are used to represent some form of event or interaction), but for the most part it's not necessarily that useful, since ids are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.

How do I increase the capacity of the Eclipse output console?

Eclipse has limit of 32000 characters per line. If you have, for example JSONObject, which you want to log into console, you won't succeed. You can't handle this with the checkbox. Tested

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

Save the console.log in Chrome to a file

On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.

export CHROME_LOG_FILE=chrome.log

Using Cygwin to Compile a C program; Execution error

Compiling your C program using Cygwin

We will be using the gcc compiler on Cygwin to compile programs.

1) Launch Cygwin

2) Change to the directory you created for this class by typing

cd c:/windows/desktop

3) Compile the program by typing

gcc myProgram.c -o myProgram

the command gcc invokes the gcc compiler to compile your C program.

How to resolve compiler warning 'implicit declaration of function memset'

Try to add next define at start of your .c file:

#define _GNU_SOURCE

It helped me with pipe2 function.

Byte Array and Int conversion in Java

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

To get bytes back just:

new BigInteger(bytes).toByteArray()

How to add column to numpy array

I add a new column with ones to a matrix array in this way:

Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T

Maybe it is not that efficient?

What are some good SSH Servers for windows?

OpenSSH is a contender. Looks like it hasn't been updated in a while though.

It's the de facto choice in my opinion. And yes, running under Cygwin is really the nicest method.

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

Generate fixed length Strings filled with whitespaces

Here's a neat trick:

// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
  /*
   * Add the pad to the left of string then take as many characters from the right 
   * that is the same length as the pad.
   * This would normally mean starting my substring at 
   * pad.length() + string.length() - pad.length() but obviously the pad.length()'s 
   * cancel.
   *
   * 00000000sss
   *    ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
   */
  return (pad + string).substring(string.length());
}

public static void main(String[] args) throws InterruptedException {
  try {
    System.out.println("Pad 'Hello' with '          ' produces: '"+pad("Hello","          ")+"'");
    // Prints: Pad 'Hello' with '          ' produces: '     Hello'
  } catch (Exception e) {
    e.printStackTrace();
  }
}

How do I escape a string inside JavaScript code inside an onClick handler?

Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.

What is the purpose of the "role" attribute in HTML?

Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.

JavaScript equivalent to printf/String.Format

/**
 * Format string by replacing placeholders with value from element with
 * corresponsing index in `replacementArray`.
 * Replaces are made simultaneously, so that replacement values like
 * '{1}' will not mess up the function.
 *
 * Example 1:
 * ('{2} {1} {0}', ['three', 'two' ,'one']) -> 'one two three'
 *
 * Example 2:
 * ('{0}{1}', ['{1}', '{0}']) -> '{1}{0}'
 */
function stringFormat(formatString, replacementArray) {
    return formatString.replace(
        /\{(\d+)\}/g, // Matches placeholders, e.g. '{1}'
        function formatStringReplacer(match, placeholderIndex) {
            // Convert String to Number
            placeholderIndex = Number(placeholderIndex);

            // Make sure that index is within replacement array bounds
            if (placeholderIndex < 0 ||
                placeholderIndex > replacementArray.length - 1
            ) {
                return placeholderIndex;
            }

            // Replace placeholder with value from replacement array
            return replacementArray[placeholderIndex];
        }
    );
}

How to change the decimal separator of DecimalFormat from comma to dot/point?

This worked for me...

    double num = 10025000;
    new DecimalFormat("#,###.##");
    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
    System.out.println(df.format(num));

Remove empty space before cells in UITableView

I'm still not sure what caused that extra space at the top, but I found that deleting the UITableView with the space and replacing it with a new one took the space away.

I must have dragged a UIView in there accidentally, but I couldn't select it so I couldn't delete.

How do I fix twitter-bootstrap on IE?

If you are using responsive layout, try including this js on your code: https://github.com/scottjehl/Respond

How to set default font family in React Native?

Super late to this thread but here goes.

TLDR; Add the following block in your AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

 ....
    // HERE: replace "Verlag" with your font
  [[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
  ....
}

Walkthrough of the whole flow.

A few ways you can do this outside of using a plugin like react-native-global-props so Ill walk you though step by step.

Adding fonts to platforms.

How to add the font to IOS project

First let's create a location for our assets. Let's make the following directory at our root.

```

ios/
static/
       fonts/

```

Now let's add a "React Native" NPM in our package.json

  "rnpm": {
    "static": [
   "./static/fonts/"
    ]
  }

Now we can run "react-native link" to add our assets to our native apps.

Verifying or doing manually.

That should add your font names into the projects .plist (for VS code users run code ios/*/Info.plist to confirm)

Here let's assume Verlag is the font you added, it should look something like this:

     <dict>
   <plist>
      .....
      <key>UIAppFonts</key>
      <array>
         <string>Verlag Bold Italic.otf</string>
         <string>Verlag Book Italic.otf</string>
         <string>Verlag Light.otf</string>
         <string>Verlag XLight Italic.otf</string>
         <string>Verlag XLight.otf</string>
         <string>Verlag-Black.otf</string>
         <string>Verlag-BlackItalic.otf</string>
         <string>Verlag-Bold.otf</string>
         <string>Verlag-Book.otf</string>
         <string>Verlag-LightItalic.otf</string>
      </array>
      ....    
</dict>
</plist>

Now that you mapped them, now let's make sure they are actually there and being loaded (this is also how you'd do it manually).

Go to "Build Phase" > "Copy Bundler Resource", If it didn't work you'll a manually add under them here.

1_uuz0__3kx2vvguz37bhvya

Get Font Names (recognized by XCode)

First open your XCode logs, like:

XXXX

Then you can add the following block in your AppDelegate.m to log the names of the Fonts and the Font Family.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    .....


  for (NSString* family in [UIFont familyNames])
  {
    NSLog(@"%@", family);
    for (NSString* name in [UIFont fontNamesForFamilyName: family])
    {
      NSLog(@" %@", name);
    }
  }

  ...
}

Once you run you should find your fonts if loaded correctly, here we found ours in logs like this:

2018-05-07 10:57:04.194127-0700 MyApp[84024:1486266] Verlag
2018-05-07 10:57:04.194266-0700 MyApp[84024:1486266]  Verlag-Book
2018-05-07 10:57:04.194401-0700 MyApp[84024:1486266]  Verlag-BlackItalic
2018-05-07 10:57:04.194516-0700 MyApp[84024:1486266]  Verlag-BoldItalic
2018-05-07 10:57:04.194616-0700 MyApp[84024:1486266]  Verlag-XLight
2018-05-07 10:57:04.194737-0700 MyApp[84024:1486266]  Verlag-Bold
2018-05-07 10:57:04.194833-0700 MyApp[84024:1486266]  Verlag-Black
2018-05-07 10:57:04.194942-0700 MyApp[84024:1486266]  Verlag-XLightItalic
2018-05-07 10:57:04.195170-0700 MyApp[84024:1486266]  Verlag-LightItalic
2018-05-07 10:57:04.195327-0700 MyApp[84024:1486266]  Verlag-BookItalic
2018-05-07 10:57:04.195510-0700 MyApp[84024:1486266]  Verlag-Light

So now we know it loaded the Verlag family and are the fonts inside that family

  • Verlag-Book
  • Verlag-BlackItalic
  • Verlag-BoldItalic
  • Verlag-XLight
  • Verlag-Bold
  • Verlag-Black
  • Verlag-XLightItalic
  • Verlag-LightItalic
  • Verlag-BookItalic
  • Verlag-Light

These are now the case sensitive names we can use in our font family we can use in our react native app.

Got -'em now set default font.

Then to set a default font to add your font family name in your AppDelegate.m with this line

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

 ....
    // ADD THIS LINE (replace "Verlag" with your font)

  [[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
  ....
}

Done.

Get the new record primary key ID from MySQL insert query?

BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.

I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.

The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.

IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

How to remove hashbang from url?

The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes. To get rid of the hash, we can use the router's history mode, which leverages the history.pushState API to achieve URL navigation without a page reload:

import {routes} from './routes'; //import the routes from routes.js    

const router = new VueRouter({
    routes,
    mode: "history",
});

new Vue({
    el: '#app',
    router,
    render: h => h(App)
});

routes.js

import ComponentName from './ComponentName';

export const routes = [
   {
      path:'/your-path'
      component:ComponentName
   }
]

Reference

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

.Net System.Mail.Message adding multiple "To" addresses

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;

namespace HMS.HtmlHelper
{
    public class SendmailHelper
    {
        //Created SendEMail method for sendiing mails to users 
        public bool SendEMail(string FromName, string ToAddress, string Subject, string Message)
        {
            bool valid =false;
            try
            {
                string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["smtpusername"].ToString();
                string smtpPassword = System.Configuration.ConfigurationManager.AppSettings["smtppassword"].ToString();
                MailMessage mail = new MailMessage();``
                mail.From = new MailAddress(smtpUserName, FromName);
                mail.Subject = Subject;
                mail.To.Add(FormatMultipleEmailAddresses(ToAddress));
                //mail.To.Add(ToAddress);
                mail.Body = Message.ToString();
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["smtpserverport"]);
                smtp.Host = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; /
                smtp.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
                smtp.EnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ssl"]); ;
                smtp.Send(mail);
                valid = true;

            }
            catch (Exception ex)
            {
                valid =false ;
            }

            return valid;
        }



        public string FormatMultipleEmailAddresses(string emailAddresses)
        {
            var delimiters = new[] { ',', ';' };

            var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            return string.Join(",", addresses);
        }

    }
}``

How to find the mysql data directory from command line in windows

if you want to find datadir in linux or windows you can do following command

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'

if you are interested to find datadir you can use grep & awk command

mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"' | grep 'datadir' | awk '{print $2}'

React Native Error: ENOSPC: System limit for number of file watchers reached

I solved this issue by using sudo ie

sudo yarn start

or

sudo npm start

Vue is not defined

I got this error but as undefined due to the way I included js files

Initailly i had

<script src="~/vue/blade-account-update-credit-card-vue.js" asp-append-version="true"></script>
<script src="~/lib/vue/vue_v2.5.16.js"></script>

in the end of my .cshtml page GOT Error Vue not Defined but later I changed it to

<script src="~/lib/vue/vue_v2.5.16.js"></script> 
<script src="~/vue/blade-account-update-credit-card-vue.js" asp-append-version="true"></script>

and magically it worked. So i assume that vue js needs to be loaded on top of the .vue

Spring: How to inject a value to static field?

This is my sample code for load static variable

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OnelinkConfig {
    public static int MODULE_CODE;
    public static int DEFAULT_PAGE;
    public static int DEFAULT_SIZE;

    @Autowired
    public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
            @Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
        MODULE_CODE = code;
        DEFAULT_PAGE = page;
        DEFAULT_SIZE = size;
    }
}

Running Windows batch file commands asynchronously

I could not get anything to work I ended up just using powershell to start bat scripts .. sometimes even start cmd /c does not work not sure why .. I even tried stuff like start cmd /c notepad & exit

start-Process "c:\BACKUP\PRIVATE\MobaXterm_Portable\MobaXterm_Portable.bat" -WindowStyle Hidden

What is the most efficient way to store tags in a database?

If you don't mind using a bit of non-standard stuff, Postgres version 9.4 and up has an option of storing a record of type JSON text array.

Your schema would be:

Table: Items
Columns: Item_ID:int, Title:text, Content:text

Table: Tags
Columns: Item_ID:int, Tag_Title:text[]

For more info, see this excellent post by Josh Berkus: http://www.databasesoup.com/2015/01/tag-all-things.html

There are more various options compared thoroughly for performance and the one suggested above is the best overall.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.

Example for Google Chrome:

  1. F12
  2. Application
  3. Local Storage
  4. Clear All

What version of Python is on my Mac?

If you have both Python2 and Python3 installed on your Mac, you can use

python --version

to check the version of Python2, and

python3 --version

to check the version of Python3.

However, if only Python3 is installed, then your system might use python instead of python3 for Python3. In this case, you can just use

python --version

to check the version of Python3.

What is a non-capturing group in regular expressions?

tl;dr non-capturing groups, as the name suggests are the parts of the regex that you do not want to be included in the match and ?: is a way to define a group as being non-capturing.

Let's say you have an email address [email protected]. The following regex will create two groups, the id part and @example.com part. (\p{Alpha}*[a-z])(@example.com). For simplicity's sake, we are extracting the whole domain name including the @ character.

Now let's say, you only need the id part of the address. What you want to do is to grab the first group of the match result, surrounded by () in the regex and the way to do this is to use the non-capturing group syntax, i.e. ?:. So the regex (\p{Alpha}*[a-z])(?:@example.com) will return just the id part of the email.

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>> 

Multiple parameters in a List. How to create without a class?

To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.

public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
    public void Add(Tkey key, TValue value){
        base.Add(new KeyValuePair<Tkey, TValue>(key, value));
    }
}

What this means is that the constructor can be initialized with better syntax::

var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};

I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.

If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple is a class not a struct like KeyValuePair this is an interesting distinction).

Curiously enough, the initializer list syntax is available on any IEnumerable and it allows you to use any Add method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[] member as a params object[] member.

Android Studio installation on Windows 7 fails, no JDK found

My issue was caused because I have an & character in my Windows user name, so when installed in the default path I was getting the following error after running bin/studio.bat

                                               |
                                               v notice broken path
The system cannot find the file C:\Users\Daniel \studio64.exe.vmoptions.
Exception in thread "main" java.lang.NoClassDefFoundError: com/intellij/idea/Main
Caused by: java.lang.ClassNotFoundException: com.intellij.idea.Main
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: com.intellij.idea.Main.  Program will exit.

So I uninstalled and reinstalled it to program files and it launches fine now.

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

Angular - How to apply [ngStyle] conditions

You can use an inline if inside your ngStyle:

[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"

A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

[style.background-color]="myColorVaraible"

Why do I get a SyntaxError for a Unicode escape in my file path?

This usually happens in Python 3. One of the common reasons would be that while specifying your file path you need "\\" instead of "\". As in:

filePath = "C:\\User\\Desktop\\myFile"

For Python 2, just using "\" would work.

Automatically start forever (node) on system restart

You can use the following command in your shell to start your node forever:

forever app.js //my node script

You need to keep in mind that the server on which your app is running should always be kept on.

How to auto-format code in Eclipse?

Notice: It did not format the document unless I corrected all mistakes. Check your file before pressing CTRLSHIFTF.

How to set time to 24 hour format in Calendar

You can set the calendar to use only AM or PM using

calendar.set(Calendar.AM_PM, int);

0 = AM

1 = PM

Hope this helps

Javascript Object push() function

You must make var tempData = new Array();

Push is an Array function.

redistributable offline .NET Framework 3.5 installer for Windows 8

You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".

Twitter Bootstrap - how to center elements horizontally or vertically

With bootstrap 4 you can use flex

<div class="d-flex justify-content-center align-items-center">
    <button type="submit" class="btn btn-primary">Create</button>
</div>

source: bootstrap 4.1

HTTP Basic Authentication - what's the expected web browser experience?

WWW-Authenticate header

You may also get this if the server is sending a 401 response code but not setting the WWW-Authenticate header correctly - I should know, I've just fixed that in out own code because VB apps weren't popping up the authentication prompt.

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Sorting arraylist in alphabetical order (case insensitive)

Unfortunately, all answers so far do not take into account that "a" must not be considered equal to "A" when it comes to sorting.

String[] array = {"b", "A", "C", "B", "a"};

// Approach 1
Arrays.sort(array);
// array is [A, B, C, a, b]

// Approach 2
Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
// array is [A, a, b, B, C]

// Approach 3
Arrays.sort(array, java.text.Collator.getInstance());
// array is [a, A, b, B, C]

In approach 1 any lower case letters are considered greater than any upper case letters.

Approach 2 makes it worse, since CASE_INSENSITIVE_ORDER considers "a" and "A" equal (comparation result is 0). This makes sorting non-deterministic.

Approach 3 (using a java.text.Collator) is IMHO the only way of doing it correctly, since it considers "a"and "A" not equal, but puts them in the correct order according to the current (or any other desired) Locale.

php stdClass to array

Use the built in type cast functionality, simply type

$realArray = (array)$stdClass;

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Maven version with a property

See the Maven - Users forum 'version' contains an expression but should be a constant. Better way to add a new version?:

here is why this is a bad plan.

the pom that gets deployed will not have the property value resolved, so anyone depending on that pom will pick up the dependency as being the string uninterpolated with the ${ } and much hilarity will ensue in your build process.

in maven 2.1.0 and/or 2.2.0 an attempt was made to deploy poms with resolved properties... this broke more than expected, which is why those two versions are not recommended, 2.2.1 being the recommended 2.x version.

laravel throwing MethodNotAllowedHttpException

I also had the same error but had a different fix, in my XYZ.blade.php I had:

{!! Form::open(array('ul' => 'services.store')) !!}

which gave me the error, - I still don't know why- but when I changed it to

{!! Form::open(array('route' => 'services.store')) !!}

It worked!

I thought it was worth sharing :)

Resize iframe height according to content height in it

@SchizoDuckie's answer is very elegant and lightweight, but due to Webkit's lack of implementation for scrollHeight (see here), does not work on Webkit-based browsers (Safari, Chrome, various and sundry mobile platforms).

For this basic idea to work on Webkit along with Gecko and Trident browsers, one need only replace

<body onload='parent.resizeIframe(document.body.scrollHeight)'>

with

<body onload='parent.resizeIframe(document.body.offsetHeight)'>

So long as everything is on the same domain, this works quite well.

Android: Remove all the previous activities from the back stack

The solution proposed here worked for me:

Java

Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);

Kotlin

val i = Intent(this, NewActivity::class.java)
// set the new task and clear flags
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)

However, it requires API level >= 11.

How to Right-align flex item?

Example code based on answer by TetraDev

Images on right:

_x000D_
_x000D_
* {_x000D_
  outline: .4px dashed red;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  flex-basis: 100%;_x000D_
}_x000D_
_x000D_
img {_x000D_
  margin: 0 5px;_x000D_
  height: 30px;_x000D_
}
_x000D_
<div class="main">_x000D_
  <h1>Secure Payment</h1>_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Images on left:

_x000D_
_x000D_
* {_x000D_
  outline: .4px dashed red;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  flex-basis: 100%;_x000D_
  text-align: right;_x000D_
}_x000D_
_x000D_
img {_x000D_
  margin: 0 5px;_x000D_
  height: 30px;_x000D_
}
_x000D_
<div class="main">_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
  <img src="https://i.stack.imgur.com/i65gn.png">_x000D_
  <h1>Secure Payment</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Numpy matrix to array

A, = np.array(M.T)

depends what you mean by elegance i suppose but thats what i would do

Sending JSON to PHP using ajax

If you want to get the values via the $_POST variable then you should not specify the contentType as "application/json" but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

Else if you want to send a JSON from JavaScript to PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Is it possible to interactively delete matching search pattern in Vim?

There are 3 ways I can think of:

The way that is easiest to explain is

:%s/phrase to delete//gc

but you can also (personally I use this second one more often) do a regular search for the phrase to delete

/phrase to delete

Vim will take you to the beginning of the next occurrence of the phrase.

Go into insert mode (hit i) and use the Delete key to remove the phrase.

Hit escape when you have deleted all of the phrase.

Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed

Continue hitting n and dot until you are done.

Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you

Count the number of characters you want to delete

Type that number in (with number keys)

Hit the x key - characters should get deleted

Continue through with n and dot like in the second method.

PS - And if you didn't know already you can do a capital n to move backwards through the search matches.

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

phpMyAdmin - Error > Incorrect format parameter?

I had this error and as I'm on shared hosting I don't have access to the php.ini so wasn't sure how I could fix it, the host didn't seem to have a clue either. In the end I emptied my browser cache and reloaded phpmyadmin and it came back!

How to generate .env file for laravel?

Just tried both ways and in both ways I got generated .env file:

enter image description here

Composer should automatically create .env file. In the post-create-project-cmd section of the composer.json you can find:

"post-create-project-cmd": [
  "php -r \"copy('.env.example', '.env');\"",
  "php artisan key:generate"
]

Both ways use the same composer.json file, so there shoudn't be any difference.

I suggest you to update laravel/installer to the last version: 1.2 and try again:

composer global require "laravel/installer=~1.2"

You can always generate .env file manually by running:

cp .env.example .env
php artisan key:generate

How to store Emoji Character in MySQL Database

Hi my friends This is how I solved this problem and I was happy to teach it to you as well I am in the Android application I encrypt a string containing text and emoj and send it to the server and save it in the mysql table and after receiving it from the server I decrypt it and display it in the textview. encoded and decoded my message before request and after response: I send Android app messages to mysql via pdo through this method and receive them with pdo. And I have no problem. I think it was a good way. Please like Thankful

_x000D_
_x000D_
 
 public void main()
 {
    String message="hi mester ali moradi ?? how are you ?";
    String encoded_message=encodeStringUrl(message);
    String decode_message=decodeStringUrl(encoded_message);
 }
 public static String encodeStringUrl(String message) {
        String encodedUrl =null;
        try {
            encodedUrl = URLEncoder.encode(message, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return encodedUrl;
        }
        return encodedUrl;
    }

    public static String decodeStringUrl(String message) {
        String decodedUrl =null;
        try {
            decodedUrl = URLDecoder.decode(message, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return decodedUrl;
        }
        return decodedUrl;
    }
_x000D_
_x000D_
_x000D_ message : hi mester ali moradi ?? how are you ? encoded : ghgh%F0%9F%98%AE%F0%9F%A4%90%F0%9F%98%A5 decoded :hi mester ali moradi ?? how are you ?

Generate random string/characters in JavaScript

One liner:

Array(15).fill(null).map(() => Math.random().toString(36).substr(2)).join('')
// Outputs: 0h61cbpw96y83qtnunwme5lxk1i70a6o5r5lckfcyh1dl9fffydcfxddd69ada9tu9jvqdx864xj1ul3wtfztmh2oz2vs3mv6ej0fe58ho1cftkjcuyl2lfkmxlwua83ibotxqc4guyuvrvtf60naob26t6swzpil

Convert.ToDateTime: how to set format

You should probably use either DateTime.ParseExact or DateTime.TryParseExact instead. They allow you to specify specific formats. I personally prefer the Try-versions since I think they produce nicer code for the error cases.

How to exit a function in bash

Use return operator:

function FUNCT {
  if [ blah is false ]; then
    return 1 # or return 0, or even you can omit the argument.
  else
    keep running the function
  fi
}

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

Laravel - Forbidden You don't have permission to access / on this server

I had the same problem and builded a .htaccess file to fix this issue with a few more improvements. You can use it as it is, just download it from Github Gist and change the filename "public/index.php" to "public/app.php" and see how it works! :)

UIView touch event in controller

For swift 4

@IBOutlet weak var someView: UIView!  
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)

@objc func someAction(_ sender:UITapGestureRecognizer){
    print("view was clicked")
}

How to use ImageBackground to set background image for screen in react-native

const img = '../../img/splash/splash_bg.png';
<ImageBackground  source={{ uri: img }} style={styles.backgroundImage} >
    </ImageBackground>

This worked for me. Reference to RN docs can be found here.I wrote mine by reading this- https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting

Select2 doesn't work when embedded in a bootstrap modal

I had a semi-related issue in an application so I'll put in my 2c.

I have multiple modals with forms containing select2 widgets. Opening modal A, then another modal inside modal A, would cause select2 widgets inside modal B to disappear and fail to initialize.

Each of these modals were loading the forms via ajax.

The solution was to remove the forms from the dom when closing a modal.

$(document).on('hidden.bs.modal', '.modal', function(e) {
    // make sure we don't leave any select2 widgets around 
    $(this).find('.my-form').remove();
});

Comparing arrays for equality in C++

You are comparing the addresses instead of the values.

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

Plain and simple:

If Jenkins sees the build step (which is a script too) exits with non-zero code, the build is marked with a red ball (= failed).

Why exactly that happens depends on your build script.

I wrote something similar from another point-of-view but maybe it will help to read it anyway: Why does Jenkins think my build succeeded?

ActiveRecord: size vs count

I recommended using the size function.

class Customer < ActiveRecord::Base
  has_many :customer_activities
end

class CustomerActivity < ActiveRecord::Base
  belongs_to :customer, counter_cache: true
end

Consider these two models. The customer has many customer activities.

If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

Consider one example: in my database, one customer has 20,000 customer activities and I try to count the number of records of customer activities of that customer with each of count, length and size method. here below the benchmark report of all these methods.

            user     system      total        real
Count:     0.000000   0.000000   0.000000 (  0.006105)
Size:      0.010000   0.000000   0.010000 (  0.003797)
Length:    0.030000   0.000000   0.030000 (  0.026481)

so I found that using :counter_cache Size is the best option to calculate the number of records.

Input Type image submit form value?

To submit a form you could use:

<input type="submit">

or

<input type="button"> + Javascript 

I never heard of such a crazy guy to try to send a form using a image or a checkbox as you want :))

What's the key difference between HTML 4 and HTML 5?

Now W3c provides an official difference on their site:

http://www.w3.org/TR/html5-diff/

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

If statement for strings in python?

proceed = "y", "Y"
if answer in proceed:

Also, you don't want

answer = str(input("Is the information correct? Enter Y for yes or N for no"))

You want

answer = raw_input("Is the information correct? Enter Y for yes or N for no")

input() evaluates whatever is entered as a Python expression, raw_input() returns a string.

Edit: That is only true on Python 2. On Python 3, input is fine, although str() wrapping is still redundant.

RegEx to parse or validate Base64 data

The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex

which is in the current version looks like:

module.exports = function (opts) {
  opts = opts || {};
  var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';

  return opts.exact ? new RegExp('(?:^' + regex + '$)') :
                    new RegExp('(?:^|\\s)' + regex, 'g');
};

For a boolean field, what is the naming convention for its getter/setter?

As a setter, how about:

// setter
public void beCurrent(boolean X) {
    this.isCurrent = X;
}

or

// setter
public void makeCurrent(boolean X) {
    this.isCurrent = X;
}

I'm not sure if these naming make sense to native English speakers.

TSQL - Cast string to integer or return default value

Regards.

I wrote a useful scalar function to simulate the TRY_CAST function of SQL SERVER 2012 in SQL Server 2008.

You can see it in the next link below and we help each other to improve it. TRY_CAST Function for SQL Server 2008 https://gist.github.com/jotapardo/800881eba8c5072eb8d99ce6eb74c8bb

The two main differences are that you must pass 3 parameters and you must additionally perform an explicit CONVERT or CAST to the field. However, it is still very useful because it allows you to return a default value if CAST is not performed correctly.

dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)

Example:

SELECT   CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL   
                        THEN 'Cast failed'  
                        ELSE 'Cast succeeded'  
                    END AS Result; 

For now only supports the data types INT, DATE, NUMERIC, BIT and FLOAT

I hope you find it useful.

CODE:

DECLARE @strSQL NVARCHAR(1000)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TRY_CAST]'))
    BEGIN
        SET @strSQL = 'CREATE FUNCTION [dbo].[TRY_CAST] () RETURNS INT AS BEGIN RETURN 0 END'
        EXEC sys.sp_executesql @strSQL
    END

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
------------------------------------------------------------------------------------------------------------------------
    Description:    
                    Syntax 
                    ---------------
                    dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)

                    +---------------------------+-----------------------+
                    |   Expression              |   VARCHAR(8000)       |
                    +---------------------------+-----------------------+
                    |   Data_Type               |   VARCHAR(8000)       |
                    +---------------------------+-----------------------+
                    |   ReturnValueIfErrorCast  |   SQL_VARIANT = NULL  |
                    +---------------------------+-----------------------+


                    Arguments
                    ---------------
                    expression
                    The value to be cast. Any valid expression.

                    Data_Type
                    The data type into which to cast expression.

                    ReturnValueIfErrorCast
                    Value returned if cast fails or is not supported. Required. Set the DEFAULT value by default.


                    Return Type
                    ----------------
                    Returns value cast to SQL_VARIANT type if the cast succeeds; otherwise, returns null if the parameter @pReturnValueIfErrorCast is set to DEFAULT, 
                    or that the user indicates.


                    Remarks
                    ----------------
                    dbo.TRY_CAST function simulates the TRY_CAST function reserved of SQL SERVER 2012 for using in SQL SERVER 2008. 
                    dbo.TRY_CAST function takes the value passed to it and tries to convert it to the specified Data_Type. 
                    If the cast succeeds, dbo.TRY_CAST returns the value as SQL_VARIANT type; if the cast doesn´t succees, null is returned if the parameter @pReturnValueIfErrorCast is set to DEFAULT. 
                    If the Data_Type is unsupported will return @pReturnValueIfErrorCast.
                    dbo.TRY_CAST function requires user make an explicit CAST or CONVERT in ANY statements.
                    This version of dbo.TRY_CAST only supports CAST for INT, DATE, NUMERIC and BIT types.


                    Examples
                    ====================================================================================================

                    --A. Test TRY_CAST function returns null

                        SELECT   
                            CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL   
                            THEN 'Cast failed'  
                            ELSE 'Cast succeeded'  
                        END AS Result; 

                    GO

                    --B. Error Cast With User Value

                        SELECT   
                            dbo.TRY_CAST('2147483648', 'INT', DEFAULT) AS [Error Cast With DEFAULT],
                            dbo.TRY_CAST('2147483648', 'INT', -1) AS [Error Cast With User Value],
                            dbo.TRY_CAST('2147483648', 'INT', NULL) AS [Error Cast With User NULL Value]; 

                        GO 

                    --C. Additional CAST or CONVERT required in any assignment statement

                        DECLARE @IntegerVariable AS INT

                        SET @IntegerVariable = CAST(dbo.TRY_CAST(123, 'INT', DEFAULT) AS INT)

                        SELECT @IntegerVariable

                        GO 

                        IF OBJECT_ID('tempdb..#temp') IS NOT NULL
                            DROP TABLE #temp

                        CREATE TABLE #temp (
                            Id INT IDENTITY
                            , FieldNumeric NUMERIC(3, 1)
                            )

                        INSERT INTO dbo.#temp (FieldNumeric)
                        SELECT CAST(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', 0) AS NUMERIC(3, 1));--Need explicit CAST on INSERT statements

                        SELECT *
                        FROM #temp

                        DROP TABLE #temp

                        GO 

                    --D. Supports CAST for INT, DATE, NUMERIC and BIT types.

                        SELECT dbo.TRY_CAST(2147483648, 'INT', 0) AS [Cast failed]
                            , dbo.TRY_CAST(2147483647, 'INT', 0) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST(212, 'INT', 0), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST('AAAA0101', 'DATE', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST('20160101', 'DATE', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST('2016-01-01', 'DATE', DEFAULT), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST(1.23, 'NUMERIC(3,1)', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST('A', 'BIT', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST(1, 'BIT', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST('123', 'BIT', DEFAULT), 'BaseType') AS [BaseType];

                        GO 

                    --E. B. TRY_CAST return NULL on unsupported data_types

                        SELECT dbo.TRY_CAST(4, 'xml', DEFAULT) AS [unsupported];  

                        GO  

                    ====================================================================================================

------------------------------------------------------------------------------------------------------------------------
    Responsible:    Javier Pardo 
    Date:           diciembre 29/2016
    WB tests:       Javier Pardo 
------------------------------------------------------------------------------------------------------------------------
    Update by:      Javier Eduardo Pardo Moreno 
    Date:           febrero 16/2017
    Id update:      JEPM20170216
    Description:    Fix  ISNUMERIC function makes it unreliable. SELECT dbo.TRY_CAST('+', 'INT', 0) will yield Msg 8114, 
                    Level 16, State 5, Line 16 Error converting data type varchar to float.
                    ISNUMERIC() function treats few more characters as numeric, like: – (minus), + (plus), $ (dollar), \ (back slash), (.)dot and (,)comma
                    Collaborator aperiooculus (http://stackoverflow.com/users/3083382/aperiooculus )

                    Fix dbo.TRY_CAST('2013/09/20', 'datetime', DEFAULT) for supporting DATETIME format

    WB tests:       Javier Pardo 

------------------------------------------------------------------------------------------------------------------------
*/

ALTER FUNCTION dbo.TRY_CAST
(
    @pExpression AS VARCHAR(8000),
    @pData_Type AS VARCHAR(8000),
    @pReturnValueIfErrorCast AS SQL_VARIANT = NULL
)
RETURNS SQL_VARIANT
AS
BEGIN
    --------------------------------------------------------------------------------
    --  INT 
    --------------------------------------------------------------------------------

    IF @pData_Type = 'INT'
    BEGIN
        IF ISNUMERIC(@pExpression) = 1 AND @pExpression NOT IN ('-','+','$','.',',','\')    --JEPM20170216
        BEGIN
            DECLARE @pExpressionINT AS FLOAT = CAST(@pExpression AS FLOAT)

            IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
            BEGIN
                RETURN CAST(@pExpressionINT as INT)
            END
            ELSE
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END --FIN IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
        END
        ELSE
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END -- FIN IF ISNUMERIC(@pExpression) = 1
    END -- FIN IF @pData_Type = 'INT'

    --------------------------------------------------------------------------------
    --  DATE    
    --------------------------------------------------------------------------------

    IF @pData_Type IN ('DATE','DATETIME')
    BEGIN
        IF ISDATE(@pExpression) = 1
        BEGIN

            DECLARE @pExpressionDATE AS DATETIME = cast(@pExpression AS DATETIME)

            IF @pData_Type = 'DATE'
            BEGIN
                RETURN cast(@pExpressionDATE as DATE)
            END

            IF @pData_Type = 'DATETIME'
            BEGIN
                RETURN cast(@pExpressionDATE as DATETIME)
            END

        END
        ELSE 
        BEGIN

            DECLARE @pExpressionDATEReplaced AS VARCHAR(50) = REPLACE(REPLACE(REPLACE(@pExpression,'\',''),'/',''),'-','')

            IF ISDATE(@pExpressionDATEReplaced) = 1
            BEGIN
                IF @pData_Type = 'DATE'
                BEGIN
                    RETURN cast(@pExpressionDATEReplaced as DATE)
                END

                IF @pData_Type = 'DATETIME'
                BEGIN
                    RETURN cast(@pExpressionDATEReplaced as DATETIME)
                END

            END
            ELSE
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END
        END --FIN IF ISDATE(@pExpression) = 1
    END --FIN IF @pData_Type = 'DATE'

    --------------------------------------------------------------------------------
    --  NUMERIC 
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'NUMERIC%'
    BEGIN

        IF ISNUMERIC(@pExpression) = 1
        BEGIN

            DECLARE @TotalDigitsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX('(',@pData_Type)+1,  CHARINDEX(',',@pData_Type) - CHARINDEX('(',@pData_Type) - 1)
                , @TotalDecimalsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX(',',@pData_Type)+1,  CHARINDEX(')',@pData_Type) - CHARINDEX(',',@pData_Type) - 1)
                , @TotalDigitsOfValue AS INT 
                , @TotalDecimalsOfValue AS INT 
                , @TotalWholeDigitsOfType AS INT 
                , @TotalWholeDigitsOfValue AS INT 

            SET @pExpression = REPLACE(@pExpression, ',','.')

            SET @TotalDigitsOfValue = LEN(REPLACE(@pExpression, '.',''))
            SET @TotalDecimalsOfValue = CASE Charindex('.', @pExpression)
                                        WHEN 0
                                            THEN 0
                                        ELSE Len(Cast(Cast(Reverse(CONVERT(VARCHAR(50), @pExpression, 128)) AS FLOAT) AS BIGINT))
                                        END 
            SET @TotalWholeDigitsOfType = @TotalDigitsOfType - @TotalDecimalsOfType
            SET @TotalWholeDigitsOfValue = @TotalDigitsOfValue - @TotalDecimalsOfValue

            -- The total digits can not be greater than the p part of NUMERIC (p, s)
            -- The total of decimals can not be greater than the part s of NUMERIC (p, s)
            -- The total digits of the whole part can not be greater than the subtraction between p and s
            IF (@TotalDigitsOfValue <= @TotalDigitsOfType) AND (@TotalDecimalsOfValue <= @TotalDecimalsOfType) AND (@TotalWholeDigitsOfValue <= @TotalWholeDigitsOfType)
            BEGIN
                DECLARE @pExpressionNUMERIC AS FLOAT
                SET @pExpressionNUMERIC = CAST (ROUND(@pExpression, @TotalDecimalsOfValue) AS FLOAT) 

                RETURN @pExpressionNUMERIC --Returns type FLOAT
            END 
            else
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END-- FIN IF (@TotalDigitisOfValue <= @TotalDigits) AND (@TotalDecimalsOfValue <= @TotalDecimals) 

        END
        ELSE 
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'NUMERIC%'

    --------------------------------------------------------------------------------
    --  BIT 
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'BIT'
    BEGIN
        IF ISNUMERIC(@pExpression) = 1
        BEGIN
            RETURN CAST(@pExpression AS BIT) 
        END
        ELSE 
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'BIT'


    --------------------------------------------------------------------------------
    --  FLOAT   
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'FLOAT'
    BEGIN
        IF ISNUMERIC(REPLACE(REPLACE(@pExpression, CHAR(13), ''), CHAR(10), '')) = 1
        BEGIN

            RETURN CAST(@pExpression AS FLOAT) 
        END
        ELSE 
        BEGIN

            IF REPLACE(@pExpression, CHAR(13), '') = '' --Only white spaces are replaced, not new lines
            BEGIN
                RETURN 0
            END
            ELSE 
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END --IF REPLACE(@pExpression, CHAR(13), '') = '' 

        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'FLOAT'

    --------------------------------------------------------------------------------
    --  Any other unsupported data type will return NULL or the value assigned by the user to @pReturnValueIfErrorCast  
    --------------------------------------------------------------------------------

    RETURN @pReturnValueIfErrorCast



END

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

May it's late for the answer. But will be helpful for anyone.

In My case want to call activity from Fragment and setResult back from the fragment.

I have used getContext of Fragment Like.

startActivityForResult(new Intent(getContext(), NextActivity.class), 111);

And Set Result from Fragment

getActivity().setResult(Activity.RESULT_OK);
                    getActivity().finish();

Now Getting Result to Fragment with

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && requestCode == 111) {

    }
}

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Started working after adding property:

mail.smtp.starttls.enable=true

Using:

mail.smtp.host=smtp.office365.com
mail.smtp.port=587
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
[email protected]
mail.smtp.password=xxx
[email protected]

git undo all uncommitted or unsaved changes

If you wish to "undo" all uncommitted changes simply run:

git stash
git stash drop

If you have any untracked files (check by running git status), these may be removed by running:

git clean -fdx

git stash creates a new stash which will become stash@{0}. If you wish to check first you can run git stash list to see a list of your stashes. It will look something like:

stash@{0}: WIP on rails-4: 66c8407 remove forem residuals
stash@{1}: WIP on master: 2b8f269 Map qualifications
stash@{2}: WIP on master: 27a7e54 Use non-dynamic finders
stash@{3}: WIP on blogit: c9bd270 some changes

Each stash is named after the previous commit messsage.

How to count frequency of characters in a string?

Please try the given code below, hope it will helpful to you,

import java.util.Scanner;

class String55 {
    public static int frequency(String s1,String s2)
    {

        int count=0;
        char ch[]=s1.toCharArray();
        char ch1[]=s2.toCharArray();
        for (int i=0;i<ch.length-1; i++)
        {



                int k=i;

                int j1=i+1;
                int j=0;
                int j11=j;
                int j2=j+1;
                {
                    while(k<ch.length && j11<ch1.length && ch[k]==ch1[j11])
                    {
                    k++;
                    j11++;

                    }


                int l=k+j1;
                int m=j11+j2;
                if( l== m)
                {
                    count=1;
                    count++;
                }





        }
        }
        return count;


    }
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter the pattern");
        String s1=sc.next();
            System.out.println("enter the String");
            String s2=sc.next();
            int res=frequency(s1, s2);
            System.out.println("FREQUENCY==" +res);

    }
}

SAMPLE OUTPUT: enter the pattern man enter the String dhimanman FREQUENCY==2

Thank-you.Happy coding.

Comparing two arrays & get the values which are not common

Collection

$a = 1..5
$b = 4..8

$Yellow = $a | Where {$b -NotContains $_}

$Yellow contains all the items in $a except the ones that are in $b:

PS C:\> $Yellow
1
2
3

$Blue = $b | Where {$a -NotContains $_}

$Blue contains all the items in $b except the ones that are in $a:

PS C:\> $Blue
6
7
8

$Green = $a | Where {$b -Contains $_}

Not in question, but anyways; Green contains the items that are in both $a and $b.

PS C:\> $Green
4
5

Note: Where is an alias of Where-Object. Alias can introduce possible problems and make scripts hard to maintain.


Addendum 12 October 2019

As commented by @xtreampb and @mklement0: although not shown from the example in the question, the task that the question implies (values "not in common") is the symmetric difference between the two input sets (the union of yellow and blue).

Union

The symmetric difference between the $a and $b can be literally defined as the union of $Yellow and $Blue:

$NotGreen = $Yellow + $Blue

Which is written out:

$NotGreen = ($a | Where {$b -NotContains $_}) + ($b | Where {$a -NotContains $_})

Performance

As you might notice, there are quite some (redundant) loops in this syntax: all items in list $a iterate (using Where) through items in list $b (using -NotContains) and visa versa. Unfortunately the redundancy is difficult to avoid as it is difficult to predict the result of each side. A Hash Table is usually a good solution to improve the performance of redundant loops. For this, I like to redefine the question: Get the values that appear once in the sum of the collections ($a + $b):

$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}

By using the ForEach statement instead of the ForEach-Object cmdlet and the Where method instead of the Where-Object you might increase the performance by a factor 2.5:

$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})

LINQ

But Language Integrated Query (LINQ) will easily beat any native PowerShell and native .Net methods (see also High Performance PowerShell with LINQ and mklement0's answer for Can the following Nested foreach loop be simplified in PowerShell?:

To use LINQ you need to explicitly define the array types:

[Int[]]$a = 1..5
[Int[]]$b = 4..8

And use the [Linq.Enumerable]:: operator:

$Yellow   = [Int[]][Linq.Enumerable]::Except($a, $b)
$Blue     = [Int[]][Linq.Enumerable]::Except($b, $a)
$Green    = [Int[]][Linq.Enumerable]::Intersect($a, $b)
$NotGreen = [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))

Benchmark

Benchmark results highly depend on the sizes of the collections and how many items there are actually shared, as a "average", I am presuming that half of each collection is shared with the other.

Using             Time
Compare-Object    111,9712
NotContains       197,3792
ForEach-Object    82,8324
ForEach Statement 36,5721
LINQ              22,7091

To get a good performance comparison, caches should be cleared by e.g. starting a fresh PowerShell session.

$a = 1..1000
$b = 500..1500

(Measure-Command {
    Compare-Object -ReferenceObject $a -DifferenceObject $b  -PassThru
}).TotalMilliseconds
(Measure-Command {
    ($a | Where {$b -NotContains $_}), ($b | Where {$a -NotContains $_})
}).TotalMilliseconds
(Measure-Command {
    $Count = @{}
    $a + $b | ForEach-Object {$Count[$_] += 1}
    $Count.Keys | Where-Object {$Count[$_] -eq 1}
}).TotalMilliseconds

(Measure-Command {
    $Count = @{}
    ForEach ($Item in $a + $b) {$Count[$Item] += 1}
    $Count.Keys.Where({$Count[$_] -eq 1})
}).TotalMilliseconds

[Int[]]$a = $a
[Int[]]$b = $b
(Measure-Command {
    [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
}).TotalMilliseconds

How do I obtain the frequencies of each value in an FFT?

I have used the following:

public static double Index2Freq(int i, double samples, int nFFT) {
  return (double) i * (samples / nFFT / 2.);
}

public static int Freq2Index(double freq, double samples, int nFFT) {
  return (int) (freq / (samples / nFFT / 2.0));
}

The inputs are:

  • i: Bin to access
  • samples: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)
  • nFFT: Size of the FFT vector

How to convert int to QString?

Use QString::number():

int i = 42;
QString s = QString::number(i);

How do I line up 3 divs on the same row?

2019 answer:

Using CSS grid:

.parent {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr;
}

Jenkins returned status code 128 with github

When I got a similar status code 128 error from Jenkins:

status code 128:
stdout: 
stderr: fatal: Couldn't find remote ref refs/heads/jenkins

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2172)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1864)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:78)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:545)
    at jenkins.plugins.git.GitSCMFileSystem$BuilderImpl.build(GitSCMFileSystem.java:358)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:197)
    at jenkins.scm.api.SCMFileSystem.of(SCMFileSystem.java:173)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:113)
    at org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition.create(CpsScmFlowDefinition.java:67)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:299)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

It was because I hadn't pushed my new branch "jenkins" that had my Jenkinsfile. So the solution was to just push my changes

How to append a jQuery variable value inside the .html tag

HTML :

<div id="myDiv">
    <form id="myForm">
    </form> 
</div>

jQuery :

var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';

$("#myDiv form#myForm").html(chbx);

//to insert dynamically created form 
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");

Demo

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

Create web service proxy in Visual Studio from a WSDL file

Using WSDL.exe didn't work for me (gave me an error about a missing type), but I was able to right-click on my project in VS and select "Add Service Reference." I entered the path to the wsdl file in the Address field and hit "Go." That seemed to be able to find all the proper types and added the classes directly to my project.

What is the difference between <section> and <div>?

<div>—the generic flow container we all know and love. It’s a block-level element with no additional semantic meaning (W3C:Markup, WhatWG)

<section>—a generic document or application section. A normally has a heading (title) and maybe a footer too. It’s a chunk of related content, like a subsection of a long article, a major part of the page (eg the news section on the homepage), or a page in a webapp’s tabbed interface. (W3C:Markup, WhatWG)

My suggestion: div: used lower version( i think 4.01 to still) html element(lot of designers handled that). section: recently comming (html5) html element.

Merge 2 DataTables and store in a new one

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

How to apply a function to two columns of Pandas dataframe

I suppose you don't want to change get_sublist function, and just want to use DataFrame's apply method to do the job. To get the result you want, I've wrote two help functions: get_sublist_list and unlist. As the function name suggest, first get the list of sublist, second extract that sublist from that list. Finally, We need to call apply function to apply those two functions to the df[['col_1','col_2']] DataFrame subsequently.

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']

def get_sublist(sta,end):
    return mylist[sta:end+1]

def get_sublist_list(cols):
    return [get_sublist(cols[0],cols[1])]

def unlist(list_of_lists):
    return list_of_lists[0]

df['col_3'] = df[['col_1','col_2']].apply(get_sublist_list,axis=1).apply(unlist)

df

If you don't use [] to enclose the get_sublist function, then the get_sublist_list function will return a plain list, it'll raise ValueError: could not broadcast input array from shape (3) into shape (2), as @Ted Petrou had mentioned.

String compare in Perl with "eq" vs "=="

First, eq is for comparing strings; == is for comparing numbers.

Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.

I think your problem is that your variables don't contain what you think they do. I think your $str1 or $str2 contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";.

The trailing newline can be removed with the chomp($str1); function.

Folder is locked and I can't unlock it

To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:

I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).

So to resolve this:

Either

1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe

1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe

Then

2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.

From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

You must run your mysql by xampp-controle.exe in folder XAMPP. After that login:

mysql -u root

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

How do I tell Python to convert integers into words

This does the job without any library. Used recursion and it is Indian style. -- Ravi.

def spellNumber(no):
    # str(no) will result in  56.9 for 56.90 so we used the method which is given below.
    strNo = "%.2f" %no
    n = strNo.split(".")
    rs = numberToText(int(n[0])).strip()
    ps =""
    if(len(n)>=2):
        ps = numberToText(int(n[1])).strip()
        rs = "" + ps+ " paise"  if(rs.strip()=="") else  (rs + " and " + ps+ " paise").strip()
    return rs
print(spellNumber(0.67))
print(spellNumber(5858.099))
print(spellNumber(5083754857380.50))    

def numberToText(no):
    ones = " ,one,two,three,four,five,six,seven,eight,nine,ten,eleven,tweleve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty".split(',')
    tens = "ten,twenty,thirty,fourty,fifty,sixty,seventy,eighty,ninety".split(',')
    text = ""
    if len(str(no))<=2:
        if(no<20):
            text = ones[no]
        else:
            text = tens[no//10-1] +" " + ones[(no %10)]
    elif len(str(no))==3:
        text = ones[no//100] +" hundred " + numberToText(no- ((no//100)* 100))
    elif len(str(no))<=5:
        text = numberToText(no//1000) +" thousand " + numberToText(no- ((no//1000)* 1000))
    elif len(str(no))<=7:
        text = numberToText(no//100000) +" lakh " + numberToText(no- ((no//100000)* 100000))
    else:
        text = numberToText(no//10000000) +" crores " + numberToText(no- ((no//10000000)* 10000000))
    return text

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

What is "with (nolock)" in SQL Server?

Simple answer - whenever your SQL is not altering data, and you have a query that might interfere with other activity (via locking).

It's worth considering for any queries used for reports, especially if the query takes more than, say, 1 second.

It's especially useful if you have OLAP-type reports you're running against an OLTP database.

The first question to ask, though, is "why am I worrying about this?" ln my experience, fudging the default locking behavior often takes place when someone is in "try anything" mode and this is one case where unexpected consequences are not unlikely. Too often it's a case of premature optimization and can too easily get left embedded in an application "just in case." It's important to understand why you're doing it, what problem it solves, and whether you actually have the problem.

How to ORDER BY a SUM() in MySQL?

Without a GROUP BY clause, any summation will roll all rows up into a single row, so your query will indeed not work. If you grouped by, say, name, and ordered by sum(c_counts+f_counts), then you might get some useful results. But you would have to group by something.

start/play embedded (iframe) youtube-video on click of an image

Example youtube iframe

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

The click to play HTML element

<div class="videoplay">Play</div> 

jQuery code to play the Video

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

Thanks to https://codepen.io/martinwolf/pen/dyLAC

Html Agility Pack get all elements by class

public static List<HtmlNode> GetTagsWithClass(string html,List<string> @class)
    {
        // LoadHtml(html);           
        var result = htmlDocument.DocumentNode.Descendants()
            .Where(x =>x.Attributes.Contains("class") && @class.Contains(x.Attributes["class"].Value)).ToList();          
        return result;
    }      

MySQL: update a field only if condition is met

Another variation:

UPDATE test
SET field = IF ( {condition}, {new value}, field )
WHERE id = 123

This will update the field with {new value} only if {condition} is met

How to add a class to body tag?

This should do it:

var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);

The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);

That pattern should yield the following:

  • ../about_us.html : about
  • ../something.html : something
  • ../has_two_underscores.html : has

How do I set up a simple delegate to communicate between two view controllers?

Simple example...

Let's say the child view controller has a UISlider and we want to pass the value of the slider back to the parent via a delegate.

In the child view controller's header file, declare the delegate type and its methods:

ChildViewController.h

#import <UIKit/UIKit.h>

// 1. Forward declaration of ChildViewControllerDelegate - this just declares
// that a ChildViewControllerDelegate type exists so that we can use it
// later.
@protocol ChildViewControllerDelegate;

// 2. Declaration of the view controller class, as usual
@interface ChildViewController : UIViewController

// Delegate properties should always be weak references
// See http://stackoverflow.com/a/4796131/263871 for the rationale
// (Tip: If you're not using ARC, use `assign` instead of `weak`)
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;

// A simple IBAction method that I'll associate with a close button in
// the UI. We'll call the delegate's childViewController:didChooseValue: 
// method inside this handler.
- (IBAction)handleCloseButton:(id)sender;

@end

// 3. Definition of the delegate's interface
@protocol ChildViewControllerDelegate <NSObject>

- (void)childViewController:(ChildViewController*)viewController 
             didChooseValue:(CGFloat)value;

@end

In the child view controller's implementation, call the delegate methods as required.

ChildViewController.m

#import "ChildViewController.h"

@implementation ChildViewController

- (void)handleCloseButton:(id)sender {
    // Xcode will complain if we access a weak property more than 
    // once here, since it could in theory be nilled between accesses
    // leading to unpredictable results. So we'll start by taking
    // a local, strong reference to the delegate.
    id<ChildViewControllerDelegate> strongDelegate = self.delegate;

    // Our delegate method is optional, so we should 
    // check that the delegate implements it
    if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) {
        [strongDelegate childViewController:self didChooseValue:self.slider.value];
    }
}

@end

In the parent view controller's header file, declare that it implements the ChildViewControllerDelegate protocol.

RootViewController.h

#import <UIKit/UIKit.h>
#import "ChildViewController.h"

@interface RootViewController : UITableViewController <ChildViewControllerDelegate>

@end

In the parent view controller's implementation, implement the delegate methods appropriately.

RootViewController.m

#import "RootViewController.h"

@implementation RootViewController

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChildViewController *detailViewController = [[ChildViewController alloc] init];
    // Assign self as the delegate for the child view controller
    detailViewController.delegate = self;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

// Implement the delegate methods for ChildViewControllerDelegate
- (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value {

    // Do something with value...

    // ...then dismiss the child view controller
    [self.navigationController popViewControllerAnimated:YES];
}

@end

Hope this helps!

How to compute the similarity between two text documents?

If you are more interested in measuring semantic similarity of two pieces of text, I suggest take a look at this gitlab project. You can run it as a server, there is also a pre-built model which you can use easily to measure the similarity of two pieces of text; even though it is mostly trained for measuring the similarity of two sentences, you can still use it in your case.It is written in java but you can run it as a RESTful service.

Another option also is DKPro Similarity which is a library with various algorithm to measure the similarity of texts. However, it is also written in java.

code example:

// this similarity measure is defined in the dkpro.similarity.algorithms.lexical-asl package
// you need to add that to your .pom to make that example work
// there are some examples that should work out of the box in dkpro.similarity.example-gpl 
TextSimilarityMeasure measure = new WordNGramJaccardMeasure(3);    // Use word trigrams

String[] tokens1 = "This is a short example text .".split(" ");   
String[] tokens2 = "A short example text could look like that .".split(" ");

double score = measure.getSimilarity(tokens1, tokens2);

System.out.println("Similarity: " + score);

Get list from pandas DataFrame column headers

This solution lists all the columns of your object my_dataframe:

print(list(my_dataframe))

mysql query result in php variable

There are a couple of mysql functions you need to look into.

  • mysql_query("query string here") : returns a resource
  • mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:

    while ($row = mysql_fetch_array($query)){
        print_r $row;
    }

    Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.

Links:

In your case,

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
    die("BAD!");
}
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    echo "user Id: " . $row['userid'];
}
else{
    echo "not found!";
}

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Logarithmic returns in pandas dataframe

Log returns are simply the natural log of 1 plus the arithmetic return. So how about this?

df['pct_change'] = df.price.pct_change()
df['log_return'] = np.log(1 + df.pct_change)

Even more concise, utilizing Ximix's suggestion:

df['log_return'] = np.log1p(df.price.pct_change())

How to capture the browser window close event?

Unfortunately, whether it is a reload, new page redirect, or browser close the event will be triggered. An alternative is catch the id triggering the event and if it is form dont trigger any function and if it is not the id of the form then do what you want to do when the page closes. I am not sure if that is also possible directly and is tedious.

You can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  /* Do you small action code here */
  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

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

Complementing @Bob Jarvis and @dmikam answer, Postgres don't perform a good plan when you don't use LATERAL, below a simulation, in both cases the query data results are the same, but the cost are very different

Table structure

CREATE TABLE ITEMS (
    N INTEGER NOT NULL,
    S TEXT NOT NULL
);

INSERT INTO ITEMS
  SELECT
    (random()*1000000)::integer AS n,
    md5(random()::text) AS s
  FROM
    generate_series(1,1000000);

CREATE INDEX N_INDEX ON ITEMS(N);

Performing JOIN with GROUP BY in subquery without LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    GROUP BY N
) I2 ON I2.N = I.N
WHERE I.N IN (243477, 997947);

The results

Merge Join  (cost=0.87..637500.40 rows=23 width=37)
  Merge Cond: (i.n = items.n)
  ->  Index Scan using n_index on items i  (cost=0.43..101.28 rows=23 width=37)
        Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..626631.11 rows=861418 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..593016.93 rows=10000000 width=4)

Using LATERAL

EXPLAIN 
SELECT 
    I.*
FROM ITEMS I
INNER JOIN LATERAL (
    SELECT 
        COUNT(1), n
    FROM ITEMS
    WHERE N = I.N
    GROUP BY N
) I2 ON 1=1 --I2.N = I.N
WHERE I.N IN (243477, 997947);

Results

Nested Loop  (cost=9.49..1319.97 rows=276 width=37)
  ->  Bitmap Heap Scan on items i  (cost=9.06..100.20 rows=23 width=37)
        Recheck Cond: (n = ANY ('{243477,997947}'::integer[]))
        ->  Bitmap Index Scan on n_index  (cost=0.00..9.05 rows=23 width=0)
              Index Cond: (n = ANY ('{243477,997947}'::integer[]))
  ->  GroupAggregate  (cost=0.43..52.79 rows=12 width=12)
        Group Key: items.n
        ->  Index Only Scan using n_index on items  (cost=0.43..52.64 rows=12 width=4)
              Index Cond: (n = i.n)

My Postgres version is PostgreSQL 10.3 (Debian 10.3-1.pgdg90+1)

Android ViewPager with bottom dots

Following is my proposed solution.

  • Since we need to show only some images in the view pagers so have avoided the cumbersome use of fragments.
    • Implemented the view page indicators (the bottom dots without any extra library or plugin)
    • On the touch of the view page indicators(the dots) also the page navigation is happening.
    • Please don"t forget to add your own images in the resources.
    • Feel free to comment and improve upon it.

A) Following is my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="schneider.carouseladventure.MainActivity">

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:id="@+id/viewPagerIndicator"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="5dp"
        android:gravity="center">

        <LinearLayout
            android:id="@+id/viewPagerCountDots"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:orientation="horizontal" />

    </RelativeLayout>


</RelativeLayout>

B) pager_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView" />
</LinearLayout>

C) MainActivity.java

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {

    int[] mResources = {R.drawable.nature1, R.drawable.nature2, R.drawable.nature3, R.drawable.nature4,
            R.drawable.nature5, R.drawable.nature6
    };

    ViewPager mViewPager;
    private CustomPagerAdapter mAdapter;
    private LinearLayout pager_indicator;
    private int dotsCount;
    private ImageView[] dots;


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

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots);
        mAdapter = new CustomPagerAdapter(this, mResources);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
        mViewPager.setOnPageChangeListener(this);

        setPageViewIndicator();

    }

    private void setPageViewIndicator() {

        Log.d("###setPageViewIndicator", " : called");
        dotsCount = mAdapter.getCount();
        dots = new ImageView[dotsCount];

        for (int i = 0; i < dotsCount; i++) {
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            params.setMargins(4, 0, 4, 0);

            final int presentPosition = i;
            dots[presentPosition].setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mViewPager.setCurrentItem(presentPosition);
                    return true;
                }

            });


            pager_indicator.addView(dots[i], params);
        }

        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        Log.d("###onPageSelected, pos ", String.valueOf(position));
        for (int i = 0; i < dotsCount; i++) {
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
        }

        dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));

        if (position + 1 == dotsCount) {

        } else {

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

D) CustomPagerAdapter.java

 import android.content.Context;
    import android.support.v4.view.PagerAdapter;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.LinearLayout;

    public class CustomPagerAdapter extends PagerAdapter {
        private Context mContext;
        LayoutInflater mLayoutInflater;
        private int[] mResources;

        public CustomPagerAdapter(Context context, int[] resources) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mResources = resources;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View itemView = mLayoutInflater.inflate(R.layout.pager_item,container,false);
            ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
            imageView.setImageResource(mResources[position]);
           /* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(950, 950);
            imageView.setLayoutParams(layoutParams);*/
            container.addView(itemView);
            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }

        @Override
        public int getCount() {
            return mResources.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

E) selecteditem_dot.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" android:useLevel="true"
    android:dither="true">

    <size android:height="12dip" android:width="12dip"/>

    <solid android:color="#7e7e7e"/>
</shape>

F) nonselecteditem_dot.xml

 <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval" android:useLevel="true"
        android:dither="true">        
        <size android:height="12dip" android:width="12dip"/>        
        <solid android:color="#d3d3d3"/>
    </shape>

first image

enter image description here

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How to add data via $.ajax ( serialize() + extra data ) like this

Personally, I'd append the element to the form instead of hacking the serialized data, e.g.

moredata = 'your custom data here';

// do what you like with the input
$input = $('<input type="text" name="moredata"/>').val(morevalue);

// append to the form
$('#myForm').append($input);

// then..
data: $('#myForm').serialize()

That way, you don't have to worry about ? or &

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

Create an Array of Arraylists

ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}

Correct way to create rounded corners in Twitter Bootstrap

<div class="img-rounded"> will give you rounded corners.

Android: Changing Background-Color of the Activity (Main View)

Just add this below one line code in the XML file of that corresponding activity:

android:background="@android:color/black" 

it will help you for sure.

Regular Expression to get a string between parentheses in Javascript

You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:

_x000D_
_x000D_
var regExp = /\(([^)]+)\)/;_x000D_
var matches = regExp.exec("I expect five hundred dollars ($500).");_x000D_
_x000D_
//matches[1] contains the value between the parentheses_x000D_
console.log(matches[1]);
_x000D_
_x000D_
_x000D_

Breakdown:

  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses

Here is a visual explanation on RegExplained

node.js execute system command synchronously

You can achieve this using fibers. For example, using my Common Node library, the code would look like this:

result = require('subprocess').command('node -v');

nodemon not working: -bash: nodemon: command not found

in Windows OS run:

npx nodemon server.js

or add in package.json config:

...
"scripts": {
    "dev": "npx nodemon server.js"
  },
...

then run:

npm run dev

How to declare strings in C

Strings in C are represented as arrays of characters.

char *p = "String";

You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.

char p2[] = "String";

You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.

char p3[5] = "String";

You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.

char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).

http://c-faq.com/~scs/cclass/notes/sx8.html

How to create a JavaScript callback for knowing when an image is loaded?

.complete + callback

This is a standards compliant method without extra dependencies, and waits no longer than necessary:

var img = document.querySelector('img')

function loaded() {
  alert('loaded')
}

if (img.complete) {
  loaded()
} else {
  img.addEventListener('load', loaded)
  img.addEventListener('error', function() {
      alert('error')
  })
}

Source: http://www.html5rocks.com/en/tutorials/es6/promises/

How to convert char to integer in C?

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <unistd.h>

int main(int argc, char *argv[])
{
    int useconds = atoi(argv[1]); 
    usleep(useconds);
}

Move entire line up and down in Vim

Move a line up: ddkP

Move a line down: ddp

How do I convert a String object into a Hash object?

I built a gem hash_parser that first checks if a hash is safe or not using ruby_parser gem. Only then, it applies the eval.

You can use it as

require 'hash_parser'

# this executes successfully
a = "{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, 
       :key_b => { :key_1b => 'value_1b' } }"
p HashParser.new.safe_load(a)

# this throws a HashParser::BadHash exception
a = "{ :key_a => system('ls') }"
p HashParser.new.safe_load(a)

The tests in https://github.com/bibstha/ruby_hash_parser/blob/master/test/test_hash_parser.rb give you more examples of the things I've tested to make sure eval is safe.

Oracle Add 1 hour in SQL

You can use INTERVAL type or just add calculated number value - "1" is equal "1 day".

first way:

select date_column + INTERVAL '0 01:00:00' DAY TO SECOND from dual;

second way:

select date_column + 1/24 from dual;

First way is more convenient when you need to add a complicated value - for example, "1 day 3 hours 25 minutes 49 seconds". See also: http://www.oracle-base.com/articles/misc/oracle-dates-timestamps-and-intervals.php

Also you have to remember that oracle have two interval types - DAY TO SECOND and YEAR TO MONTH. As for me, one interval type would be better, but I hope people in oracle knows, what they do ;)

Ruby on Rails - Import Data from a CSV file

The better way is to include it in a rake task. Create import.rake file inside /lib/tasks/ and put this code to that file.

desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
  lines = File.new(args[:filename], "r:ISO-8859-1").readlines
  header = lines.shift.strip
  keys = header.split(',')
  lines.each do |line|
    values = line.strip.split(',')
    attributes = Hash[keys.zip values]
    Module.const_get(args[:model]).create(attributes)
  end
end

After that run this command in your terminal rake csv_model_import[file.csv,Name_of_the_Model]

Select distinct values from a large DataTable column

Try this:

var idColumn="id";
var list = dt.DefaultView
    .ToTable(true, idColumn)
    .Rows
    .Cast<DataRow>()
    .Select(row => row[idColumn])
    .ToList();

What are file descriptors, explained in simple terms?

File descriptors

  • To Kernel all open files are referred to by file descriptors.
  • A file descriptor is a non - negative integer.
  • When we open an existing or create a new file, the kernel returns a file descriptor to a process.
  • When we want to read or write on a file, we identify the file with file descriptor that was retuned by open or create, as an argument to either read or write.
  • Each UNIX process has 20 file descriptors and it disposal, numbered 0 through 19 but it was extended to 63 by many systems.
  • The first three are already opened when the process begins 0: The standard input 1: The standard output 2: The standard error output
  • When the parent process forks a process, the child process inherits the file descriptors of the parent

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

How to use executeReader() method to retrieve the value of just one cell

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
    cmd.Parameters.AddWithValue("@id", index);
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
        }
    }
}

How to get image height and width using java?

So unfortunately, after trying all the answers from above, I did not get them to work after tireless times of trying. So I decided to do the real hack myself and I go this to work for me. I trust it would work perfectly for you too.

I am using this simple method to get the width of an image generated by the app and yet to be upload later for verification :

Pls. take note : you would have to enable permissions in manifest for access storage.

/I made it static and put in my Global class so I can reference or access it from just one source and if there is any modification, it would all have to be done at just one place. Just maintaining a DRY concept in java. (anyway) :)/

public static int getImageWidthOrHeight(String imgFilePath) {

            Log.d("img path : "+imgFilePath);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFilePath, o);

            int width_tmp = o.outWidth, height_tmp = o.outHeight;

            Log.d("Image width : ", Integer.toString(width_tmp) );

            //you can decide to rather return height_tmp to get the height.

            return width_tmp;

}

C compile : collect2: error: ld returned 1 exit status

I got this problem, and tried many ways to solve it. Finally, it turned out that make clean and make again solved it. The reason is: I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean saved the day.

Kubernetes how to make Deployment to update image

I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID

Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example

imagename:buildID

once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as

imagename:env:buildID

here evn:buildid is the azure devops variable which having value of build ID.

so now every time I have new changes to build(CI) and deploy(CD).

please comment if you need build definition for CI/CD.

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

Django: Get list of model fields?

In sometimes we need the db columns as well:

def get_db_field_names(instance):
   your_fields = instance._meta.local_fields
   db_field_names=[f.name+'_id' if f.related_model is not None else f.name  for f in your_fields]
   model_field_names = [f.name for f in your_fields]
   return db_field_names,model_field_names

Call the method to get the fields:

db_field_names,model_field_names=get_db_field_names(Mymodel)

Ant build failed: "Target "build..xml" does not exist"

Looks like you called it 'ant build..xml'. ant automatically choose a file build.xml in the current directory, so it is enough to call 'ant' (if a default-target is defined) or 'ant target' (the target named target will be called).

With the call 'ant -p' you get a list of targets defined in your build.xml.

Edit: In the comment is shown the call 'ant -verbose build.xml'. To be correct, this has to be called as 'ant -verbose'. The file build.xml in the current directory will be used automatically. If it is needed to explicitly specify the buildfile (because it's name isn't build.xml for example), you have to specify the buildfile with the '-f'-option: 'ant -verbose -f build.xml'. I hope this helps.

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

MySQL error - #1062 - Duplicate entry ' ' for key 2

Error 'Duplicate entry '338620-7' for key 2' on query. Default database

For this error :

set global sql_slave_skip_counter=1; 
start slave; 
show slave status\G

This worked for me

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

Function overloading in Javascript - Best practices

You can use this methode

function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1, 2, 3);

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

How to access custom attributes from event object in React?

In React you don't need the html data, use a function return a other function; like this it's very simple send custom params and you can acces the custom data and the event.

render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag: (i) => (event) => {
    this.setState({inputVal: i}); 
},

What is "Linting"?

Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.

Linters are also useful for code formatting and/or adhering to language specific best practices.

Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.

How to get the top 10 values in postgresql?

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)

UNION ALL

(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC    
LIMIT 10)

Unable to preventDefault inside passive event listener

To handle sortable list in Framework7 when user release currently sorting element in new position, you can use this code:

  $$('li').on('sortable:sort',function(event){
    alert("From " + event.detail.startIndex + " to " + event.detail.newIndex);
  });

Fiddle : https://jsfiddle.net/0zf5w4y7/

Finding the length of a Character Array in C

There is also a compact form for that, if you do not want to rely on strlen. Assuming that the character array you are considering is "msg":

  unsigned int len=0;
  while(*(msg+len) ) len++;

How to pass ArrayList<CustomeObject> from one activity to another?

Use this code to pass arraylist<customobj> to anthother Activity

firstly serialize our contact bean

public class ContactBean implements Serializable {
      //do intialization here
}

Now pass your arraylist

 Intent intent = new Intent(this,name of activity.class);
 contactBean=(ConactBean)_arraylist.get(position);
 intent.putExtra("contactBeanObj",conactBean);
 _activity.startActivity(intent);

Casting to string in JavaScript

There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:

?var foo;

?var myString1 = String(foo); // "undefined" as a string

var myString2 = foo + ''; // "undefined" as a string

var myString3 = foo.toString(); // throws an exception

http://jsfiddle.net/f8YwA/

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

CRON job to run on the last day of the month

Set up a cron job to run on the first day of the month. Then change the system's clock to be one day ahead.

How to make HTML element resizable using pure Javascript?

I really recommend using some sort of library, but you asked for it, you get it:

var p = document.querySelector('p'); // element to make resizable

p.addEventListener('click', function init() {
    p.removeEventListener('click', init, false);
    p.className = p.className + ' resizable';
    var resizer = document.createElement('div');
    resizer.className = 'resizer';
    p.appendChild(resizer);
    resizer.addEventListener('mousedown', initDrag, false);
}, false);

var startX, startY, startWidth, startHeight;

function initDrag(e) {
   startX = e.clientX;
   startY = e.clientY;
   startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
   startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
   document.documentElement.addEventListener('mousemove', doDrag, false);
   document.documentElement.addEventListener('mouseup', stopDrag, false);
}

function doDrag(e) {
   p.style.width = (startWidth + e.clientX - startX) + 'px';
   p.style.height = (startHeight + e.clientY - startY) + 'px';
}

function stopDrag(e) {
    document.documentElement.removeEventListener('mousemove', doDrag, false);
    document.documentElement.removeEventListener('mouseup', stopDrag, false);
}

Demo

Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).

How to convert Rows to Columns in Oracle?

If you are using Oracle 10g, you can use the DECODE function to pivot the rows into columns:

CREATE TABLE doc_tab (
  loan_number VARCHAR2(20),
  document_type VARCHAR2(20),
  document_id VARCHAR2(20)
);

INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');

COMMIT;

SELECT
    loan_number,
    MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
    MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
    MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
  FROM
    doc_tab
GROUP BY loan_number
ORDER BY loan_number;

Output:

LOAN_NUMBER   VOTERS_ID            PAN_CARD             DRIVERS_LICENCE    
------------- -------------------- -------------------- --------------------
992452533663  XPD0355636           CHXPS5522D           DL-0420110141769     

You can achieve the same using Oracle PIVOT clause, introduced in 11g:

SELECT *
  FROM doc_tab
PIVOT (
  MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);

SQLFiddle example with both solutions: SQLFiddle example

Read more about pivoting here: Pivot In Oracle by Tim Hall

Remove sensitive files and their commits from Git history

If you pushed to GitHub, force pushing is not enough, delete the repository or contact support

Even if you force push one second afterwards, it is not enough as explained below.

The only valid courses of action are:

  • is what leaked a changeable credential like a password?

    • yes: modify your passwords immediately, and consider using more OAuth and API keys!

    • no (naked pics):

      • do you care if all issues in the repository get nuked?

        • no: delete the repository

        • yes:

          • contact support
          • if the leak is very critical to you, to the point that you are willing to get some repository downtime to make it less likely to leak, make it private while you wait for GitHub support to reply to you

Force pushing a second later is not enough because:

If you delete the repository instead of just force pushing however, commits do disappear even from the API immediately and give 404, e.g. https://api.github.com/repos/cirosantilli/test-dangling-delete/commits/8c08448b5fbf0f891696819f3b2b2d653f7a3824 This works even if you recreate another repository with the same name.

To test this out, I have created a repo: https://github.com/cirosantilli/test-dangling and did:

git init
git remote add origin [email protected]:cirosantilli/test-dangling.git

touch a
git add .
git commit -m 0
git push

touch b
git add .
git commit -m 1
git push

touch c
git rm b
git add .
git commit --amend --no-edit
git push -f

See also: How to remove a dangling commit from GitHub?

git filter-repo is now officially recommended over git filter-branch

This is mentioned in the manpage of git filter-branch in Git 2.5 itself.

With git filter repo, you could either remove certain files with: Remove folder and its contents from git/GitHub's history

pip install git-filter-repo
git filter-repo --path path/to/remove1 --path path/to/remove2 --invert-paths

This automatically removes empty commits.

Or you can replace certain strings with: How to replace a string in a whole Git history?

git filter-repo --replace-text <(echo 'my_password==>xxxxxxxx')

Difference between a User and a Login in SQL Server

I think there is a really good MSDN blog post about this topic by Laurentiu Cristofor:

The first important thing that needs to be understood about SQL Server security is that there are two security realms involved - the server and the database. The server realm encompasses multiple database realms. All work is done in the context of some database, but to get to do the work, one needs to first have access to the server and then to have access to the database.

Access to the server is granted via logins. There are two main categories of logins: SQL Server authenticated logins and Windows authenticated logins. I will usually refer to these using the shorter names of SQL logins and Windows logins. Windows authenticated logins can either be logins mapped to Windows users or logins mapped to Windows groups. So, to be able to connect to the server, one must have access via one of these types or logins - logins provide access to the server realm.

But logins are not enough, because work is usually done in a database and databases are separate realms. Access to databases is granted via users.

Users are mapped to logins and the mapping is expressed by the SID property of logins and users. A login maps to a user in a database if their SID values are identical. Depending on the type of login, we can therefore have a categorization of users that mimics the above categorization for logins; so, we have SQL users and Windows users and the latter category consists of users mapped to Windows user logins and of users mapped to Windows group logins.

Let's take a step back for a quick overview: a login provides access to the server and to further get access to a database, a user mapped to the login must exist in the database.

that's the link to the full post.

Rename multiple files in a folder, add a prefix (Windows)

The problem with the two Powershell answers here is that the prefix can end up being duplicated since the script will potentially run over the file both before and after it has been renamed, depending on the directory being resorted as the renaming process runs. To get around this, simply use the -Exclude option:

Get-ChildItem -Exclude "house chores-*" | rename-item -NewName { "house chores-" + $_.Name }

This will prevent the process from renaming any one file more than once.

How to Sign an Already Compiled Apk

You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

  1. npm install --save-dev "cross-env" module.
  2. modify the code as cross-env NODE_ENV=development node foo.js. Then you can run the like npm run build.

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

How do I pre-populate a jQuery Datepicker textbox with today's date?

Try this

$(this).datepicker("destroy").datepicker({
            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"
        }).focus();

How do I concatenate two lists in Python?

It's also possible to create a generator that simply iterates over the items in both lists using itertools.chain(). This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

import itertools
for item in itertools.chain(listone, listtwo):
    # Do something with each list item

Authentication versus Authorization

As Authentication vs Authorization puts it:

Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:

  • Who is the user?
  • Is the user really who he/she represents himself to be?

Authorization, by contrast, is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:

  • Is user X authorized to access resource R?
  • Is user X authorized to perform operation P?
  • Is user X authorized to perform operation P on resource R?

See also:

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

In Android studio 0.8 and after Right click on app folder then New > Image Asset

Browse for best resolution image you have in "Image file" field

hit Next The rest will be generated

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

What's the difference between SoftReference and WeakReference in Java?

The six types of object reachability states in Java:

  1. Strongly reachable objects - GC will not collect (reclaim the memory occupied by) this kind of object. These are reachable via a root node or another strongly reachable object (i.e. via local variables, class variables, instance variables, etc.)
  2. Softly reachable objects - GC may attempt to collect this kind of object depending on memory contention. These are reachable from the root via one or more soft reference objects
  3. Weakly reachable objects - GC must collect this kind of object. These are reachable from the root via one or more weak reference objects
  4. Resurrect-able objects - GC is already in the process of collecting these objects. But they may go back to one of the states - Strong/Soft/Weak by the execution of some finalizer
  5. Phantomly reachable object - GC is already in the process of collecting these objects and has determined to not be resurrect-able by any finalizer (if it declares a finalize() method itself, then its finalizer will have been run). These are reachable from the root via one or more phantom reference objects
  6. Unreachable object - An object is neither strongly, softly, weakly, nor phantom reachable, and is not resurrectable. These objects are ready for reclamation

For more details: https://www.artima.com/insidejvm/ed2/gc16.html « collapse

jquery - is not a function error

When converting an ASP.Net webform prototype to a MVC site I got these errors:

TypeError: $(...).accordion is not a function
$("#accordion").accordion(


$('#dialog').dialog({
TypeError: $(...).dialog is not a function

It worked fine in the webforms. The problem/solution was this line in the _Layout.cshtml

@Scripts.Render("~/bundles/jquery")

Comment it out to see if the errors go away. Then fix it in the BundlesConfig:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

What is the equivalent to getLastInsertId() in Cakephp?

When you use save(), the last insert ID is set to the model’s $id property. So:

if ($this->Model->save()) {
    printf('Last insert ID was %s', $this->Model->id);
}

Is there a way to define a min and max value for EditText in Android?

There is a small error in Pratik's code. For instance, if a value is 10 and you add a 1 at the beginning to make 110, the filter function would treat the new value as 101.

See below for a fix to this:

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    try {
        // Removes string that is to be replaced from destination
        // and adds the new string in.
        String newVal = dest.subSequence(0, dstart)
                // Note that below "toString()" is the only required:
                + source.subSequence(start, end).toString()
                + dest.subSequence(dend, dest.length());
        int input = Integer.parseInt(newVal);
        if (isInRange(min, max, input))
            return null;
    } catch (NumberFormatException nfe) { }
    return "";
}

Use YAML with variables

I had this same question, and after a lot of research, it looks like it's not possible.

The answer from cgat is on the right track, but you can't actually concatenate references like that.

Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):

Define a value and use an exact copy of it later:

default: &default_title This Post Has No Title
title: *default_title

{ or }

example_post: &example
  title: My mom likes roosters
  body: Seriously, she does. And I don't know when it started.
  date: 8/18/2012
first_post: *example
second_post:
  title: whatever, etc.

For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References

Define an object and use it with modifications later:

default: &DEFAULT
  URL:          stooges.com
  throw_pies?:  true  
  stooges:  &stooge_list
    larry:  first_stooge
    moe:    second_stooge
    curly:  third_stooge

development:
  <<: *DEFAULT
  URL:      stooges.local
  stooges: 
    shemp: fourth_stooge

test:
  <<: *DEFAULT
  URL:    test.stooges.qa
  stooges: 
    <<: *stooge_list
    shemp: fourth_stooge

This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804

ImportError: No module named MySQLdb

Got so many errors related to permissions and what not. You may wanna try this :

xcode-select --install

How do I add a Fragment to an Activity with a programmatically created content view

After read all Answers I came up with elegant way:

public class MyActivity extends ActionBarActivity {

 Fragment fragment ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FragmentManager fm = getSupportFragmentManager();
    fragment = fm.findFragmentByTag("myFragmentTag");
    if (fragment == null) {
        FragmentTransaction ft = fm.beginTransaction();
        fragment =new MyFragment();
        ft.add(android.R.id.content,fragment,"myFragmentTag");
        ft.commit();
    }

}

basically you don't need to add a frameLayout as container of your fragment instead you can add straight the fragment into the android root View container

IMPORTANT: don't use replace fragment as most of the approach shown here, unless you don't mind to lose fragment variable instance state during onrecreation process.

Using npm behind corporate proxy .pac

Adding the lines below in the .typingsrc file helped me.

{
    "rejectUnauthorized": false,
    "registryURL" :"http://api.typings.org/"
 }

How to exclude a directory in find . command

You can also use regular expressions to include / exclude some files /dirs your search using something like this:

find . -regextype posix-egrep -regex ".*\.(js|vue|s?css|php|html|json)$" -and -not -regex ".*/(node_modules|vendor)/.*" 

This will only give you all js, vue, css, etc files but excluding all files in the node_modules and vendor folders.

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

import { map } from 'rxjs/operators';

this works for me in angular 8

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Getting the parent of a directory in Bash

Clearly the parent directory is given by simply appending the dot-dot filename:

/home/smith/Desktop/Test/..     # unresolved path

But you must want the resolved path (an absolute path without any dot-dot path components):

/home/smith/Desktop             # resolved path

The problem with the top answers that use dirname, is that they don't work when you enter a path with dot-dots:

$ dir=~/Library/../Desktop/../..
$ parentdir="$(dirname "$dir")"
$ echo $parentdir
/Users/username/Library/../Desktop/..   # not fully resolved

This is more powerful:

dir=/home/smith/Desktop/Test
parentdir=$(builtin cd $dir; pwd)

You can feed it /home/smith/Desktop/Test/.., but also more complex paths like:

$ dir=~/Library/../Desktop/../..
$ parentdir=$(builtin cd $dir; pwd)
$ echo $parentdir
/Users                                  # the fully resolved path!
 

NOTE: use of builtin ensures no user defined function variant of cd is called, but rather the default utility form which has no output.