Programs & Examples On #Xpsdocument

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

Difference between "enqueue" and "dequeue"

Enqueue means to add an element, dequeue to remove an element.

var stackInput= []; // First stack
var stackOutput= []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

How an 'if (A && B)' statement is evaluated?

for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
}else{
}
if( (A) ||(B) ){
     //if A or B is true 
}else{
}

jquery - Check for file extension before uploading

If you want to do it without a plugin you could use the following.

Javascript, using jQuery:

$(document).ready( function (){
    $("#your_form").submit( function(submitEvent) {

        // get the file name, possibly with path (depends on browser)
        var filename = $("#file_input").val();

        // Use a regular expression to trim everything before final dot
        var extension = filename.replace(/^.*\./, '');

        // Iff there is no dot anywhere in filename, we would have extension == filename,
        // so we account for this possibility now
        if (extension == filename) {
            extension = '';
        } else {
            // if there is an extension, we convert to lower case
            // (N.B. this conversion will not effect the value of the extension
            // on the file upload.)
            extension = extension.toLowerCase();
        }

        switch (extension) {
            case 'jpg':
            case 'jpeg':
            case 'png':
                alert("it's got an extension which suggests it's a PNG or JPG image (but N.B. that's only its name, so let's be sure that we, say, check the mime-type server-side!)");

            // uncomment the next line to allow the form to submitted in this case:
//          break;

            default:
                // Cancel the form submission
                submitEvent.preventDefault();
        }

  });
});

HTML:

<form id="your_form" method="post" enctype="multipart/form-data">
    <input id="file_input" type="file" />
    <input type="submit">
</form>

Excel is not updating cells, options > formula > workbook calculation set to automatic

In short

creating or moving some/all reference containing worksheets (out and) into your workbook may solve it.

More details

I had this issue after copying some sheets from "template" sheets/workbooks to some new "destination" workbook (the templates were provided by other users!):

I got:

  • workbook WbTempl1
    • with sheet WsTempl1RefDef (defining the references used e.g. in WsTempl2RefUsr below, e.g. project on A1)
  • workbook WbTempl2 (above references do not exist, because WsTempl1RefDef is not contained nor externally referenced, e.g. like WbTempl2.Names("project").refersTo="C:\WbTempl1.xls]'WsTempl1RefDef!A1")
    • contains sheet WsTempl2RefUsr (uses inexisting global references, e.g. =project)

and wanted to create a WbDst to copy WsTempl1RefDef and WsTempl2RefUsr into it.


The following did not work:

  1. create workbook WbDst
  2. copy sheet WsTempl1RefDef into it (references were locally created)
  3. copy sheet WsTempl2RefUsr into it

Here as well the Ctrl(SHIFT)ALTF9 nor Application.CalculateFullRebuild worked on WbDst.


The following worked:

  1. create workbook WbDst
  2. move (not copy) sheet WsTempl1RefDef into WbTempl2
    • (we do not have to save them)
  3. copy sheet WsTempl1RefDef into WbDst
  4. copy sheet WsTempl2RefUsr into WbDst

Laravel - Model Class not found

Make sure to be careful when editing your model file. For example, in your post model:

<?php 
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    protected $table = 'posts';    
}

You need to pay close attention to the class Post extend Model line. The class Post defined here will be your namespace for your controller.

How get an apostrophe in a string in javascript

You can use double quotes instead of single quotes:

theAnchorText = "I'm home";

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home';

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

How can I create a border around an Android LinearLayout?

you can do it Pragmatically also

  GradientDrawable gradientDrawable=new GradientDrawable();
   gradientDrawable.setStroke(4,getResources().getColor(R.color.line_Input));

Then set the background of layout as :

LinearLayout layout = (LinearLayout ) findViewById(R.id.ayout); layout .setBackground(gradientDrawable);

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had the same problem, and my solving was to replace :

return redirect(url_for('index'))

with

return render_template('indexo.html',data=Todos.query.all())

in my POST and DELETE route.

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

Can the Android drawable directory contain subdirectories?

There is a workaround for this situation: you can create a resVector (for example) folder on the same level as default res folder. There you can add any drawable-xxx resource folders there:

resVector
-drawable
-layout
-color

After that all you need is to add

sourceSets {
        main.res.srcDirs += 'src/main/resVector'
    }

into your build.gradle file (inside android { }).

How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

How to detect a remote side socket close?

Since the answers deviate I decided to test this and post the result - including the test example.

The server here just writes data to a client and does not expect any input.

The server:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
  • clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • out.checkError() is true as soon as the client is disconnected so I recommend this

How to stop app that node.js express 'npm start'

Check with netstat -nptl all processes

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      1736/mongod     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1594/sshd       
tcp6       0      0 :::3977                 :::*                    LISTEN      6231/nodejs     
tcp6       0      0 :::22                   :::*                    LISTEN      1594/sshd       
tcp6       0      0 :::3200                 :::*                    LISTEN      5535/nodejs 

And it simply kills the process by the PID reference.... In my case I want to stop the 6231/nodejs so I execute the following command:

kill -9 6231

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

I've SSL on Apache2.4.4 and executing this code at first, did the trick:
set OPENSSL_CONF=C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf

then execute the rest codes..

How do I get the current date and time in PHP?

Very simple

date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y H:i:s', time());

How to terminate a Python script

import sys
sys.exit()

details from the sys module documentation:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use os._exit(*errorcode*), though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it does kill the entire process, including all running threads, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

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

simply use "$last_id = mysqli_insert_id($conn);"

How to clean up R memory (without the need to restart my PC)?

Maybe you can try to use the function gc(). A call of gc() causes a garbage collection to take place. It can be useful to call gc() after a large object has been removed, as this may prompt R to return memory to the operating system. gc() also return a summary of the occupy memory.

Tkinter understanding mainloop

I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).

In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!

As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.

import Tkinter as tk

class Window(tk.Frame):
    def __init__(self, master=None, view=None ):
        tk.Frame.__init__( self, master )
        self.view_ = view       
        """ Setup window linking it to the view... """

class GuiView( MyViewSuperClass ):

    def open( self ):
        self.tkRoot_ = tk.Tk()
        self.window_ = Window( master=None, view=self )
        self.window_.pack()
        self.refresh()
        self.onOpen()
        self.tkRoot_.mainloop()         

    def onOpen( self ):        
        """ Do some initial tasks... """

    def refresh( self ):        
        self.tkRoot_.update()

How to check if there exists a process with a given pid in Python?

The answers involving sending 'signal 0' to the process will work only if the process in question is owned by the user running the test. Otherwise you will get an OSError due to permissions, even if the pid exists in the system.

In order to bypass this limitation you can check if /proc/<pid> exists:

import os

def is_running(pid):
    if os.path.isdir('/proc/{}'.format(pid)):
        return True
    return False

This applies to linux based systems only, obviously.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

How to use onClick() or onSelect() on option tag in a JSP page?

in this example de select tag is named as: aula_clase_cb

<select class="form-control" id="aula_clase_cb" >
</select>

document.getElementById("aula_clase_cb").onchange = function(e){
    id = document.getElementById('aula_clase_cb').value;
    alert("id: "+id);
};

Transaction marked as rollback only: How do I find the cause

apply the below code in productRepository

@Query("update Product set prodName=:name where prodId=:id ") @Transactional @Modifying int updateMyData(@Param("name")String name, @Param("id") Integer id);

while in junit test apply below code

@Test
public void updateData()
{
  int i=productRepository.updateMyData("Iphone",102);

  System.out.println("successfully updated ... ");
  assertTrue(i!=0);

}

it is working fine for my code

How do I get extra data from intent on Android?

In the receiving activity

Bundle extras = getIntent().getExtras(); 
String userName;

if (extras != null) {
    userName = extras.getString("name");
    // and get whatever type user account id is
}

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

How to completely uninstall Android Studio from windows(v10)?

To Completely Remove Android Studio from Windows:

Step 1: Run the Android Studio uninstaller

The first step is to run the uninstaller. Open the Control Panel and under Programs, select Uninstall a Program. After that, click on "Android Studio" and press Uninstall. If you have multiple versions, uninstall them as well.

Step 2: Remove the Android Studio files

To delete any remains of Android Studio setting files, in File Explorer, go to your user folder (%USERPROFILE%), and delete .android, .AndroidStudio and any analogous directories with versions on the end, i.e. .AndroidStudio1.2, as well as .gradle and .m2 if they exist.

Then go to %APPDATA% and delete the JetBrains directory.

Finally, go to C:\Program Files and delete the Android directory.

Step 3: Remove SDK

To delete any remains of the SDK, go to %LOCALAPPDATA% and delete the Android directory.

Step 4: Delete Android Studio projects

Android Studio creates projects in a folder %USERPROFILE%\AndroidStudioProjects, which you may want to delete.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

You can use a while loop.

Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry<String, String> entry = iterator.next();
    if(entry.getKey().equals("test")) {
        iterator.remove();
    } 
}

What does auto do in margin:0 auto?

It becomes clearer with some explanation of how the two values work.

The margin property is shorthand for:

margin-top
margin-right
margin-bottom
margin-left

So how come only two values?

Well, you can express margin with four values like this:

margin: 10px, 20px, 15px, 5px;

which would mean 10px top, 20px right, 15px bottom, 5px left

Likewise you can also express with two values like this:

margin: 20px 10px;

This would give you a margin 20px top and bottom and 10px left and right.

And if you set:

margin: 20px auto;

Then that means top and bottom margin of 20px and left and right margin of auto. And auto means that the left/right margin are automatically set based on the container. If your element is a block type element, meaning it is a box and takes up the entire width of the view, then auto sets the left and right margin the same and hence the element is centered.

Mockito: Trying to spy on method is calling the original method

Bit late to the party but above solutions did not work for me , so sharing my 0.02$

Mokcito version: 1.10.19

MyClass.java

private int handleAction(List<String> argList, String action)

Test.java

MyClass spy = PowerMockito.spy(new MyClass());

Following did NOT work for me (actual method was being called):

1.

doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());

2.

doReturn(0).when(spy , "handleAction", any(), anyString());

3.

doReturn(0).when(spy , "handleAction", null, null);

Following WORKED:

doReturn(0).when(spy , "handleAction", any(List.class), anyString());

Adding images to an HTML document with javascript

This works:

var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)

Or using jQuery:

$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');

How to access data/data folder in Android device?

may be to access this folder you need administrative rights.

so you have two options:-

  1. root your device and than try to access this folder
  2. use emulator

p.s. : if you are using any of above two options you can access this folder by following these steps

open DDMS perspective -> your device ->(Select File Explorer from right window options) select package -> data -> data -> package name ->files

and from there you can pull up your file

How to iterate over a JavaScript object?

If you have a simple object you can iterate through it using the following code:

_x000D_
_x000D_
let myObj = {
  abc: '...',
  bca: '...',
  zzz: '...',
  xxx: '...',
  ccc: '...',
  // ...
};

let objKeys = Object.keys(myObj);

//Now we can use objKeys to iterate over myObj

for (item of objKeys) {
  //this will print out the keys
  console.log('key:', item);
  
  //this will print out the values 
  console.log('value:', myObj[item]);
}
_x000D_
_x000D_
_x000D_

If you have a nested object you can iterate through it using the following code:

_x000D_
_x000D_
let b = {
  one: {
    a: 1,
    b: 2,
    c: 3
  },
  two: {
    a: 4,
    b: 5,
    c: 6
  },
  three: {
    a: 7,
    b: 8,
    c: 9
  }
};

let myKeys = Object.keys(b);

for (item of myKeys) {
  //print the key
  console.log('Key', item)
  
  //print the value (which will be another object)
  console.log('Value', b[item])
  
  //print the nested value
  console.log('Nested value', b[item]['a'])
}
_x000D_
_x000D_
_x000D_

If you have array of objects you can iterate through it using the following code:

_x000D_
_x000D_
let c = [
{
  a: 1,
  b: 2
},
{
  a: 3,
  b: 4
}
];

for(item of c){
//print the whole object individually 
console.log('object', item);

//print the value inside the object
console.log('value', item['a']);
}
_x000D_
_x000D_
_x000D_

Reading Properties file in Java

I see that the question is an old one. If anyone stumbles upon this in the future, I think this is one simple way of doing it. Keep the properties file in your project folder.

        FileReader reader = new FileReader("Config.properties");

        Properties prop = new Properties();
        prop.load(reader);

Variable might not have been initialized error

You declared them, but you didn't initialize them with a value. Add something like this:

int a = 0;

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

.m2 , settings.xml in Ubuntu

You can find your maven files here:

cd ~/.m2

Probably you need to copy settings.xml in your .m2 folder:

cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/

If no .m2 folder exists:

mkdir -p ~/.m2

How to submit a form using Enter key in react.js?

It's been quite a few years since this question was last answered. React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.

Now we can write this:

  useEffect(() => {
    const listener = event => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        console.log("Enter key was pressed. Run your function.");
        // callMyFunction();
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);

This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.

Selector on background color of TextView

An even simpler solution to the above:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <color android:color="@color/semitransparent_white" />
    </item>
    <item>
        <color android:color="@color/transparent" />
    </item>
</selector>

Save that in the drawable folder and you're good to go.

Difference between onStart() and onResume()

Not sure if this counts as an answer - but here is YouTube Video From Google's Course (Developing Android Apps with Kotlin) that explains the difference.

  • On Start is called when the activity becomes visible
  • On Pause is called when the activity loses focus (like a dialog pops up)
  • On Resume is called when the activity gains focus (like when a dialog disappears)

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

JavaScript: Is there a way to get Chrome to break on all errors?

Edit: The original link I answered with is now invalid.The newer URL would be https://developers.google.com/web/tools/chrome-devtools/javascript/add-breakpoints#exceptions as of 2016-11-11.

I realize this question has an answer, but it's no longer accurate. Use the link above ^


(link replaced by edited above) - you can now set it to break on all exceptions or just unhandled ones. (Note that you need to be in the Sources tab to see the button.)

Chrome's also added some other really useful breakpoint capabilities now, such as breaking on DOM changes or network events.

Normally I wouldn't re-answer a question, but I had the same question myself, and I found this now-wrong answer, so I figured I'd put this information in here for people who came along later in searching. :)

How can I find a file/directory that could be anywhere on linux command line?

Below example will help to find the specific folder in the current directory. This example only search current direct and it'll search sub directory available in the current directory

#!/bin/bash

result=$(ls -d operational)

echo $result

test="operational"

if [ "$result" == "$test" ] 
then 
   echo "TRUE"
else
   echo "FALSE"
fi

Error With Port 8080 already in use

if you are running from inside eclipse with wtp, you should be able to change the port from the "servers" view (window -> show view -> servers)

Make one div visible and another invisible

I don't think that you really want an iframe, do you?

Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?

For your white box / extra space issue, try

style="display: none;"

instead of

style="visibility: hidden;"

Can I add color to bootstrap icons only using CSS?

It is actually very easy:

just use:

.icon-name{
color: #0C0;}

For example:

.icon-compass{
color: #C30;}

That's it.

foreach with index

I like being able to use foreach, so I made an extension method and a structure:

public struct EnumeratedInstance<T>
{
    public long cnt;
    public T item;
}

public static IEnumerable<EnumeratedInstance<T>> Enumerate<T>(this IEnumerable<T> collection)
{
    long counter = 0;
    foreach (var item in collection)
    {
        yield return new EnumeratedInstance<T>
        {
            cnt = counter,
            item = item
        };
        counter++;
    }
}

and an example use:

foreach (var ii in new string[] { "a", "b", "c" }.Enumerate())
{
    Console.WriteLine(ii.item + ii.cnt);
}

One nice thing is that if you are used to the Python syntax, you can still use it:

foreach (var ii in Enumerate(new string[] { "a", "b", "c" }))

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Best way to center a <div> on a page vertically and horizontally?

In case you know a defined sized for your div you could use calc.

Live example: https://jsfiddle.net/o8416eq3/

Notes: This works only if you hard coded the width and height of your ``div` in the CSS.

_x000D_
_x000D_
#target {_x000D_
  position:fixed;_x000D_
  top: calc(50vh - 100px/2);_x000D_
  left: calc(50vw - 200px/2);_x000D_
  width:200px;_x000D_
  height:100px;_x000D_
  background-color:red;_x000D_
}
_x000D_
<div id='target'></div>
_x000D_
_x000D_
_x000D_

Remove scroll bar track from ScrollView in Android

By using below, solved the problem

android:scrollbarThumbVertical="@null"

typedef struct vs struct definitions

The typedef, as it is with other constructs, is used to give a data type a new name. In this case it is mostly done in order to make the code cleaner:

struct myStruct blah;

vs.

myStruct blah;

How to correctly use "section" tag in HTML5?

The correct method is #2. You used the section tag to define a section of your document. From the specs http://www.w3.org/TR/html5/sections.html:

The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead

"webxml attribute is required" error in Maven

The value of my webXml tag needed to look like this in order to work:

<webXml>${project.basedir}\src\main\webapp\WEB-INF\web.xml</webXml> 

How to use foreach with a hash reference?

foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

How to change Angular CLI favicon

For future readers, if this happens to you, your browser wants to use the old cached favicon.

Follow these steps:

  1. Hold CTRL and click the "Refresh" button in your browser.
  2. Hold Shift and click the "Refresh" button in your browser.

Fixed.

How to use timeit module

I'll let you in on a secret: the best way to use timeit is on the command line.

On the command line, timeit does proper statistical analysis: it tells you how long the shortest run took. This is good because all error in timing is positive. So the shortest time has the least error in it. There's no way to get negative error because a computer can't ever compute faster than it can compute!

So, the command-line interface:

%~> python -m timeit "1 + 2"
10000000 loops, best of 3: 0.0468 usec per loop

That's quite simple, eh?

You can set stuff up:

%~> python -m timeit -s "x = range(10000)" "sum(x)"
1000 loops, best of 3: 543 usec per loop

which is useful, too!

If you want multiple lines, you can either use the shell's automatic continuation or use separate arguments:

%~> python -m timeit -s "x = range(10000)" -s "y = range(100)" "sum(x)" "min(y)"
1000 loops, best of 3: 554 usec per loop

That gives a setup of

x = range(1000)
y = range(100)

and times

sum(x)
min(y)

If you want to have longer scripts you might be tempted to move to timeit inside a Python script. I suggest avoiding that because the analysis and timing is simply better on the command line. Instead, I tend to make shell scripts:

 SETUP="

 ... # lots of stuff

 "

 echo Minmod arr1
 python -m timeit -s "$SETUP" "Minmod(arr1)"

 echo pure_minmod arr1
 python -m timeit -s "$SETUP" "pure_minmod(arr1)"

 echo better_minmod arr1
 python -m timeit -s "$SETUP" "better_minmod(arr1)"

 ... etc

This can take a bit longer due to the multiple initialisations, but normally that's not a big deal.


But what if you want to use timeit inside your module?

Well, the simple way is to do:

def function(...):
    ...

timeit.Timer(function).timeit(number=NUMBER)

and that gives you cumulative (not minimum!) time to run that number of times.

To get a good analysis, use .repeat and take the minimum:

min(timeit.Timer(function).repeat(repeat=REPEATS, number=NUMBER))

You should normally combine this with functools.partial instead of lambda: ... to lower overhead. Thus you could have something like:

from functools import partial

def to_time(items):
    ...

test_items = [1, 2, 3] * 100
times = timeit.Timer(partial(to_time, test_items)).repeat(3, 1000)

# Divide by the number of repeats
time_taken = min(times) / 1000

You can also do:

timeit.timeit("...", setup="from __main__ import ...", number=NUMBER)

which would give you something closer to the interface from the command-line, but in a much less cool manner. The "from __main__ import ..." lets you use code from your main module inside the artificial environment created by timeit.

It's worth noting that this is a convenience wrapper for Timer(...).timeit(...) and so isn't particularly good at timing. I personally far prefer using Timer(...).repeat(...) as I've shown above.


Warnings

There are a few caveats with timeit that hold everywhere.

  • Overhead is not accounted for. Say you want to time x += 1, to find out how long addition takes:

    >>> python -m timeit -s "x = 0" "x += 1"
    10000000 loops, best of 3: 0.0476 usec per loop
    

    Well, it's not 0.0476 µs. You only know that it's less than that. All error is positive.

    So try and find pure overhead:

    >>> python -m timeit -s "x = 0" ""      
    100000000 loops, best of 3: 0.014 usec per loop
    

    That's a good 30% overhead just from timing! This can massively skew relative timings. But you only really cared about the adding timings; the look-up timings for x also need to be included in overhead:

    >>> python -m timeit -s "x = 0" "x"
    100000000 loops, best of 3: 0.0166 usec per loop
    

    The difference isn't much larger, but it's there.

  • Mutating methods are dangerous.

    >>> python -m timeit -s "x = [0]*100000" "while x: x.pop()"
    10000000 loops, best of 3: 0.0436 usec per loop
    

    But that's completely wrong! x is the empty list after the first iteration. You'll need to reinitialize:

    >>> python -m timeit "x = [0]*100000" "while x: x.pop()"
    100 loops, best of 3: 9.79 msec per loop
    

    But then you have lots of overhead. Account for that separately.

    >>> python -m timeit "x = [0]*100000"                   
    1000 loops, best of 3: 261 usec per loop
    

    Note that subtracting the overhead is reasonable here only because the overhead is a small-ish fraction of the time.

    For your example, it's worth noting that both Insertion Sort and Tim Sort have completely unusual timing behaviours for already-sorted lists. This means you will require a random.shuffle between sorts if you want to avoid wrecking your timings.

how to fire event on file select

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.
    });

The APK file does not exist on disk

I got it to work by:

  1. Closing the project
  2. From the Android Studio Welcome Window (or File > New), click on Import Project.

I guess that forced it to reinstall the APK, and now everything is running fine.

How do I close a tkinter window?

import Tkinter as tk

def quit(root):
    root.destroy()

root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

How do I float a div to the center?

If for some reason you have position absolute on the div, do this:

<div class="something"></div>

.something {
    position:absolute;
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto;
}

Using jQuery to center a DIV on the screen

I put a jquery plugin here

VERY SHORT VERSION

$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});

SHORT VERSION

(function($){
    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2;
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    }); 
})(jQuery);

Activated by this code :

$('#mainDiv').center();

PLUGIN VERSION

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                    vertical:true, // booleen, center vertical
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);

Activated by this code :

$(document).ready(function(){
    $('#mainDiv').center();
    $(window).bind('resize', function() {
        $('#mainDiv').center({transition:300});
    });
);

is that right ?

UPDATE :

From CSS-Tricks

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); /* Yep! */
  width: 48%;
  height: 59%;
}

Call a VBA Function into a Sub Procedure

Procedures in a Module start being useful and generic when you pass in arguments.

For example:

Public Function DoSomethingElse(strMessage As String)  
    MsgBox strMessage
End Function

Can now display any message that is passed in with the string variable called strMessage.

Why does AngularJS include an empty option in select?

Refer the example from angularjs documentation how to overcome these issues.

  1. Go to this documentation link here
  2. Find 'Binding select to a non-string value via ngModel parsing / formatting'
  3. There u can see there, directive called 'convertToNumber' solve the issue.

It works for me. Can also see how it works here

How can I resolve the error: "The command [...] exited with code 1"?

For me : I have a white space in my path's folder name G:\Other Imp Projects\Mi.....

Solution 1 :

Remove white space from folder

Example: Other Imp Projects ->> Other_Imp_Projects

Solution 2:

add Quote ("") for your path.

Example: mkdir "$(ProjectDir)$(OutDir)Configurations" //see double quotes

how to change background image of button when clicked/focused?

you can implement in a xml file for this as follows:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/your_imagename_while_focused"/>
<item android:state_pressed="true" android:drawable="@drawable/your_imagename_while_pressed" />
<item android:drawable="@drawable/image_name_while_notpressed" />  //means normal
</selector>

now save this xml file in drawable folder and name it suppos abc.xml and set it as follows

 Button tiny = (Button)findViewById(R.id.tiny);
 tiny.setBackgroundResource(R.drawable.abc);

Hope it will help you. :)

Maven project.build.directory

You can find the most up to date answer for the value in your project just execute the

mvn3 help:effective-pom

command and find the <build> ... <directory> tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

If you don't have a common way to atomically update or insert (e.g., via a transaction) then you can fallback to another locking scheme. A 0-byte file, system mutex, named pipe, etc...

how to end ng serve or firebase serve

You can use the following command to end an ongoing process:

ctrl + c

What does int argc, char *argv[] mean?

argv and argc are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments.

Try the following program:

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}

Running it with ./test a1 b2 c3 will output

Have 4 arguments:
./test
a1
b2
c3

Unity 2d jumping script

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

Changing the current working directory in Java?

I have tried to invoke

String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());

It seems to work. But

File myFile = new File("localpath.ext"); InputStream openit = new FileInputStream(myFile);

throws a FileNotFoundException though

myFile.getAbsolutePath()

shows the correct path. I have read this. I think the problem is:

  • Java knows the current directory with the new setting.
  • But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.

The solution may be:

File myFile = new File(System.getPropety("user.dir"), "localpath.ext");

It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.

~~~~JcHartmut

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

This is how it can be fixed easily in iOS 11 and Xcode 9.1 through Storyboard:

Select Table View > Size Inspector > Content Insets: Never

Merging cells in Excel using Apache POI

i made a method that merge cells and put border.

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}



protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

What is the correct format to use for Date/Time in an XML file

If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ")); That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.

Finding the position of bottom of a div with jquery

EDIT: this solution is now in the original answer too.

The accepted answer is not quite correct. You should not be using the position() function since it is relative to the parent. If you are doing global positioning(in most cases?) you should only add the offset top with the outerheight like so:

var actualBottom = $(selector).offset().top + $(selector).outerHeight(true);

The docs http://api.jquery.com/offset/

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

The following steps fix the problem for VS 2015 and VS 2017:


Close VS.

Navigate to the folder of the solution and delete the hidden .vs folder.

open VS.

Hit F5 and IIS Express should load as normal, allowing you to debug.

PHP strtotime +1 month adding an extra month

 $endOfCycle = date("Y-m", mktime(0, 0, 0, date("m", time())+1 , 15, date("m", time())));

Expanding a parent <div> to the height of its children

_x000D_
_x000D_
#childRightCol_x000D_
{_x000D_
float:right;_x000D_
}_x000D_
#childLeftCol_x000D_
{_x000D_
float:left;_x000D_
}_x000D_
#parent_x000D_
{_x000D_
    display:inline;_x000D_
}
_x000D_
_x000D_
_x000D_

Eclipse: All my projects disappeared from Project Explorer

I found a solution that worked better for me. Under my home folder I found a workspace/.metadata folder. I copied this folder into my eclipse workspace, replacing the .metadata folder that had been there. When I started Eclipse everything was back to the way I had left it - all projects present, all open files were still open, etc. Just like nothing had happened! I'm using Neon.

Find document with array that contains a specific value

I feel like $all would be more appropriate in this situation. If you are looking for person that is into sushi you do :

PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})

As you might want to filter more your search, like so :

PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})

$in is like OR and $all like AND. Check this : https://docs.mongodb.com/manual/reference/operator/query/all/

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

grabbing first row in a mysql query only

To return only one row use LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

How to sort an array of integers correctly

Update! Scroll to bottom of answer for smartSort prop additive that gives even more fun!
Sorts arrays of anything!

My personal favorite form of this function allows for a param for Ascending, or Descending:

function intArraySort(c, a) {
    function d(a, b) { return b - a; }
    "string" == typeof a && a.toLowerCase();
    switch (a) {
        default: return c.sort(function(a, b) { return a - b; });
        case 1:
                case "d":
                case "dc":
                case "desc":
                return c.sort(d)
    }
};

Usage as simple as:

var ara = function getArray() {
        var a = Math.floor(Math.random()*50)+1, b = [];
        for (i=0;i<=a;i++) b.push(Math.floor(Math.random()*50)+1);
        return b;
    }();

//    Ascending
intArraySort(ara);
console.log(ara);

//    Descending
intArraySort(ara, 1);
console.log(ara);

//    Ascending
intArraySort(ara, 'a');
console.log(ara);

//    Descending
intArraySort(ara, 'dc');
console.log(ara);

//    Ascending
intArraySort(ara, 'asc');
console.log(ara);

jsFiddle


Or Code Snippet Example Here!

_x000D_
_x000D_
function intArraySort(c, a) {_x000D_
 function d(a, b) { return b - a }_x000D_
 "string" == typeof a && a.toLowerCase();_x000D_
 switch (a) {_x000D_
  default: return c.sort(function(a, b) { return a - b });_x000D_
  case 1:_x000D_
  case "d":_x000D_
  case "dc":_x000D_
  case "desc":_x000D_
  return c.sort(d)_x000D_
 }_x000D_
};_x000D_
_x000D_
function tableExample() {_x000D_
 var d = function() {_x000D_
   var a = Math.floor(50 * Math.random()) + 1,_x000D_
    b = [];_x000D_
   for (i = 0; i <= a; i++) b.push(Math.floor(50 * Math.random()) + 1);_x000D_
   return b_x000D_
  },_x000D_
  a = function(a) {_x000D_
   var b = $("<tr/>"),_x000D_
    c = $("<th/>").prependTo(b);_x000D_
   $("<td/>", {_x000D_
    text: intArraySort(d(), a).join(", ")_x000D_
   }).appendTo(b);_x000D_
   switch (a) {_x000D_
    case 1:_x000D_
    case "d":_x000D_
    case "dc":_x000D_
    case "desc":_x000D_
     c.addClass("desc").text("Descending");_x000D_
     break;_x000D_
    default:_x000D_
     c.addClass("asc").text("Ascending")_x000D_
   }_x000D_
   return b_x000D_
  };_x000D_
 return $("tbody").empty().append(a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1))_x000D_
};_x000D_
_x000D_
tableExample();
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
.asc { color: red; }_x000D_
.desc { color: blue }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table><tbody></tbody></table>
_x000D_
_x000D_
_x000D_


.smartSort('asc' | 'desc')

Now have even more fun with a sorting method that sorts an array full of multiple items! Doesn't currently cover "associative" (aka, string keys), but it does cover about every type of value! Not only will it sort the multiple values asc or desc accordingly, but it will also maintain constant "position" of "groups" of values. In other words; ints are always first, then come strings, then arrays (yes, i'm making this multidimensional!), then Objects (unfiltered, element, date), & finally undefineds and nulls!

"Why?" you ask. Why not!

Now comes in 2 flavors! The first of which requires newer browsers as it uses Object.defineProperty to add the method to the Array.protoype Object. This allows for ease of natural use, such as: myArray.smartSort('a'). If you need to implement for older browsers, or you simply don't like modifying native Objects, scroll down to Method Only version.

/* begin */
/* KEY NOTE! Requires EcmaScript 5.1 (not compatible with older browsers) */
;;(function(){if(Object.defineProperty&&!Array.prototype.smartSort){var h=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a>b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("a");b instanceof Array&&b.smartSort("a");if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("a"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("a"),a.id==e[0]?1:-1;e=[a.tagName, b.tagName].smartSort("a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("a"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d"); return a[d].tagName==c[0]?1:-1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]>g[1]},k=function(a,b){if(null== a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("d");b instanceof Array&&b.smartSort("d");if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("d"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("d"),a.id==e[0]?-1:1;e=[a.tagName,b.tagName].smartSort("d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("d"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1;if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]};Object.defineProperty(Array.prototype,"smartSort",{value:function(){return arguments&& (!arguments.length||1==arguments.length&&/^a([sc]{2})?$|^d([esc]{3})?$/i.test(arguments[0]))?this.sort(!arguments.length||/^a([sc]{2})?$/i.test(arguments[0])?h:k):this.sort()}})}})();
/* end */

jsFiddle Array.prototype.smartSort('asc|desc')


Use is simple! First make some crazy array like:

window.z = [ 'one', undefined, $('<span />'), 'two', null, 2, $('<div />', { id: 'Thing' }), $('<div />'), 4, $('<header />') ];
z.push(new Date('1/01/2011'));
z.push('three');
z.push(undefined);
z.push([ 'one', 'three', 'four' ]);
z.push([ 'one', 'three', 'five' ]);
z.push({ a: 'a', b: 'b' });
z.push({ name: 'bob', value: 'bill' });
z.push(new Date());
z.push({ john: 'jill', jack: 'june' });
z.push([ 'abc', 'def', [ 'abc', 'def', 'cba' ], [ 'cba', 'def', 'bca' ], 'cba' ]);
z.push([ 'cba', 'def', 'bca' ]);
z.push({ a: 'a', b: 'b', c: 'c' });
z.push({ a: 'a', b: 'b', c: 'd' });

Then simply sort it!

z.smartSort('asc'); // Ascending
z.smartSort('desc'); // Descending

Method Only

Same as the preceding, except as just a simple method!

/* begin */
/* KEY NOTE! Method `smartSort` is appended to native `window` for global use. If you'd prefer a more local scope, simple change `window.smartSort` to `var smartSort` and place inside your class/method */
window.smartSort=function(){if(arguments){var a,b,c;for(c in arguments)arguments[c]instanceof Array&&(a=arguments[c],void 0==b&&(b="a")),"string"==typeof arguments[c]&&(b=/^a([sc]{2})?$/i.test(arguments[c])?"a":"d");if(a instanceof Array)return a.sort("a"==b?smartSort.asc:smartSort.desc)}return this.sort()};smartSort.asc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a> b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.asc);b instanceof Array&&b.sort(smartSort.asc);if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c], b[c]],"a"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"a"),a.id==e[0]?1:-1;e=smartSort([a.tagName,b.tagName],"a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g), "a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"a"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"a");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1; if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==c[0]?1:-1}g=[a,b].sort();return g[0]>g[1]};smartSort.desc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)? 1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.desc);b instanceof Array&&b.sort(smartSort.desc);if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c],b[c]],"d"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]], b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"d"),a.id==e[0]?-1:1;e=smartSort([a.tagName,b.tagName],"d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g),"a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&& b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"d"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1; if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]}
/* end */

Use:

z = smartSort(z, 'asc'); // Ascending
z = smartSort(z, 'desc'); // Descending

jsFiddle Method smartSort(Array, "asc|desc")

incompatible character encodings: ASCII-8BIT and UTF-8

For Haml put an encoding hint:

-# coding: UTF-8

on the top left of the Haml page.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

format statement in a string resource file

Inside file strings.xml define a String resource like this:

<string name="string_to_format">Amount: %1$f  for %2$d days%3$s</string>

Inside your code (assume it inherits from Context) simply do the following:

 String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);

(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

int value under 10 convert to string two digit number

The accepted answer is good and fast:

i.ToString("00")

or

i.ToString("000")

If you need more complexity, String.Format is worth a try:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}

For the i = 10 case:

str1: "10"
str2: "010"

I use this, for example, to clear the text on particular Label Controls on my form by name:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}

Can I load a UIImage from a URL?

Try this code, you can set loading image with it, so the users knows that your app is loading an image from url:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
    [yourImageView setContentMode:UIViewContentModeScaleAspectFit];

    //Request image data from the URL:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (imgData)
            {
                //Load the data into an UIImage:
                UIImage *image = [UIImage imageWithData:imgData];

                //Check if your image loaded successfully:
                if (image)
                {
                    yourImageView.image = image;
                }
                else
                {
                    //Failed to load the data into an UIImage:
                    yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
                }
            }
            else
            {
                //Failed to get the image data:
                yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
            }
        });
    });

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

How Do I Convert an Integer to a String in Excel VBA?

Another way to do it is to splice two parsed sections of the numerical value together:

Cells(RowNum, ColumnNum).Value = Mid(varNumber,1,1) & Mid(varNumber,2,Len(varNumber))

I have found better success with this than CStr() because CStr() doesn't seem to convert decimal numbers that came from variants in my experience.

Current date and time - Default in MVC razor

You could initialize ReturnDate on the model before sending it to the view.

In the controller:

[HttpGet]
public ActionResult SomeAction()
{
    var viewModel = new MyActionViewModel
    {
        ReturnDate = System.DateTime.Now
    };

    return View(viewModel);
}

Android: failed to convert @drawable/picture into a drawable

I have the same problem on Android Studio. No need to restart the IDE, just close and reopen the project and that will resolve the problem. (Make sure the src are correclty input).

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Inserting a text where cursor is using Javascript/jquery

Content Editable, HTML or any other DOM element Selections

If you are trying to insert at caret on a <div contenteditable="true">, this becomes much more difficult, especially if there are children within the editable container.

I have had really great luck using the Rangy library:

It has a ton of great features such as:

  • Save Position or Selection
  • Then later, Restore the Position or Selection
  • Get selection HTML or Plaintext
  • Among many others

The online demo was not working last I checked, however the repo has working demos. To get started, simple download the Repo from Git or NPM, then open ./rangy/demos/index.html

It makes working with caret pos and text selection a breeze!

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.

Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.

edit

Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.

You use the same casting technique to iterate over the fields:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

The above code and more can be found by clicking on that link.

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How can I convert an Integer to localized month name in Java?

tl;dr

Month.of( yourMonthNumber )           // Represent a month by its number, 1-12 for January-December. 
  .getDisplayName(                    // Generate text of the name of the month automatically localized. 
      TextStyle.SHORT_STANDALONE ,    // Specify how long or abbreviated the name of month should be.
      new Locale( "es" , "MX" )       // Locale determines (a) the human language used in translation, and (b) the cultural norms used in deciding issues of abbreviation, capitalization, punctuation, and so on.
  )                                   // Returns a String.

java.time.Month

Much easier to do now in the java.time classes that supplant these troublesome old legacy date-time classes.

The Month enum defines a dozen objects, one for each month.

The months are numbered 1-12 for January-December.

Month month = Month.of( 2 );  // 2 ? February.

Ask the object to generate a String of the name of the month, automatically localized.

Adjust the TextStyle to specify how long or abbreviated you want the name. Note that in some languages (not English) the month name varies if used alone or as part of a complete date. So each text style has a …_STANDALONE variant.

Specify a Locale to determine:

  • Which human language should be used in translation.
  • What cultural norms should decide issues such as abbreviation, punctuation, and capitalization.

Example:

Locale l = new Locale( "es" , "MX" );
String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , l );  // Or Locale.US, Locale.CANADA_FRENCH. 

Name ? Month object

FYI, going the other direction (parsing a name-of-month string to get a Month enum object) is not built-in. You could write your own class to do so. Here is my quick attempt at such a class. Use at your own risk. I gave this code no serious thought nor any serious testing.

Usage.

Month m = MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ;  // Month.JANUARY

Code.

package com.basilbourque.example;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.time.Month;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// For a given name of month in some language, determine the matching `java.time.Month` enum object.
// This class is the opposite of `Month.getDisplayName` which generates a localized string for a given `Month` object.
// Usage… MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ? Month.JANUARY
// Assumes `FormatStyle.FULL`, for names without abbreviation.
// About `java.time.Month` enum: https://docs.oracle.com/javase/9/docs/api/java/time/Month.html
// USE AT YOUR OWN RISK. Provided without guarantee or warranty. No serious testing or code review was performed.
public class MonthDelocalizer
{
    @NotNull
    private Locale locale;

    @NotNull
    private List < String > monthNames, monthNamesStandalone; // Some languages use an alternate spelling for a “standalone” month name used without the context of a date.

    // Constructor. Private, for static factory method.
    private MonthDelocalizer ( @NotNull Locale locale )
    {
        this.locale = locale;

        // Populate the pair of arrays, each having the translated month names.
        int countMonthsInYear = 12; // Twelve months in the year.
        this.monthNames = new ArrayList <>( countMonthsInYear );
        this.monthNamesStandalone = new ArrayList <>( countMonthsInYear );

        for ( int i = 1 ; i <= countMonthsInYear ; i++ )
        {
            this.monthNames.add( Month.of( i ).getDisplayName( TextStyle.FULL , this.locale ) );
            this.monthNamesStandalone.add( Month.of( i ).getDisplayName( TextStyle.FULL_STANDALONE , this.locale ) );
        }
//        System.out.println( this.monthNames );
//        System.out.println( this.monthNamesStandalone );
    }

    // Constructor. Private, for static factory method.
    // Personally, I think it unwise to default implicitly to a `Locale`. But I included this in case you disagree with me, and to follow the lead of the *java.time* classes. --Basil Bourque
    private MonthDelocalizer ( )
    {
        this( Locale.getDefault() );
    }

    // static factory method, instead of  constructors.
    // See article by Dr. Joshua Bloch. http://www.informit.com/articles/article.aspx?p=1216151
    // The `Locale` argument determines the human language and cultural norms used in de-localizing input strings.
    synchronized static public MonthDelocalizer of ( @NotNull Locale localeArg )
    {
        MonthDelocalizer x = new MonthDelocalizer( localeArg ); // This class could be optimized by caching this object.
        return x;
    }

    // Attempt to translate the name of a month to look-up a matching `Month` enum object.
    // Returns NULL if the passed String value is not found to be a valid name of month for the human language and cultural norms of the `Locale` specified when constructing this parent object, `MonthDelocalizer`.
    @Nullable
    public Month parse ( @NotNull String input )
    {
        int index = this.monthNames.indexOf( input );
        if ( - 1 == index )
        { // If no hit in the contextual names, try the standalone names.
            index = this.monthNamesStandalone.indexOf( input );
        }
        int ordinal = ( index + 1 );
        Month m = ( ordinal > 0 ) ? Month.of( ordinal ) : null;  // If we have a hit, determine the `Month` enum object. Else return null.
        if ( null == m )
        {
            throw new java.lang.IllegalArgumentException( "The passed month name: ‘" + input + "’ is not valid for locale: " + this.locale.toString() );
        }
        return m;
    }

    // `Object` class overrides.

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;

        MonthDelocalizer that = ( MonthDelocalizer ) o;

        return locale.equals( that.locale );
    }

    @Override
    public int hashCode ( )
    {
        return locale.hashCode();
    }

    public static void main ( String[] args )
    {
        // Usage example:
        MonthDelocalizer monthDelocJapan = MonthDelocalizer.of( Locale.JAPAN );
        try
        {
            Month m = monthDelocJapan.parse( "pink elephant" ); // Invalid input.
        } catch ( IllegalArgumentException e )
        {
            // … handle error
            System.out.println( "ERROR: " + e.getLocalizedMessage() );
        }

        // Ignore exception. (not recommended)
        if ( MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ).equals( Month.JANUARY ) )
        {
            System.out.println( "GOOD - In locale "+Locale.CANADA_FRENCH+", the input ‘janvier’ parses to Month.JANUARY." );
        }
    }
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to retrieve Jenkins build parameters using the Groovy API?

Update: Jenkins 2.x solution:

With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:

echo " FOOBAR value: ${params.'FOOBAR'}"

The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters

Original Answer for Jenkins 1.x:

For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:

// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)

Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters: https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script

The salient part is reproduced below:

// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
   println "parameter ${it.name}:"
   println it.dump()
}

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

Don't use document.write, here is workaround:

var script = document.createElement('script');  
script.src = "....";  
document.head.appendChild(script);

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

AES Encryption for an NSString on the iPhone

Please use the below mentioned URL to encrypt string using AES excryption with 
key and IV values.

https://github.com/muneebahmad/AESiOSObjC

How can I list all foreign keys referencing a given table in SQL Server?

The following solution work for me:

--Eliminar las llaves foraneas
declare @query varchar(8000)
declare cursorRecorrerTabla cursor for

SELECT  'ALTER TABLE [PoaComFinH].['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' 'query'
FROM PoaComFinH.sys.foreign_key_columns fk
JOIN PoaComFinH.sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
JOIN PoaComFinH.sys.schemas sch ON referencingTable.schema_id = sch.schema_id
JOIN PoaComFinH.sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
JOIN PoaComFinH.sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id


--3ro. abrir el cursor.
open cursorRecorrerTabla
fetch next from cursorRecorrerTabla
into @query
while @@fetch_status = 0
begin
--inicio cuerpo del cursor
    print @query
    exec(@query)
--fin cuerpo del cursor
fetch next from cursorRecorrerTabla
into @query
end
--cerrar cursor
close cursorRecorrerTabla
deallocate cursorRecorrerTabla

Android TabLayout Android Design

I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.

DashboardFragment

public class DashboardFragment extends BaseFragment {

    private Context mContext;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private DashboardPagerAdapter mAdapter;
    private OnModuleChangeListener onModuleChangeListener;
    private NavDashBoardActivity activityInstance;

    public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
        this.onModuleChangeListener = onModuleChangeListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dashboard_fragment, container, false);
    }

    //pass -1 if you want to get it via pager
    public Fragment getFragmentFromViewpager(int position) {
        if (position == -1)
            position = mViewPager.getCurrentItem();
        return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mContext = getActivity();

        activityInstance = (NavDashBoardActivity) getActivity();

        mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);

        final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
        mViewPager.setOffscreenPageLimit(moduleToShow.size());

        for(EnumUtils.Module module :moduleToShow)
            mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));

        updateTabPagerAndMenu(0 , moduleToShow);

        mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
        mViewPager.setOffscreenPageLimit(mAdapter.getCount());

        mViewPager.setAdapter(mAdapter);

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(final TabLayout.Tab tab) {
                    mViewPager.post(new Runnable() {
                    @Override
                    public void run() {
                        mViewPager.setCurrentItem(tab.getPosition());
                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //added to redraw menu on scroll
            }

            @Override
            public void onPageSelected(int position) {
                updateTabPagerAndMenu(position , moduleToShow);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    //also validate other checks and this method should be in SharedPrefs...
    public static List<EnumUtils.Module> getModuleToShowList(){
        List<EnumUtils.Module> moduleToShow = new ArrayList<>();

        moduleToShow.add(EnumUtils.Module.HOME);
        moduleToShow.add(EnumUtils.Module.ABOUT);

        return moduleToShow;
    }

    public void setCurrentTab(final int position){
        if(mViewPager != null){
            mViewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mViewPager.setCurrentItem(position);
                }
            },100);
        }
    }

    private Fragment getCurrentFragment(){
        return mAdapter.getCurrentFragment();
    }

    private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
        //it helps to change menu on scroll
        //http://stackoverflow.com/a/27984263/3496570
        //No effect after changing below statement
        ActivityCompat.invalidateOptionsMenu(getActivity());
        if(mTabLayout != null)
            mTabLayout.getTabAt(position).select();

        if(onModuleChangeListener != null){

            if(activityInstance != null){
                activityInstance.updateStatusBarColor(
                        EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
            }
            onModuleChangeListener.onModuleChanged(moduleToShow.get(position));

            mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
            mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
                    , EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
        }
    }
}

dashboardfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- our tablayout to display tabs  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabBackground="@android:color/white"
        app:tabGravity="fill"
        app:tabIndicatorHeight="4dp"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@android:color/black"
        app:tabTextColor="@android:color/black" />

    <!-- View pager to swipe views -->
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</LinearLayout>

DashboardPagerAdapter

public class DashboardPagerAdapter extends FragmentPagerAdapter {

private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;

public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
    super(fm);
    this.moduleList = moduleList;
}

@Override
public Fragment getItem(int position) {
    return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}

@Override
public int getCount() {
    return moduleList.size();
}

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    if (getCurrentFragment() != object) {
        mCurrentFragment = ((Fragment) object);
    }
    super.setPrimaryItem(container, position, object);
}

public Fragment getCurrentFragment() {
    return mCurrentFragment;
}

public int getModulePosition(EnumUtils.Module moduleName){
    for(int x = 0 ; x < moduleList.size() ; x++){
        if(moduleList.get(x).equals(moduleName))
            return x;
    }
    return -1;
}

}

And in each page of Fragment setHasOptionMenu(true) in onCreate and implement onCreateOptionMenu. then it will work properly.

dASHaCTIVITY

public class NavDashBoardActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Context mContext;
    private DashboardFragment dashboardFragment;
    private Toolbar mToolbar;
    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;

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

        mContext = NavDashBoardActivity.this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
        }

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        updateToolbarText(new ToolbarTextBO("NCompass " ,""));

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //onclick of back button on Navigation it will popUp fragment...
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!toggle.isDrawerIndicatorEnabled()) {
                    getSupportFragmentManager().popBackStack();
                }
            }
        });

        final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
        updateNavigationMenuItem(navigationView);

        navigationView.setNavigationItemSelectedListener(this);

        //Left Drawer Upper Section
        View headerLayout = navigationView.getHeaderView(0); // 0-index header

        TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
        userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
        RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);

        ivUserPic.setImageResource(R.drawable.profile_img);

        headerLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //close drawer and add a fragment to it
                drawer.closeDrawers();//also try other methods..
            }
        });

        //ZA code starts...
        dashboardFragment = new DashboardFragment();
        dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
            @Override
            public void onModuleChanged(EnumUtils.Module module) {
                if(mToolbar != null){
                    mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));

                    if(EnumUtils.Module.getMenuID(module) != -1)
                        navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
                }
            }
        });

        addBaseFragment(dashboardFragment);
        backStackListener();
    }



    public void updateStatusBarColor(int colorResourceID){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(colorResourceID);
        }
    }

    private void updateNavigationMenuItem(NavigationView navigationView){
        List<EnumUtils.Module> modules =  DashboardFragment.getModuleToShowList();

        if(!modules.contains(EnumUtils.Module.MyStores)){
            navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
        }
        if(!modules.contains(EnumUtils.Module.Livewall)){
            navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
        }
    }

    private void backStackListener(){
        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {

                if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
                {
                    toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
                    toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
                    ///toggle.setDrawerArrowDrawable();
                    ///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
                    ///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
                }
                else{
                    toggle.setDrawerIndicatorEnabled(true);
                }
                if(getSupportFragmentManager().getBackStackEntryCount() >0){
                    if(getCurrentFragment() instanceof DashboardFragment){
                        Fragment subFragment = ((DashboardFragment) getCurrentFragment())
                                .getViewpager(-1);
                    }
                }
                else{

                }
            }
        });
    }

    private void updateToolBarTitle(String title){
        getSupportActionBar().setTitle(title);
    }
    public void updateToolBarColor(String hexColor){
        if(mToolbar != null)
            mToolbar.setBackgroundColor(Color.parseColor(hexColor));
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (drawer.isDrawerOpen(GravityCompat.START))
            getMenuInflater().inflate(R.menu.empty, menu);

        return super.onCreateOptionsMenu(menu);//true is wriiten first..
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            if (drawer.isDrawerOpen(GravityCompat.START))
                drawer.closeDrawer(GravityCompat.START);
            else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {

                } else
                    drawer.openDrawer(GravityCompat.START);
            }

            return false;///true;
        }

        return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
        ///return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_my_store) {
            // Handle the camera action
            dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
        } 
        }else if  (id == R.id.nav_log_out)  {
            Dialogs.logOut(mContext);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void updateToolbarText(ToolbarTextBO toolbarTextBO){
        mToolbar.setTitle("");
        mToolbar.setSubtitle("");
        if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
            mToolbar.setTitle(toolbarTextBO.getTitle());
        if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
            mToolbar.setSubtitle(toolbarTextBO.getDescription());*/

    }

    @Override
    public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        toggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toggle.onConfigurationChanged(newConfig);
    }
}

Android: Is it possible to display video thumbnails?

Using the class:

import android.provider.MediaStore.Video.Thumbnails;

We can get two preview thumbnail sizes from the video:

Thumbnails.MICRO_KIND for 96 x 96

Thumbnails.MINI_KIND for 512 x 384 px

This is a code example:

String filePath = "/sdcard/DCIM/Camera/my_video.mp4"; //change the location of your file!

ImageView imageview_mini = (ImageView)findViewById(R.id.thumbnail_mini);
ImageView imageview_micro = (ImageView)findViewById(R.id.thumbnail_micro);

Bitmap bmThumbnail;

//MICRO_KIND, size: 96 x 96 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MICRO_KIND);
imageview_micro.setImageBitmap(bmThumbnail);
     
// MINI_KIND, size: 512 x 384 thumbnail 
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);
imageview_mini.setImageBitmap(bmThumbnail);

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

Predict() - Maybe I'm not understanding it

instead of newdata you are using newdate in your predict code, verify once. and just use Coupon$estimate <- predict(model, Coupon) It will work.

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Add / remove input field dynamically with jQuery

enter image description here You should be able to create and remove input field dynamically by using jquery using this method(https://www.adminspress.com/onex/view/uaomui), Even you can able to generate input fields in bulk and export to string.

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

This is very simple, you just need to add a background image to the select element and position it where you need to, but don't forget to add:

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

According to http://shouldiprefix.com/#appearance

Microsoft Edge and IE mobile support this property with the -webkit- prefix rather than -ms- for interop reasons.

I just made this fiddle http://jsfiddle.net/drjorgepolanco/uxxvayqe/

Changing element style attribute dynamically using JavaScript

In addition to other answers, if you want to use the dash notition for style properties, you can also use:

document.getElementById("xyz").style["padding-top"] = "10px";

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

503 means the functions are working and you're getting a response from the remote server denying you. If you ever tried to cURL google results the same thing happens, because they can detect the user-agent used by file_get_contents and cURL and as a result block those user agents. It's also possible that the server you're accessing from also has it's IP address blackballed for such practices.

Mainly three common reasons why the commands wouldn't work just like the browser in a remote situation.

1) The default USER-AGENT has been blocked. 2) Your server's IP block has been blocked. 3) Remote host has a proxy detection.

How do I query using fields inside the new PostgreSQL JSON datatype?

With postgres 9.3 use -> for object access. 4 example

seed.rb

se = SmartElement.new
se.data = 
{
    params:
    [
        {
            type: 1,
            code: 1,
            value: 2012,
            description: 'year of producction'
        },
        {
            type: 1,
            code: 2,
            value: 30,
            description: 'length'
        }
    ]
}

se.save

rails c

SELECT data->'params'->0 as data FROM smart_elements;

returns

                                 data
----------------------------------------------------------------------
 {"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)

You can continue nesting

SELECT data->'params'->0->'type' as data FROM smart_elements;

return

 data
------
 1
(1 row)

Achieving white opacity effect in html/css

Try RGBA, e.g.

div { background-color: rgba(255, 255, 255, 0.5); }

As always, this won't work in every single browser ever written.

Extract csv file specific columns to list in Python

import csv
from sys import argv

d = open("mydata.csv", "r")

db = []

for line in csv.reader(d):
    db.append(line)

# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Load local HTML file in a C# WebBrowser

Update on @ghostJago answer above

for me it worked as the following lines in VS2017

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));

org.hibernate.PersistentObjectException: detached entity passed to persist

Here you have used native and assigning value to the primary key, in native primary key is auto generated.

Hence the issue is coming.

How do I wait for an asynchronously dispatched block to finish?

In addition to the semaphore technique covered exhaustively in other answers, we can now use XCTest in Xcode 6 to perform asynchronous tests via XCTestExpectation. This eliminates the need for semaphores when testing asynchronous code. For example:

- (void)testDataTask
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"asynchronous request"];

    NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
    NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        XCTAssertNil(error, @"dataTaskWithURL error %@", error);

        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode];
            XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode);
        }

        XCTAssert(data, @"data nil");

        // do additional tests on the contents of the `data` object here, if you want

        // when all done, Fulfill the expectation

        [expectation fulfill];
    }];
    [task resume];

    [self waitForExpectationsWithTimeout:10.0 handler:nil];
}

For the sake of future readers, while the dispatch semaphore technique is a wonderful technique when absolutely needed, I must confess that I see too many new developers, unfamiliar with good asynchronous programming patterns, gravitate too quickly to semaphores as a general mechanism for making asynchronous routines behave synchronously. Worse I've seen many of them use this semaphore technique from the main queue (and we should never block the main queue in production apps).

I know this isn't the case here (when this question was posted, there wasn't a nice tool like XCTestExpectation; also, in these testing suites, we must ensure the test does not finish until the asynchronous call is done). This is one of those rare situations where the semaphore technique for blocking the main thread might be necessary.

So with my apologies to the author of this original question, for whom the semaphore technique is sound, I write this warning to all of those new developers who see this semaphore technique and consider applying it in their code as a general approach for dealing with asynchronous methods: Be forewarned that nine times out of ten, the semaphore technique is not the best approach when encounting asynchronous operations. Instead, familiarize yourself with completion block/closure patterns, as well as delegate-protocol patterns and notifications. These are often much better ways of dealing with asynchronous tasks, rather than using semaphores to make them behave synchronously. Usually there are good reasons that asynchronous tasks were designed to behave asynchronously, so use the right asynchronous pattern rather than trying to make them behave synchronously.

In Android EditText, how to force writing uppercase?

edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {            

    }
        @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {             
    }
    @Override
    public void afterTextChanged(Editable et) {
          String s=et.toString();
      if(!s.equals(s.toUpperCase()))
      {
         s=s.toUpperCase();
         edittext.setText(s);
      }
      editText.setSelection(editText.getText().length());
    }
});  

how to use ng-option to set default value of select element

This answer is more usefull when you are bringing data from a DB, make modifications and then persist the changes.

 <select  ng-options="opt.id as opt.name for opt in users" ng-model="selectedUser"></select>

Check the example here:

http://plnkr.co/edit/HrT5vUMJOtP9esGngbIV

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Markdown open a new window link

Using sed

If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:

sed -i 's|href="http|target="_blank" href="http|g' index.html

This can be further automated in a single workflow when a Makefile with build instructions is employed.

PS: This answer was written at a time when extension link_attributes was not yet available in Pandoc.

Get string character by index - Java

You want .charAt()

Here's a tutorial

"mystring".charAt(2)

returns s

If you're hellbent on having a string there are a couple of ways to convert a char to a string:

String mychar = Character.toString("mystring".charAt(2));

Or

String mychar = ""+"mystring".charAt(2);

Or even

String mychar = String.valueOf("mystring".charAt(2));

For example.

How to delete a folder in C++?

void remove_dir(char *path)
{
        struct dirent *entry = NULL;
        DIR *dir = NULL;
        dir = opendir(path);
        while(entry = readdir(dir))
        {   
                DIR *sub_dir = NULL;
                FILE *file = NULL;
                char abs_path[100] = {0};
                if(*(entry->d_name) != '.')
                {   
                        sprintf(abs_path, "%s/%s", path, entry->d_name);
                        if(sub_dir = opendir(abs_path))
                        {   
                                closedir(sub_dir);
                                remove_dir(abs_path);
                        }   
                        else 
                        {   
                                if(file = fopen(abs_path, "r"))
                                {   
                                        fclose(file);
                                        remove(abs_path);
                                }   
                        }   
                }   
        }   
        remove(path);
}

Handling the window closing event with WPF / MVVM Light Toolkit

Here is an answer according to the MVVM-pattern if you don't want to know about the Window (or any of its event) in the ViewModel.

public interface IClosing
{
    /// <summary>
    /// Executes when window is closing
    /// </summary>
    /// <returns>Whether the windows should be closed by the caller</returns>
    bool OnClosing();
}

In the ViewModel add the interface and implementation

public bool OnClosing()
{
    bool close = true;

    //Ask whether to save changes och cancel etc
    //close = false; //If you want to cancel close

    return close;
}

In the Window I add the Closing event. This code behind doesn't break the MVVM pattern. The View can know about the viewmodel!

void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    IClosing context = DataContext as IClosing;
    if (context != null)
    {
        e.Cancel = !context.OnClosing();
    }
}

Disable click outside of bootstrap modal area to close modal

I was missing modal-dialog that's why my close modal wasn't working properly.

How to find the remainder of a division in C?

You can use the % operator to find the remainder of a division, and compare the result with 0.

Example:

if (number % divisor == 0)
{
    //code for perfect divisor
}
else
{
    //the number doesn't divide perfectly by divisor
}

List of phone number country codes

There is an Excel file with regexps here. You can easily "convert" it to XML and you will be able to determine country by the full phone number.

UPD: The file that I referenced 4 years ago is no longer accessible. I would recommend using Google's libphonenumber.

The answer to Extract code country from phone number [libphonenumber] will show you the proper way to receive country code from a phone number.

VSCode single to double quote automatic replace

As noted by @attdona the Vetur extension includes prettier.

While you can change the prettier settings, as per the accepted answer, you can also change the formatter for specific regions of a vue component.

Here, for example, I've set Vetur to use the vscode-typescript formatter as it uses single quotes by default:

vscode vetur settings

Bootstrap 3 Glyphicons CDN

With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

In css:

 @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

Here is a working demo.

Note that you have to use .glyphicon classes instead of .icon:

Example:

<span class="glyphicon glyphicon-heart"></span>

Also note that you would still need to include bootstrap.min.js for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.


If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

In css:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");

Since the css file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css file is all there is to do to start using Glyphicons.

Here is a working demo of the Glyphicons without Bootstrap.

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

You could use:

^(mailto|ftp|joe)

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

You could also look at the System.Uri class if you are parsing URIs.

How to check if a text field is empty or not in swift

another way to check in realtime textField source :

 @IBOutlet var textField1 : UITextField = UITextField()

 override func viewDidLoad() 
 {
    ....
    self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
 }

 func yourNameFunction(sender: UITextField) {

    if sender.text.isEmpty {
      // textfield is empty
    } else {
      // text field is not empty
    }
  }

Elegant way to report missing values in a data.frame

Another function that would help you look at missing data would be df_status from funModeling library

library(funModeling)

iris.2 is the iris dataset with some added NAs.You can replace this with your dataset.

df_status(iris.2)

This will give you the number and percentage of NAs in each column.

Error: Execution failed for task ':app:clean'. Unable to delete file

Deleting the directory intermediates is a quick fix for problem.

The directory will be rebuilt when the project is rebuilt.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

View's SELECT contains a subquery in the FROM clause

create view view_clients_credit_usage as
    select client_id, sum(credits_used) as credits_used 
    from credit_usage 
    group by client_id

create view view_credit_status as 
    select 
        credit_orders.client_id, 
        sum(credit_orders.number_of_credits) as purchased, 
        ifnull(t1.credits_used,0) as used 
    from credit_orders
    left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
    where credit_orders.payment_status='Paid'
    group by credit_orders.client_id)

Python Script to convert Image into Byte array

with BytesIO() as output:
    from PIL import Image
    with Image.open(filename) as img:
        img.convert('RGB').save(output, 'BMP')                
    data = output.getvalue()[14:]

I just use this for add a image to clipboard in windows.

Center a popup window on screen?

try it like this:

function popupwindow(url, title, w, h) {
  var left = (screen.width/2)-(w/2);
  var top = (screen.height/2)-(h/2);
  return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
} 

Android Recyclerview vs ListView with Viewholder

More from Bill Phillip's article (go read it!) but i thought it was important to point out the following.

In ListView, there was some ambiguity about how to handle click events: Should the individual views handle those events, or should the ListView handle them through OnItemClickListener? In RecyclerView, though, the ViewHolder is in a clear position to act as a row-level controller object that handles those kinds of details.

We saw earlier that LayoutManager handled positioning views, and ItemAnimator handled animating them. ViewHolder is the last piece: it’s responsible for handling any events that occur on a specific item that RecyclerView displays.

Is there a way to reduce the size of the git folder?

I'm not sure what you want. First of all, of course each time you commit/push the directory is going to get a little larger, since it has to store each of those additional commits.

However, probably you want git gc which will "cleanup unnecessary files and optimize the local repository" (manual page).

Another possibly relevant command is git clean which will delete untracked files from your tree (manual page).

Difference between virtual and abstract methods

an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it

Example:

abstract class twodshape
{
    public abstract void area(); // no body in base class
}

class twodshape2 : twodshape
{
    public virtual double area()
    {
        Console.WriteLine("AREA() may be or may not be override");
    }
}

How do you make an array of structs in C?

move

struct body bodies[n];

to after

struct body
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
};

Rest all looks fine.

Is there any standard for JSON API response format?

The RFC 7807: Problem Details for HTTP APIs is at the moment the closest thing we have to an official standard.

Where is the Docker daemon log?

Using CentOS7, logs are available using the command journalctl -u docker. Answering distinctly, because @sabin's answer might be accurate for older versions of CentOS but was not true for me.

systemd has its own logging system called the journal. The logs for the docker daemon can be viewed using journalctl -u docker

Ref: https://docs.docker.com/engine/admin/configuring/

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

Powershell handles tasks like this fairly handily:

$productCode = (gwmi win32_product | `
                ? { $_.Name -Like "<PRODUCT NAME HERE>*" } | `
                % { $_.IdentifyingNumber } | `
                Select-Object -First 1)

You can then use it to get the uninstall information as well:

$wow = ""
$is32BitInstaller = $True # or $False

if($is32BitInstaller -and [System.Environment]::Is64BitOperatingSystem) 
{
    $wow = "\Wow6432Node" 
}

$regPath = "HKEY_LOCAL_MACHINE\SOFTWARE$wow\Microsoft\Windows\CurrentVersion\Uninstall"

dir "HKLM:\SOFTWARE$wow\Microsoft\Windows\CurrentVersion\Uninstall" | `
? { $_.Name -Like "$regPath\$productCode"  }

How can I find the first occurrence of a sub-string in a python string?

to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as

def find_pos(string,word):

    for i in range(len(string) - len(word)+1):
        if string[i:i+len(word)] == word:
            return i
    return 'Not Found'

string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4

What does %~d0 mean in a Windows batch file?

Yes, There are other shortcuts that you can use which are given below. In your command, ~d0 would mean the drive letter of the 0th argument.

~ expands the given variable
d gets the drive letter only
0 is the argument you are referencing

As the 0th argument is the script path, it gets the drive letter of the path for you. You can use the following shortcuts too.

%~1         - expands %1 removing any surrounding quotes (")
%~f1        - expands %1 to a fully qualified path name
%~d1        - expands %1 to a drive letter only
%~p1        - expands %1 to a path only
%~n1        - expands %1 to a file name only
%~x1        - expands %1 to a file extension only
%~s1        - expanded path contains short names only
%~a1        - expands %1 to file attributes
%~t1        - expands %1 to date/time of file
%~z1        - expands %1 to size of file
%~$PATH:1   - searches the directories listed in the PATH
               environment variable and expands %1 to the fully
               qualified name of the first one found.  If the
               environment variable name is not defined or the
               file is not found by the search, then this
               modifier expands to the empty string    

%~dp1       - expands %1 to a drive letter and path only
%~nx1       - expands %1 to a file name and extension only
%~dp$PATH:1 - searches the directories listed in the PATH
               environment variable for %1 and expands to the
               drive letter and path of the first one found.
%~ftza1     - expands %1 to a DIR like output line

This can be also found directly in command prompt when you run CALL /? or FOR /?

How to go back to previous page if back button is pressed in WebView?

This is my solution. It works also in Fragment.

webView.setOnKeyListener(new OnKeyListener()
{
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            WebView webView = (WebView) v;

            switch(keyCode)
            {
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack())
                    {
                        webView.goBack();
                        return true;
                    }
                    break;
            }
        }

        return false;
    }
});

Convert NSArray to NSString in Objective-C

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];

How to get the last day of the month?

Use pandas!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

Create an array with random values

Refer below :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

How to add an item to a drop down list in ASP.NET?

Try following code;

DropDownList1.Items.Add(new ListItem(txt_box1.Text));

Correct modification of state arrays in React.js

If you are using functional component please use this as below.

const [chatHistory, setChatHistory] = useState([]); // define the state

const chatHistoryList = [...chatHistory, {'from':'me', 'message':e.target.value}]; // new array need to update
setChatHistory(chatHistoryList); // update the state

Datatables Select All Checkbox

The solution given by @annoyingmouse works for me.

But to use the checkbox in the header cell, I also had to fix select.dataTables.css.
It seems that they used :

table.dataTable tbody th.select-checkbox

instead of :

table.dataTable thead th.select-checkbox

So I had to add this to my css :

table.dataTable thead th.select-checkbox {
  position: relative;
}
table.dataTable thead th.select-checkbox:before,
table.dataTable thead th.select-checkbox:after {
  display: block;
  position: absolute;
  top: 1.2em;
  left: 50%;
  width: 12px;
  height: 12px;
  box-sizing: border-box;
}
table.dataTable tbody td.select-checkbox:before,
table.dataTable thead th.select-checkbox:before {
  content: ' ';
  margin-top: -6px;
  margin-left: -6px;
  border: 1px solid black;
  border-radius: 3px;
}

Check if string is neither empty nor space in shell script

In case you need to check against any amount of whitespace, not just single space, you can do this:

To strip string of extra white space (also condences whitespace in the middle to one space):

trimmed=`echo -- $original`

The -- ensures that if $original contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put "" around $original, or the spaces will not get removed.

After that you can just check if $trimmed is empty.

[ -z "$trimmed" ] && echo "empty!"

How to set default values in Rails?

The suggestion to override new/initialize is probably incomplete. Rails will (frequently) call allocate for ActiveRecord objects, and calls to allocate won't result in calls to initialize.

If you're talking about ActiveRecord objects, take a look at overriding after_initialize.

These blog posts (not mine) are useful:

Default values Default constructors not called

[Edit: SFEley points out that Rails actually does look at the default in the database when it instantiates a new object in memory - I hadn't realized that.]

What are file descriptors, explained in simple terms?

File Descriptors are the descriptors to a file. They give links to a file. With the help of them we can read, write and open a file.

Retrieve only the queried element in an object array in MongoDB collection

Thanks to JohnnyHK.

Here I just want to add some more complex usage.

// Document 
{ 
"_id" : 1
"shapes" : [
  {"shape" : "square",  "color" : "red"},
  {"shape" : "circle",  "color" : "green"}
  ] 
} 

{ 
"_id" : 2
"shapes" : [
  {"shape" : "square",  "color" : "red"},
  {"shape" : "circle",  "color" : "green"}
  ] 
} 


// The Query   
db.contents.find({
    "_id" : ObjectId(1),
    "shapes.color":"red"
},{
    "_id": 0,
    "shapes" :{
       "$elemMatch":{
           "color" : "red"
       } 
    }
}) 


//And the Result

{"shapes":[
    {
       "shape" : "square",
       "color" : "red"
    }
]}

UIScrollView not scrolling

Something that wasn't mentioned before!

Make sure your outlet was correctly connected to the scrollView! It should have a filled circle, but even if you have filled circle, scrollView may not been connected - so double check! Hover over the circle and see if the actual scrollview gets highlighted! (This was a case for me)

//Connect below well to the scrollView in the storyBoard
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

How to change the output color of echo in Linux

I've written swag to achieve just that.

You can just do

pip install swag

Now you can install all the escape commands as txt files to a given destination via:

swag install -d <colorsdir>

Or even easier via:

swag install

Which will install the colors to ~/.colors.

Either you use them like this:

echo $(cat ~/.colors/blue.txt) This will be blue

Or this way, which I find actually more interesting:

swag print -c red -t underline "I will turn red and be underlined"

Check it out on asciinema!

"elseif" syntax in JavaScript

You are missing a space between else and if

It should be else if instead of elseif

if(condition)
{

} 
else if(condition)
{

}
else
{

}

Adding custom radio buttons in android

In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :

android:button="@null"

Also it would be better to use styles as there are several radio buttons :

<RadioButton style="@style/RadioButtonStyle" ... />

<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
    <item name="android:background">@drawable/customButtonBackground</item>
    <item name="android:button">@null</item>
</style>

You'll need the Seslyn customButtonBackground drawable too.

How to specify "does not contain" in dplyr filter

Note that %in% returns a logical vector of TRUE and FALSE. To negate it, you can use ! in front of the logical statement:

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
 !where_case_travelled_1 %in% 
   c('Outside Canada','Outside province/territory of residence but within Canada'))

Regarding your original approach with -c(...), - is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -.

Return JsonResult from web api without its properties

As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!

ActionResult is bad because as you've discovered.

Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.

Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.

public HttpResponseMessage GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return Request.CreateResponse(HttpStatusCode.OK, result);
}

In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:

 public class ResponseResultExtractor
    {
        public T Extract<T>(HttpResponseMessage response)
        {
            return response.Content.ReadAsAsync<T>().Result;
        }
    }

var actual = ResponseResultExtractor.Extract<List<ListItems>>(response);

In this way, you've achieved the below:

  • Your Action can also return Error Messages and status codes like 404 not found so in the above way you can easily handle it.
  • Your Action isn't limited to JSON only but supports JSON depending on the client's request preference and the settings in the Formatter.

Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation

Show ImageView programmatically

Getting Integer value from a String using javascript/jquery

Is this logically possible??.. I guess the approach that you must take is this way :

Str1 ="test123.00"
Str2 ="yes50.00"

This will be impossible to tackle unless you have delimiter in between test and 123.00

eg: Str1 = "test-123.00" 

Then you can split this way

Str2 = Str1.split("-"); 

This will return you an array of words split with "-"

Then you can do parseFloat(Str2[1]) to get the floating value i.e 123.00

How to get a microtime in Node.js?

now('milli'); //  120335360.999686
now('micro') ; // 120335360966.583
now('nano') ; //  120335360904333

Known that now is :

const now = (unit) => {
  
  const hrTime = process.hrtime();
  
  switch (unit) {
    
    case 'milli':
      return hrTime[0] * 1000 + hrTime[1] / 1000000;
      
    case 'micro':
      return hrTime[0] * 1000000 + hrTime[1] / 1000;
      
    case 'nano':
    default:
      return hrTime[0] * 1000000000 + hrTime[1];
  }
  
};

Clearing a text field on button click

If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!

Here I have used jQuery function, it can be done by simple JavaScript also...

        <form id="form_data">
           <input type="anything"  name="anything" />
           <input type="anything"  name="anything" />

             <!-- Save and Reset button -->
           <button type="button" id="btn_submit">Save</button>
           <button type="reset" id="btn_reset" style="display: none;"></button>
        </form>

<script type="text/javascript">
$(function(){
    $('#btn_submit').click(function(){
        // Do what ever you want
       $('#btn_reset').click();  // Clicking reset button
    });
});
</script>

How to check if a network port is open on linux?

Agree with Sachin. Just one improvement, use connect_ex instead of connect, which can avoid try except

>>> def port_check(ip_port):
...     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
...     s.settimeout(1)
...     r = s.connect_ex(ip_port)
...     return r == 0
... 
>>> port_check(loc)
True
>>> port_check(loc_x)
False
>>> loc
('10.3.157.24', 6443)
>>> 

How to actually search all files in Visual Studio

Press Ctrl+,

Then you will see a docked window under name of "Go to all"

This a picture of the "Go to all" in my IDE

Picture

Recyclerview inside ScrollView not scrolling smoothly

Every answer is same here. and i already used what everyone is suggested. Then i found that NestedScrollView is faster then ScrollView so

use

<androidx.core.widget.NestedScrollView

Instead of

<ScrollView

And use this as usual

recycleView.setNestedScrollingEnabled(false);

Draw horizontal rule in React Native

Creating a reusable Line component worked for me:

import React from 'react';
import { View } from 'react-native';

export default function Line() {
    return (
        <View style={{
            height: 1,
            backgroundColor: 'rgba(255, 255, 255 ,0.3)',
            alignSelf: 'stretch'
        }} />
    )
}

Now, Import and use Line anywhere:

<Line />

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Just to expand on @splattne's answer a little:

MapPath(string virtualPath) calls the following:

public string MapPath(string virtualPath)
{
    return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}

MapPath(VirtualPath virtualPath) in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) which contains the following:

//...
if (virtualPath == null)
{
    virtualPath = VirtualPath.Create(".");
}
//...

So if you call MapPath(null) or MapPath(""), you are effectively calling MapPath(".")

Do I need <class> elements in persistence.xml?

I'm not sure this solution is under the spec but I think I can share for others.

dependency tree

my-entities.jar

Contains entity classes only. No META-INF/persistence.xml.

my-services.jar

Depends on my-entities. Contains EJBs only.

my-resources.jar

Depends on my-services. Contains resource classes and META-INF/persistence.xml.

problems

  • How can we specify <jar-file/> element in my-resources as the version-postfixed artifact name of a transient dependency?
  • How can we sync the <jar-file/> element's value and the actual transient dependency's one?

solution

direct (redundant?) dependency and resource filtering

I put a property and a dependency in my-resources/pom.xml.

<properties>
  <my-entities.version>x.y.z-SNAPSHOT</my-entities.version>
</properties>
<dependencies>
  <dependency>
    <!-- this is actually a transitive dependency -->
    <groupId>...</groupId>
    <artifactId>my-entities</artifactId>
    <version>${my-entities.version}</version>
    <scope>compile</scope> <!-- other values won't work -->
  </dependency>
  <dependency>
    <groupId>...</groupId>
    <artifactId>my-services</artifactId>
    <version>some.very.sepecific</version>
    <scope>compile</scope>
  </dependency>
<dependencies>

Now get the persistence.xml ready for being filtered

<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
  <persistence-unit name="myPU" transaction-type="JTA">
    ...
    <jar-file>lib/my-entities-${my-entities.version}.jar</jar-file>
    ...
  </persistence-unit>
</persistence>

Maven Enforcer Plugin

With the dependencyConvergence rule, we can assure that the my-entities' version is same in both direct and transitive.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.4.1</version>
  <executions>
    <execution>
      <id>enforce</id>
      <configuration>
        <rules>
           <dependencyConvergence/>
        </rules>
      </configuration>
      <goals>
        <goal>enforce</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Scripting SQL Server permissions

Yes, you can use a script like this to generate another script

SET NOCOUNT ON;
DECLARE @NewRole varchar(100), @SourceRole varchar(100);

-- Change as needed
SELECT @SourceRole = 'Giver', @NewRole = 'Taker';

SELECT
    state_desc + ' ' + permission_name + ' ON ' + OBJECT_NAME(major_id) + ' TO ' + @NewRole
FROM
    sys.database_permissions
WHERE
    grantee_principal_id = DATABASE_PRINCIPAL_ID(@SourceRole) AND
    -- 0 = DB,  1 = object/column, 3 = schema. 1 is normally enough
    class <= 3

This is taken from my answer here

Batch file to perform start, run, %TEMP% and delete all

@echo off
del /s /f /q c:\windows\temp\*.*
rd /s /q c:\windows\temp
md c:\windows\temp
del /s /f /q C:\WINDOWS\Prefetch
del /s /f /q %temp%\*.*
rd /s /q %temp%
md %temp%
deltree /y c:\windows\tempor~1
deltree /y c:\windows\temp
deltree /y c:\windows\tmp
deltree /y c:\windows\ff*.tmp
deltree /y c:\windows\history
deltree /y c:\windows\cookies
deltree /y c:\windows\recent
deltree /y c:\windows\spool\printers
del c:\WIN386.SWP
cls

How to define relative paths in Visual Studio Project?

Instead of using relative paths, you could also use the predefined macros of VS to achieve this.

$(ProjectDir) points to the directory of your .vcproj file, $(SolutionDir) is the directory of the .sln file.

You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:

project properties

In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):

additional include directories

You can use the Macros by typing $(MACRO_NAME) (note the $ and the round brackets).

How to install Openpyxl with pip

(optional) Install git for windows (https://git-scm.com/) to get git bash. Git bash is much more similar to Linux terminal than Windows cmd.

Install Anaconda 3

https://www.anaconda.com/download/

It should set itself into Windows PATH. Restart your PC. Then pip should work in your cmd

Then in cmd (or git bash), run command

pip install openpyxl

How does autowiring work in Spring?

Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:

UserService userService = new UserServiceImpl();

You will be using this after introducing DI:

@Autowired
private UserService userService;

For achieving this you need to create a bean of your service in your ServiceConfiguration file. After that you need to import that ServiceConfiguration class to your WebApplicationConfiguration class so that you can autowire that bean into your Controller like this:

public class AccController {

    @Autowired
    private UserService userService;
} 

You can find a java configuration based POC here example.

What can MATLAB do that R cannot do?

We can't because it's expected/required by our customers.

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

How do I clone a specific Git branch?

To clone a branch without fetching other branches:

mkdir $BRANCH
cd $BRANCH
git init
git remote add -t $BRANCH -f origin $REMOTE_REPO
git checkout $BRANCH

How to get all selected values from <select multiple=multiple>?

If you have multiple select boxes with multiple='multiple' and you want to select all selected options from every dropdown then use this HTML:

<select id='Alphabets'>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
</select>

<select id='Alphabets' multiple='multiple'>
    <option value="4">D</option>
    <option value="5">E</option>
    <option value="6">F</option>
</select>
<select id='Alphabets'>
    <option value="7">G</option>
    <option value="8">H</option>
    <option value="9">I</option>
</select>
<select id='Alphabets' multiple='multiple'>
    <option value="10">J</option>
    <option value="11">K</option>
    <option value="12">L</option>
</select>

JavaScript for above UI:

function show_Alphebets()
{
        var tag =document.querySelectorAll("select");        
        var values="";
        for(var i=1; i<4; i++) {
            if(tag[i].options.length>0)
            for (var option of tag[i].selectedOptions) {                  
                  values+= i+"(multiple)="+option.value+",";
            }
            else values+= i+"="+tag[i].value+",";
        }
        alert(values);
}

How to connect Android app to MySQL database?

The one way is by using webservice, simply write a webservice method in PHP or any other language . And From your android app by using http client request and response , you can hit the web service method which will return whatever you want.

For PHP You can create a webservice like this. Assuming below we have a php file in the server. And the route of the file is yourdomain.com/api.php

if(isset($_GET['api_call'])){
    switch($_GET['api_call']){
       case 'userlogin':
           //perform your userlogin task here
       break; 
    }
}

Now you can use Volley or Retrofit to send a network request to the above PHP Script and then, actually the php script will handle the database operation.

In this case the PHP script is called a RESTful API.

You can learn all the operation at MySQL from this tutorial. Android MySQL Tutorial to Perform CRUD.

Get selected option text with JavaScript

Use -

$.trim($("select").children("option:selected").text())   //cat

Here is the fiddle - http://jsfiddle.net/eEGr3/

PHP : send mail in localhost

It is configured to use localhost:25 for the mail server.

The error message says that it can't connect to localhost:25.

Therefore you have two options:

  1. Install / Properly configure an SMTP server on localhost port 25
  2. Change the configuration to point to some other SMTP server that you can connect to