Programs & Examples On #Anonymous scope

Find row in datatable with specific id

try this code

DataRow foundRow = FinalDt.Rows.Find(Value);

but set at lease one primary key

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is only supported by IE - the other browsers use a plugin architecture called NPAPI. However, there's a cross-browser plugin framework called Firebreath that you might find useful.

Why am I getting "void value not ignored as it ought to be"?

srand doesn't return anything so you can't initialize a with its return value because, well, because it doesn't return a value. Did you mean to call rand as well?

Correct way to use StringBuilder in SQL

You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.

However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table" it emits code which actually creates a StringBuilder behind the scenes and appends to it, so the end result is not that bad afterall.

But of course anyone looking at that code is bound to think that it is kind of retarded.

How to fit Windows Form to any screen resolution?

You can simply set the window state

this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

bootstrap responsive table content wrapping

_x000D_
_x000D_
.table td.abbreviation {_x000D_
  max-width: 30px;_x000D_
}_x000D_
.table td.abbreviation p {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
_x000D_
}
_x000D_
<table class="table">_x000D_
<tr>_x000D_
 <td class="abbreviation"><p>ABC DEF</p></td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I read a text file from the SD card in Android?

In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>

And your code will look like this:

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

This could go in the onCreate() method of your Activity, or somewhere else depending on just what it is you want to do.

Now() function with time trim

Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue).

how to open .mat file without using MATLAB?

You don't need to download any new software. You can use Octave Online to open .m files.

How to render a DateTime in a specific format in ASP.NET MVC 3?

In MVC5 I'd use, if your model is the datetime

string dt = Model.ToString("dd/MM/yyy"); 

Or if your model contains the property of the datetime

string dt = Model.dateinModel.ToString("dd/MM/yyy"); 

Here's the official meaning of the Formats:

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

JFrame in full screen Java

Set 2 properties below:

  1. extendedState = 6
  2. resizeable = true

It works for me.

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Working with TIFFs (import, export) in Python using numpy

First, I downloaded a test TIFF image from this page called a_image.tif. Then I opened with PIL like this:

>>> from PIL import Image
>>> im = Image.open('a_image.tif')
>>> im.show()

This showed the rainbow image. To convert to a numpy array, it's as simple as:

>>> import numpy
>>> imarray = numpy.array(im)

We can see that the size of the image and the shape of the array match up:

>>> imarray.shape
(44, 330)
>>> im.size
(330, 44)

And the array contains uint8 values:

>>> imarray
array([[  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       ..., 
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246],
       [  0,   1,   2, ..., 244, 245, 246]], dtype=uint8)

Once you're done modifying the array, you can turn it back into a PIL image like this:

>>> Image.fromarray(imarray)
<Image.Image image mode=L size=330x44 at 0x2786518>

Decreasing height of bootstrap 3.0 navbar

After spending few hours, adding the following css class fixed my issue.

Work with Bootstrap 3.0.*

.tnav .navbar .container { height: 28px; }

Work with Bootstrap 3.3.4

.navbar-nav > li > a, .navbar-brand {
    padding-top:4px !important; 
    padding-bottom:0 !important;
    height: 28px;
}
.navbar {min-height:28px !important;}

Update Complete code to customize and decrease height of navbar with screenshot.

enter image description here

CSS:

/* navbar */
.navbar-primary .navbar { background:#9f58b5; border-bottom:none; }
.navbar-primary .navbar .nav > li > a {color: #501762;}
.navbar-primary .navbar .nav > li > a:hover {color: #fff; background-color: #8e49a3;}
.navbar-primary .navbar .nav .active > a,.navbar .nav .active > a:hover {color: #fff; background-color: #501762;}
.navbar-primary .navbar .nav li > a .caret, .tnav .navbar .nav li > a:hover .caret {border-top-color: #fff;border-bottom-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover {}
.navbar-primary .navbar .nav > li.dropdown.open > a {color: #fff;background-color: #9f58b5;border-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover .caret, .tnav .navbar .nav > li.dropdown.open > a .caret {border-top-color: #fff;}
.navbar-primary .navbar .navbar-brand {color:#fff;}
.navbar-primary .navbar .nav.pull-right {margin-left: 10px; margin-right: 0;}
.navbar-xs .navbar-primary .navbar { min-height:28px; height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
.navbar-sm .navbar-primary .navbar { min-height:40px; height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 40px; }

Usage Code:

<div class="navbar-xs">
   <div class="navbar-primary">
       <nav class="navbar navbar-static-top" role="navigation">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-8">
                 <span class="sr-only">Toggle navigation</span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
                 <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Brand</a>
          </div>
          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
              <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Home</a></li>
                  <li><a href="#">Link</a></li>
                   <li><a href="#">Link</a></li>
              </ul>
          </div><!-- /.navbar-collapse -->
      </nav>
  </div>
</div>

Write a file in UTF-8 using FileWriter (Java)?

Safe Encoding Constructors

Getting Java to properly notify you of encoding errors is tricky. You must use the most verbose and, alas, the least used of the four alternate contructors for each of InputStreamReader and OutputStreamWriter to receive a proper exception on an encoding glitch.

For file I/O, always make sure to always use as the second argument to both OutputStreamWriter and InputStreamReader the fancy encoder argument:

  Charset.forName("UTF-8").newEncoder()

There are other even fancier possibilities, but none of the three simpler possibilities work for exception handing. These do:

 OutputStreamWriter char_output = new OutputStreamWriter(
     new FileOutputStream("some_output.utf8"),
     Charset.forName("UTF-8").newEncoder() 
 );

 InputStreamReader char_input = new InputStreamReader(
     new FileInputStream("some_input.utf8"),
     Charset.forName("UTF-8").newDecoder() 
 );

As for running with

 $ java -Dfile.encoding=utf8 SomeTrulyRemarkablyLongcLassNameGoeShere

The problem is that that will not use the full encoder argument form for the character streams, and so you will again miss encoding problems.

Longer Example

Here’s a longer example, this one managing a process instead of a file, where we promote two different input bytes streams and one output byte stream all to UTF-8 character streams with full exception handling:

 // this runs a perl script with UTF-8 STD{IN,OUT,ERR} streams
 Process
 slave_process = Runtime.getRuntime().exec("perl -CS script args");

 // fetch his stdin byte stream...
 OutputStream
 __bytes_into_his_stdin  = slave_process.getOutputStream();

 // and make a character stream with exceptions on encoding errors
 OutputStreamWriter
   chars_into_his_stdin  = new OutputStreamWriter(
                             __bytes_into_his_stdin,
         /* DO NOT OMIT! */  Charset.forName("UTF-8").newEncoder()
                         );

 // fetch his stdout byte stream...
 InputStream
 __bytes_from_his_stdout = slave_process.getInputStream();

 // and make a character stream with exceptions on encoding errors
 InputStreamReader
   chars_from_his_stdout = new InputStreamReader(
                             __bytes_from_his_stdout,
         /* DO NOT OMIT! */  Charset.forName("UTF-8").newDecoder()
                         );

// fetch his stderr byte stream...
 InputStream
 __bytes_from_his_stderr = slave_process.getErrorStream();

 // and make a character stream with exceptions on encoding errors
 InputStreamReader
   chars_from_his_stderr = new InputStreamReader(
                             __bytes_from_his_stderr,
         /* DO NOT OMIT! */  Charset.forName("UTF-8").newDecoder()
                         );

Now you have three character streams that all raise exception on encoding errors, respectively called chars_into_his_stdin, chars_from_his_stdout, and chars_from_his_stderr.

This is only slightly more complicated that what you need for your problem, whose solution I gave in the first half of this answer. The key point is this is the only way to detect encoding errors.

Just don’t get me started about PrintStreams eating exceptions.

How can I quickly delete a line in VIM starting at the cursor position?

This is a very old question, but as VIM is still relevant something should be clarified.

Every answer and comment here as of October 2018 has referred to what would commonly be known as a "cut" action, thus using any of them will replace whatever is currently in VIM's unnamed register. This register tends to be treated like a default copy/paste clipboard, so none of these answers will work as desired if you are deleting the rest of a line to paste something in the same place afterward, as whatever was just deleted will be subsequently pasted in place of whatever was yanked before.

The true delete command in the OP's context is "_D (or "_C if insert mode is desired) This sends the deleted content into the black hole register, designated by "_, where it will bother no one ever again (although you can still undo this action using u).

That being said, whatever was last yanked is stored in the 0 register, and even if it gets replaced in the unnamed register, it can still be pasted using "0p.

Learn more about the black hole register and registers in general for extra VIM fun!

How to calculate UILabel height dynamically?

The current solution has been deprecated as of iOS 7.

Here is an updated solution:

+ (CGFloat)heightOfCellWithIngredientLine:(NSString *)ingredientLine
                       withSuperviewWidth:(CGFloat)superviewWidth
{
    CGFloat labelWidth                  = superviewWidth - 30.0f;
    //    use the known label width with a maximum height of 100 points
    CGSize labelContraints              = CGSizeMake(labelWidth, 100.0f);

    NSStringDrawingContext *context     = [[NSStringDrawingContext alloc] init];

    CGRect labelRect                    = [ingredientLine boundingRectWithSize:labelContraints
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                     attributes:nil
                                                        context:context];

    //    return the calculated required height of the cell considering the label
    return labelRect.size.height;
}

The reason that my solution is set up like this is because I am using a UITableViewCell and resizing the cell dynamically relative to how much room the label will take up.

Python: Find in list

 lstr=[1, 2, 3]
 lstr=map(str,lstr)
 r=re.compile('^(3){1}')
 results=list(filter(r.match,lstr))
 print(results)

DataTable: Hide the Show Entries dropdown but keep the Search box

sDom: "Tfrtip" or via a callback:

"fnHeaderCallback": function(){
    $('#YOURTABLENAME-table_length').hide();
}

Printing prime numbers from 1 through 100

#include<iostream>
using namespace std;
void main()
{
        int num,i,j,prime;
    cout<<"Enter the upper limit :";
    cin>>num;
    cout<<"Prime numbers till "<<num<<" are :2, ";

    for(i=3;i<=num;i++)
    {
        prime=1;
        for(j=2;j<i;j++)
        {
            if(i%j==0)
            {
                prime=0;
                break;
            }
        }
        if(prime==1)
            cout<<i<<", ";
    }
}

Kotlin unresolved reference in IntelliJ

Sometimes in similar situations (I don't think it is your problem because your case is very simple) it's worth to check kotlin file package.

If you have Kotlin file within the same package and put there some classes and missed the package declaration it looks inside the IntelliJ that you have classes in the same package but without definition of package the IntelliJ shows you:

Error:(5, 5) Kotlin: Unresolved reference: ...

Register DLL file on Windows Server 2008 R2

TS1086: An accessor cannot be declared in ambient context

Setting "skipLibCheck": true in tsconfig.json solved my problem

"compilerOptions": {
    "skipLibCheck": true
}

How to recompile with -fPIC

I hit this same issue trying to install Dashcast on Centos 7. The fix was adding -fPIC at the end of each of the CFLAGS in the x264 Makefile. Then I had to run make distclean for both x264 and ffmpeg and rebuild.

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

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

Just added the

set /p NetworkLocation= Enter name for network?

echo %NetworkLocation% >> netlist.txt

sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.

Can I do Android Programming in C++, C?

You can use the Android NDK, but answers should note that the Android NDK app is not free to use and there's no clear open source route to programming Android on Android in an increasingly Android-driven market that began as open source, with Android developer support or the extensiveness of the NDK app, meaning you're looking at abandoning Android as any kind of first steps programming platform without payments.

Note: I consider subscription requests as payments under duress and this is a freemium context which continues to go undefeated by the open source community.

Is it possible to specify the schema when connecting to postgres with JDBC?

Don't forget SET SCHEMA 'myschema' which you could use in a separate Statement

SET SCHEMA 'value' is an alias for SET search_path TO value. Only one schema can be specified using this syntax.

And since 9.4 and possibly earlier versions on the JDBC driver, there is support for the setSchema(String schemaName) method.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.

Example. Suppose I write:

(function() {

    var x = 2;

    // do stuff with x

})();

Now other libraries cannot access the variable x I created to use in my library.

AngularJS: How to run additional code after AngularJS has rendered a template?

Neither $scope.$evalAsync() or $timeout(fn, 0) worked reliably for me.

I had to combine the two. I made a directive and also put a priority higher than the default value for good measure. Here's a directive for it (Note I use ngInject to inject dependencies):

app.directive('postrenderAction', postrenderAction);

/* @ngInject */
function postrenderAction($timeout) {
    // ### Directive Interface
    // Defines base properties for the directive.
    var directive = {
        restrict: 'A',
        priority: 101,
        link: link
    };
    return directive;

    // ### Link Function
    // Provides functionality for the directive during the DOM building/data binding stage.
    function link(scope, element, attrs) {
        $timeout(function() {
            scope.$evalAsync(attrs.postrenderAction);
        }, 0);
    }
}

To call the directive, you would do this:

<div postrender-action="functionToRun()"></div>

If you want to call it after an ng-repeat is done running, I added an empty span in my ng-repeat and ng-if="$last":

<li ng-repeat="item in list">
    <!-- Do stuff with list -->
    ...

    <!-- Fire function after the last element is rendered -->
    <span ng-if="$last" postrender-action="$ctrl.postRender()"></span>
</li>

How to find out whether a file is at its `eof`?

The "for-else" design is often overlooked. See: Python Docs "Control Flow in Loop":

Example

with open('foobar.file', 'rb') as f:
    for line in f:
        foo()

    else:
        # No more lines to be read from file
        bar()

Is there a way to view past mysql queries with phpmyadmin?

you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe

it run your last mysql and you can see it in phpmyadmin and other section of your system.

notice: stop your current mysql version.

S F My English.

How to convert a string to ASCII

You can do it by using LINQ-expression.

  public static List<int> StringToAscii(string value)
  {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Value cannot be null or empty.", nameof(value));

        return value.Select(System.Convert.ToInt32).ToList();
  } 

Transpose list of lists

just for fun, valid rectangles and assuming that m[0] exists

>>> m = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[row[i] for row in m] for i in range(len(m[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Simplest way to read json from a URL in java

The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/

Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode

Where does the @Transactional annotation belong?

The correct answer for traditional Spring architectures is to place transactional semantics on the service classes, for the reasons that others have already described.

An emerging trend in Spring is toward domain-driven design (DDD). Spring Roo exemplifies the trend nicely. The idea is to make the domain object POJOs a lot richer than they are on typical Spring architectures (usually they are anemic), and in particular to put transaction and persistence semantics on the domain objects themselves. In cases where all that's needed is simple CRUD operations, the web controllers operate directly on the domain object POJOs (they're functioning as entities in this context), and there's no service tier. In cases where there's some kind of coordination needed between domain objects, you can have a service bean handle that, with @Transaction as per tradition. You can set the transaction propagation on the domain objects to something like REQUIRED so that the domain objects use any existing transactions, such as transactions that were started at the service bean.

Technically this technique makes use of AspectJ and <context:spring-configured />. Roo uses AspectJ inter-type definitions to separate the entity semantics (transactions and persistence) from the domain object stuff (basically fields and business methods).

Image library for Python 3

Qt works very well with graphics. In my opinion it is more versatile than PIL.

You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, QPainter.

To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.

Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:

from PySide.QtCore import *
from PySide.QtGui import *

app = QCoreApplication([])

img = QImage('input.jpg')

g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()

img.save('output.png')

But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.

What process is listening on a certain port on Solaris?

#!/usr/bin/bash
# This is a little script based on the "pfiles" solution that prints the PID and PORT.

pfiles `ls /proc` 2>/dev/null | awk "/^[^ \\t]/{smatch=\$0;next}/port:[ \\t]*${1}/{print smatch, \$0}{next}"

sed one-liner to convert all uppercase to lowercase?

With tr:

# Converts upper to lower case 
$ tr '[:upper:]' '[:lower:]' < input.txt > output.txt

# Converts lower to upper case
$ tr '[:lower:]' '[:upper:]' < input.txt > output.txt

Or, sed on GNU (but not BSD or Mac as they don't support \L or \U):

# Converts upper to lower case
$ sed -e 's/\(.*\)/\L\1/' input.txt > output.txt

# Converts lower to upper case
$ sed -e 's/\(.*\)/\U\1/' input.txt > output.txt
 

Deep copy in ES6 using the spread syntax

const a = {
  foods: {
    dinner: 'Pasta'
  }
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta

Using JSON.stringify and JSON.parse is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

How to create a date and time picker in Android?

I wrote up a little widget that allows you to pick both date and time.

DateTimeWidget

enter image description here

Retrieving the last record in each group - MySQL

UPD: 2017-03-31, the version 5.7.5 of MySQL made the ONLY_FULL_GROUP_BY switch enabled by default (hence, non-deterministic GROUP BY queries became disabled). Moreover, they updated the GROUP BY implementation and the solution might not work as expected anymore even with the disabled switch. One needs to check.

Bill Karwin's solution above works fine when item count within groups is rather small, but the performance of the query becomes bad when the groups are rather large, since the solution requires about n*n/2 + n/2 of only IS NULL comparisons.

I made my tests on a InnoDB table of 18684446 rows with 1182 groups. The table contains testresults for functional tests and has the (test_id, request_id) as the primary key. Thus, test_id is a group and I was searching for the last request_id for each test_id.

Bill's solution has already been running for several hours on my dell e4310 and I do not know when it is going to finish even though it operates on a coverage index (hence using index in EXPLAIN).

I have a couple of other solutions that are based on the same ideas:

  • if the underlying index is BTREE index (which is usually the case), the largest (group_id, item_value) pair is the last value within each group_id, that is the first for each group_id if we walk through the index in descending order;
  • if we read the values which are covered by an index, the values are read in the order of the index;
  • each index implicitly contains primary key columns appended to that (that is the primary key is in the coverage index). In solutions below I operate directly on the primary key, in you case, you will just need to add primary key columns in the result.
  • in many cases it is much cheaper to collect the required row ids in the required order in a subquery and join the result of the subquery on the id. Since for each row in the subquery result MySQL will need a single fetch based on primary key, the subquery will be put first in the join and the rows will be output in the order of the ids in the subquery (if we omit explicit ORDER BY for the join)

3 ways MySQL uses indexes is a great article to understand some details.

Solution 1

This one is incredibly fast, it takes about 0,8 secs on my 18M+ rows:

SELECT test_id, MAX(request_id) AS request_id
FROM testresults
GROUP BY test_id DESC;

If you want to change the order to ASC, put it in a subquery, return the ids only and use that as the subquery to join to the rest of the columns:

SELECT test_id, request_id
FROM (
    SELECT test_id, MAX(request_id) AS request_id
    FROM testresults
    GROUP BY test_id DESC) as ids
ORDER BY test_id;

This one takes about 1,2 secs on my data.

Solution 2

Here is another solution that takes about 19 seconds for my table:

SELECT test_id, request_id
FROM testresults, (SELECT @group:=NULL) as init
WHERE IF(IFNULL(@group, -1)=@group:=test_id, 0, 1)
ORDER BY test_id DESC, request_id DESC

It returns tests in descending order as well. It is much slower since it does a full index scan but it is here to give you an idea how to output N max rows for each group.

The disadvantage of the query is that its result cannot be cached by the query cache.

Change div height on button click

_x000D_
_x000D_
var ww1 = "";_x000D_
var ww2 = 0;_x000D_
var myVar1 ;_x000D_
var myVar2 ;_x000D_
function wm1(){_x000D_
  myVar1 =setInterval(w1, 15);_x000D_
}_x000D_
function wm2(){_x000D_
  myVar2 =setInterval(w2, 15);_x000D_
}_x000D_
function w1(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) <= 200){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)+5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar1);_x000D_
    }_x000D_
}_x000D_
function w2(){_x000D_
 ww1=document.getElementById('chartdiv').style.height;_x000D_
 ww2= ww1.replace("px", ""); _x000D_
    if(parseFloat(ww2) >= 50){_x000D_
document.getElementById('chartdiv').style.height = (parseFloat(ww2)-5) + 'px';_x000D_
    }else{_x000D_
      clearInterval(myVar2);_x000D_
    }_x000D_
}
_x000D_
<html>_x000D_
  <head>    _x000D_
  </head>_x000D_
_x000D_
<body >_x000D_
    <button type="button" onClick = "wm1()">200px</button>_x000D_
    <button type="button" onClick = "wm2()">50px</button>_x000D_
    <div id="chartdiv" style="width: 100%; height: 50px; background-color:#ccc"></div>_x000D_
  _x000D_
  <div id="demo"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Make JQuery UI Dialog automatically grow or shrink to fit its contents

Height is supported to auto.

Width is not!

To do some sort of auto get the size of the div you are showing and then set the window with.

In the C# code..

TheDiv.Style["width"] = "200px";

    private void setWindowSize(int width, int height)
    {
        string widthScript =    "$('.dialogDiv').dialog('option', 'width', "    +   width   +");";
        string heightScript =   "$('.dialogDiv').dialog('option', 'height', "   +   height  + ");";

        ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
            "scriptDOWINDOWSIZE",
            "<script type='text/javascript'>"
            + widthScript
            + heightScript +
            "</script>", false);
    }

How do I align views at the bottom of the screen?

You don't even need to nest the second relative layout inside the first one. Simply use the android:layout_alignParentBottom="true" in the Button and EditText.

Entity Framework Queryable async

There is a massive difference in the example you have posted, the first version:

var urls = await context.Urls.ToListAsync();

This is bad, it basically does select * from table, returns all results into memory and then applies the where against that in memory collection rather than doing select * from table where... against the database.

The second method will not actually hit the database until a query is applied to the IQueryable (probably via a linq .Where().Select() style operation which will only return the db values which match the query.

If your examples were comparable, the async version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async functionality.

However the major difference (and benefit) is that the async version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).

Add Favicon to Website

Simply put a file named favicon.ico in the webroot.

If you want to know more, please start reading:

Extract Google Drive zip from Google colab notebook

After mounting on drive, use shutil.unpack_archive. It works with almost all archive formats (e.g., “zip”, “tar”, “gztar”, “bztar”, “xztar”) and it's simple:

import shutil
shutil.unpack_archive("filename", "path_to_extract")

Android EditText view Floating Hint in Material Design

The Android support library can be imported within gradle in the dependencies :

    compile 'com.android.support:design:22.2.0'

It should be included within GradlePlease! And as an example to use it:

 <android.support.design.widget.TextInputLayout
    android:id="@+id/to_text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextViewTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="To"
        android:layout_marginTop="45dp"
        />
</android.support.design.widget.TextInputLayout>

Btw, the editor may not understand that AutoCompleteTextView is allowed within TextInputLayout.

How do I handle the window close event in Tkinter?

Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager.

You can use the protocol method to install a handler for this protocol (the widget must be a Tk or Toplevel widget):

Here you have a concrete example:

import tkinter as tk
from tkinter import messagebox

root = tk.Tk()

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

How to run TypeScript files from command line?

To add to @Aamod answer above, If you want to use one command line to compile and run your code, you can use the following:

Windows:

tsc main.ts | node main.js

Linux / macOS:

tsc main.ts && node main.js

JSON Stringify changes time of date because of UTC

In this case I think you need transform the date to UNIX timestamp

timestamp = testDate.getTime();
strJson = JSON.stringify(timestamp);

After that you can re use it to create a date object and format it. Example with javascript and toLocaleDateString ( https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleDateString )

newDateObject = new Date(JSON.parse(strJson));
newDateObject = newDateObject.toLocalDateStrin([
  "fr-FR",
]);

If you use stringify to use AJAX, now it's not useful. You just need to send timestamp and get it in your script:

$newDateObject = new \DateTime();
$newDateObject->setTimestamp(round($timestamp/1000));

Be aware that getTime() will return a time in milliseconds and the PHP function setTimestamp take time in seconds. It's why you need to divide by 1000 and round.

Java and SQLite

The example code leads to a memory leak in Tomcat (after undeploying the webapp, the classloader still remains in memory) which will cause an outofmemory eventually. The way to solve it is to use the sqlite-jdbc-3.7.8.jar; it's a snapshot, so it doesn't appear for maven yet.

How to navigate through a vector using iterators? (C++)

Vector's iterators are random access iterators which means they look and feel like plain pointers.

You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];

Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

std::advance(it, 5);
int sixth = *it;

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

What is function overloading and overriding in php?

Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).

If you define your function like this:

function f($p=0)
{
  if($p)
  {
    //implement functionality #1 here
  }
  else
  {
    //implement functionality #2 here
  }
}

When you call this function like:

f();

you'll get one functionality (#1), but if you call it with parameter like:

f(1);

you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).

I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).

Write to CSV file and export it?

How to write to a file (easy search in Google) ... 1st Search Result

As far as creation of the file each time a user accesses the page ... each access will act on it's own behalf. You business case will dictate the behavior.

Case 1 - same file but does not change (this type of case can have multiple ways of being defined)

  • You would have logic that created the file when needed and only access the file if generation is not needed.

Case 2 - each user needs to generate their own file

  • You would decide how you identify each user, create a file for each user and access the file they are supposed to see ... this can easily merge with Case 1. Then you delete the file after serving the content or not if it requires persistence.

Case 3 - same file but generation required for each access

  • Use Case 2, this will cause a generation each time but clean up once accessed.

hasOwnProperty in JavaScript

hasOwnProperty expects the property name as a string, so it would be shape1.hasOwnProperty("name")

jQuery ajax request with json response, how to?

Firstly, it will help if you set the headers of your PHP to serve JSON:

header('Content-type: application/json');

Secondly, it will help to adjust your ajax call:

$.ajax({
    url: "main.php",
    type: "POST",
    dataType: "json",
    data: {"action": "loadall", "id": id},
    success: function(data){
        console.log(data);
    },
    error: function(error){
         console.log("Error:");
         console.log(error);
    }
});

If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.

NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

I also ran into the same problem, where the initial dtabase size is set to 4Gb and autogrowth is set by 1Mb. The virtual encrypted TrueCrypt drive that the databse was on, seemed to have plenty of space.

I changed a couple of (the above) things:

  • I turned the Windows service for Sql Server Express from automatic to manual, so only the 'regular' Sql Server is running. (Even though I am running Sql Server 2008 R2 which should allow 10 GB.)
  • I changed the autogrowth from 1 MB to 10%
  • I changed the autogrowth increment-size from 10% to 1000 MB
  • I defragmented the drive
  • I shrank the database:
    • manually DBCC SHRINKDATABASE('...')
    • automatically right click on database | "properties" | "Auto Shrink" | "Truncate log on check point")

All to little avail (I could insert some more records, but soon ran into the same problem). The pagefile mentioned by Tobbi, made me try a larger virtual drive. (Even though my drive should not contain any such system files, since I run without it being mounted a lot of the time.)

  • I made a new larger virtual drive with TrueCrypt

When making this, I ran into a TrueCrypt-question, if I am going to store files larger than 4gb (as shown in this SuperUser question).

  • I told TrueCrypt I would store files larger than 4 GB

After these last two I was doing fine, and I am assuming this last one did the trick. I think TrueCrypt chooses an exfat file system (as described here), which limits all files to 4GB. (So I probably did not need to enlarge the drive after all, but I did anyway.)

This is probably a very rare border case, but maybe it is of help to somebody.

Is there any free OCR library for Android?

Google Goggles is the perfect application for doing both OCR and translation.
And the good news is that Google Goggles to Become App Platform.

Until then, you can use IQ Engines.

How to take character input in java

using java you can do this:

Using the Scanner:

Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast

Using the BufferedReader:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast

In the two cases you need to pass you Default input, in my case System.in

Inserting a blank table row with a smaller height

I couldn't get anything to work until I tried this simple line:

<p style="margin-top:0; margin-bottom:0; line-height:.5"><br /></p>

which allows you to vary a filler line height to your hearts content (I was [probably MISusing Table to get three columns (boxes) of text which I then wanted to line up along the bottom)

I'm an amateur so would appreciate comments

Variable declaration in a header file

What about this solution?

#ifndef VERSION_H
#define VERSION_H

static const char SVER[] = "14.2.1";
static const char AVER[] = "1.1.0.0";

#else

extern static const char SVER[];
extern static const char AVER[];

#endif /*VERSION_H */

The only draw back I see is that the include guard doesn't save you if you include it twice in the same file.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Custom Card Shape Flutter SDK

When Card I always use RoundedRectangleBorder.

Card(
  color: Colors.grey[900],
  shape: RoundedRectangleBorder(
    side: BorderSide(color: Colors.white70, width: 1),
    borderRadius: BorderRadius.circular(10),
  ),
  margin: EdgeInsets.all(20.0),
  child: Container(
    child: Column(
        children: <Widget>[
        ListTile(
            title: Text(
            'example',
            style: TextStyle(fontSize: 18, color: Colors.white),
            ),
        ),
        ],
    ),
  ),
),

How to insert values in two dimensional array programmatically?

Try to code below,

String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
  for(int y = 0; y < 3; y++)
  {
    shades[i][y] = value;
  }
}

Authorize attribute in ASP.NET MVC

The tag in web.config is based on paths, whereas MVC works with controller actions and routes.

It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.

The first case is covered from the answer of BobRock.

The user should have at least one of the following Roles to access the Controller or the Action

[Authorize(Roles = "Admin, Super User")]

The user should have both these roles in order to be able to access the Controller or Action

[Authorize(Roles = "Super User")]
[Authorize(Roles = "Admin")]

The users that can access the Controller or the Action are Betty and Johnny

[Authorize(Users = "Betty, Johnny")]

In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize].

options.AddPolicy("ElevatedRights", policy =>
                  policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));

[Authorize(Policy = "ElevatedRights")]

The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.

public class CustomAuthorizeAttribute: AuthorizeAttribute  
{  
    public override void OnAuthorization(AuthorizationContext filterContext)  
    {  }
}

The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize] attribute.

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

I was able to do this with the following classes in my project

d-flex justify-content-end

<div class="col-lg-6 d-flex justify-content-end">

Biggest differences of Thrift vs Protocol Buffers?

One obvious thing not yet mentioned is that can be both a pro or con (and is same for both) is that they are binary protocols. This allows for more compact representation and possibly more performance (pros), but with reduced readability (or rather, debuggability), a con.

Also, both have bit less tool support than standard formats like xml (and maybe even json).

(EDIT) Here's an Interesting comparison that tackles both size & performance differences, and includes numbers for some other formats (xml, json) as well.

Filename timestamp in Windows CMD batch script getting truncated

In the past, I've used a .cmd script I found on the Internet. I hate the way localization normally messes with dates. Anytime you have dates in filenames (or anywhere else, if I may be so bold) I figure you want them in ISO 8601 format:

2015-02-19T14:54:51Z

or something else that has Y M D H M in that order, such as

2015-02-19 14:54

because it fixes the MDY / DMY ambiguity and because it's sortable as text.

I don't know where I got that .cmd script, but it may have been http://ss64.com/nt/syntax-getdate.html, which works beautifully on my YYYY-MM-DD Windows 8.1 and on a M/D/YYYY vanilla install of Windows 7. Both give the same format:

2015-02-09 04:43

Setting HttpContext.Current.Session in a unit test

I worte something about this a while ago.

Unit Testing HttpContext.Current.Session in MVC3 .NET

Hope it helps.

[TestInitialize]
public void TestSetup()
{
    // We need to setup the Current HTTP Context as follows:            

    // Step 1: Setup the HTTP Request
    var httpRequest = new HttpRequest("", "http://localhost/", "");

    // Step 2: Setup the HTTP Response
    var httpResponce = new HttpResponse(new StringWriter());

    // Step 3: Setup the Http Context
    var httpContext = new HttpContext(httpRequest, httpResponce);
    var sessionContainer = 
        new HttpSessionStateContainer("id", 
                                       new SessionStateItemCollection(),
                                       new HttpStaticObjectsCollection(), 
                                       10, 
                                       true,
                                       HttpCookieMode.AutoDetect,
                                       SessionStateMode.InProc, 
                                       false);
    httpContext.Items["AspSession"] = 
        typeof(HttpSessionState)
        .GetConstructor(
                            BindingFlags.NonPublic | BindingFlags.Instance,
                            null, 
                            CallingConventions.Standard,
                            new[] { typeof(HttpSessionStateContainer) },
                            null)
        .Invoke(new object[] { sessionContainer });

    // Step 4: Assign the Context
    HttpContext.Current = httpContext;
}

[TestMethod]
public void BasicTest_Push_Item_Into_Session()
{
    // Arrange
    var itemValue = "RandomItemValue";
    var itemKey = "RandomItemKey";

    // Act
    HttpContext.Current.Session.Add(itemKey, itemValue);

    // Assert
    Assert.AreEqual(HttpContext.Current.Session[itemKey], itemValue);
}

Class has no initializers Swift

This is from Apple doc

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You get the error message Class "HomeCell" has no initializers because your variables is in an indeterminate state. Either you create initializers or you make them optional types, using ! or ?

Get google map link with latitude/longitude

None of the above answers worked for me, but I got it working with the following:

src="'https://maps.google.com/maps?q=' + lat + ',' + long + '&t=&z=15&ie=UTF8&iwloc=&output=embed'"

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

How to search multiple columns in MySQL?

1)

select *
from employee em
where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';

2)

select *
from employee em
where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';

First is usefull when we have data like : 'firstname lastname'.

e.g

  • parth patel
  • parth p
  • patel parth

Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.

e.g

  • parth-patel
  • parth_p
  • patel#parth

How to display a json array in table format?

using jquery $.each you can access all data and also set in table like this

<table style="width: 100%">
     <thead>
          <tr>
               <th>Id</th>
               <th>Name</th>
               <th>Category</th>
               <th>Color</th>
           </tr>
     </thead>
     <tbody id="tbody">
     </tbody>
</table>

$.each(data, function (index, item) {
     var eachrow = "<tr>"
                 + "<td>" + item[1] + "</td>"
                 + "<td>" + item[2] + "</td>"
                 + "<td>" + item[3] + "</td>"
                 + "<td>" + item[4] + "</td>"
                 + "</tr>";
     $('#tbody').append(eachrow);
});

How to connect to a remote Windows machine to execute commands using python?

I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint

Server:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection 

Client

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

it also have all the needed information for simple client/server applications.

Just convert the server and use some simple protocol to call a function from python.

P.S: i'm sure there are a lot of better options, it's just a simple one if you want...

Using a RegEx to match IP addresses in Python

If you really want to use RegExs, the following code may filter the non-valid ip addresses in a file, no matter the organiqation of the file, one or more per line, even if there are more text (concept itself of RegExs) :

def getIps(filename):
    ips = []
    with open(filename) as file:
        for line in file:
            ipFound = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$").findall(line)
            hasIncorrectBytes = False
            try:
                    for ipAddr in ipFound:
                        for byte in ipAddr:
                            if int(byte) not in range(1, 255):
                                hasIncorrectBytes = True
                                break
                            else:
                                pass
                    if not hasIncorrectBytes:
                        ips.append(ipAddr)
            except:
                hasIncorrectBytes = True

    return ips

How can I dynamically add a directive in AngularJS?

In addition to perfect Riceball LEE's example of adding a new element-directive

newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)

Adding a new attribute-directive to existed element could be done using this way:

Let's say you wish to add on-the-fly my-directive to the span element.

template: '<div>Hello <span>World</span></div>'

link: ($scope, $element, $attrs) ->

  span = $element.find('span').clone()
  span.attr('my-directive', 'my-directive')
  span = $compile(span)($scope)
  $element.find('span').replaceWith span

Hope that helps.

What are best practices that you use when writing Objective-C and Cocoa?

All these comments are great, but I'm really surprised nobody mentioned Google's Objective-C Style Guide that was published a while back. I think they have done a very thorough job.

How to execute my SQL query in CodeIgniter

I can see what @Þaw mentioned :

$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);

CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.

Next you need to use them as below:

$ENROLLEES->query();
$ENROLLEES->result();

and

$ACCOUNTS->query();
$ACCOUNTS->result();

Instead of using

$this->db->query();
$this->db->result();

See this for reference: http://ellislab.com/codeigniter/user-guide/database/connecting.html

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

#1214 - The used table type doesn't support FULLTEXT indexes

*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************

Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.

So i am mentioning here steps in very simple words will resolve your issue.

1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)

2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)

3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM

4.) Now Click on Replace All Button

5.) Click CTRL+S or File>Save

6.) Now Upload This File and I am Sure your issue will be resolved....

Shuffle an array with python, randomize array item order with python

Be aware that random.shuffle() should not be used on multi-dimensional arrays as it causes repetitions.

Imagine you want to shuffle an array along its first dimension, we can create the following test example,

import numpy as np
x = np.zeros((10, 2, 3))

for i in range(10):
   x[i, ...] = i*np.ones((2,3))

so that along the first axis, the i-th element corresponds to a 2x3 matrix where all the elements are equal to i.

If we use the correct shuffle function for multi-dimensional arrays, i.e. np.random.shuffle(x), the array will be shuffled along the first axis as desired. However, using random.shuffle(x) will cause repetitions. You can check this by running len(np.unique(x)) after shuffling which gives you 10 (as expected) with np.random.shuffle() but only around 5 when using random.shuffle().

How do I show the schema of a table in a MySQL database?

describe [db_name.]table_name;

for formatted output, or

show create table [db_name.]table_name;

for the SQL statement that can be used to create a table.

Why is json_encode adding backslashes?

I had a very similar problem, I had an array ready to be posted. in my post function I had this:

json = JSON.stringfy(json);

the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object.

In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable.

var aux = JSON.stringfy(json);

This way i keep json as an object, and not a string.

Generate UML Class Diagram from Java Project

How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.

Get the height and width of the browser viewport without scrollbars using jquery?

Here is a generic JS which should work in most browsers (FF, Cr, IE6+):

var viewportHeight;
var viewportWidth;
if (document.compatMode === 'BackCompat') {
    viewportHeight = document.body.clientHeight;
    viewportWidth = document.body.clientWidth;
} else {
    viewportHeight = document.documentElement.clientHeight;
    viewportWidth = document.documentElement.clientWidth;
}

Delete first character of a string in Javascript

var test = '0test';
test = test.replace(/0(.*)/, '$1');

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

JavaScript has replace() method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace() method having both string arguments is shown below.

var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text)  //ten, two, three, one, five, one

Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g (global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one in the above example.

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text)  //ten, two, three, ten, five, ten

Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi. Notice the i flag added here.

If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,

var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten

You can have more control over the replacement text using a function as the second argument.

How to style the menu items on an Android action bar

My guess is that you have to also style the views that are generated from the menu information in your onCreateOptionsMenu(). The styling you applied so far is working, but I doubt that the menu items, when rendered with text use a style that is the same as the title part of the ActionBar.

You may want to look at Menu.getActionView() to get the view for the menu action and then adjust it accordingly.

Git copy changes from one branch to another

If you are using tortoise git.

please follow the below steps.

  1. Checkout BranchB
  2. Open project folder, go to TortoiseGit --> Pull
  3. In pull screen, Change the remote branch "BranchA" and click ok.
  4. Then right click again, go to TortoiseGit --> Push.

Now your changes moved from BranchA to BranchB

What is the difference between "px", "dip", "dp" and "sp"?

Pixels(px) – corresponds to actual pixels on the screen. This is used if you want to give in terms of absolute pixels for width or height.

Density-independent Pixels (dp or dip) – an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

Scale-independent Pixels(sp) – this is like the dp unit, but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user’s preference.

Always use dp and sp only. sp for font sizes and dp for everything else. It will make UI compatible for Android devices with different densities. You can learn more about pixel and dp from https://www.google.com/design/spec/layout/units-measurements.html#units-measurements-density-independent-pixels-dp-

Source url:- http://www.androidtutorialshub.com/what-is-the-difference-between-px-dp-dip-sp-on-android/

Setting value of active workbook in Excel VBA

This is all you need

Set wbOOR = ActiveWorkbook

Calling Java from Python

You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)

Disclaimer: I am the author of Py4J

What does "subject" mean in certificate?

The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.

If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.

The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.

If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK

To look at your certificates on a microsoft machine:-

Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.

In the other areas of the store you will see the other trusted certificates used to validate signatures etc.

PHP remove all characters before specific string

You can use substring and strpos to accomplish this goal.

You could also use a regular expression to pattern match only what you want. Your mileage may vary on which of these approaches makes more sense.

How do I run Google Chrome as root?

It no longer suffices to start Chrome with --user-data-dir=/root/.config/google-chrome. It simply prints Aborted and ends (Chrome 48 on Ubuntu 12.04).

You need actually to run it as a non-root user. This you can do with

gksu -wu chrome-user google-chrome

where chrome-user is some user you've decided should be the one to run Chrome. Your Chrome user profile will be found at ~chrome-user/.config/google-chrome.

BTW, the old hack of changing all occurrences of geteuid to getppid in the chrome binary no longer works.

How to check if smtp is working from commandline (Linux)

The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)

thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
>    1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$ 
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<-  220 dur.bounceme.net ESMTP Postfix (Ubuntu)
 -> EHLO dur.bounceme.net
<-  250-dur.bounceme.net
<-  250-PIPELINING
<-  250-SIZE 10240000
<-  250-VRFY
<-  250-ETRN
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-8BITMIME
<-  250 DSN
 -> MAIL FROM:<[email protected]>
<-  250 2.1.0 Ok
 -> RCPT TO:<[email protected]>
<-  250 2.1.5 Ok
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Mon, 30 Dec 2013 14:33:17 -0800
 -> To: [email protected]
 -> From: [email protected]
 -> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
 -> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 -> 
 -> This is a test mailing
 -> 
 -> .
<-  250 2.0.0 Ok: queued as 52D162C3EFF
 -> QUIT
<-  221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$ 
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
     1 [email protected]                   15/553   test Mon, 30 Dec 2013 10:15:12 -0800
     2 [email protected]                   15/581   test Mon, 30 Dec 2013 10:15:55 -0800
     3 [email protected]                   15/581   test Mon, 30 Dec 2013 10:29:57 -0800
     4 [email protected]                   15/581   test Mon, 30 Dec 2013 11:54:16 -0800
>N   5 [email protected]                   15/581   test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
    by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
    for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>

This is a test mailing

New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$ 

It's just one easy command.

What is the HTML unicode character for a "tall" right chevron?

I use ? (0x25B8) for the right arrow, often to show a collapsed list; and I pair it with ? (0x25BE) to show the list opened up. Both are unobtrusive.

git: updates were rejected because the remote contains work that you do not have locally

I have done below steps. finally it's working fine.

Steps

1) git init

2) git status (for checking status)

3) git add . (add all the change file (.))

4) git commit -m "<pass your comment>"

5) git remote add origin "<pass your project clone url>"

6) git pull --allow-unrelated-histories "<pass your project clone url>" master

7) git push -u "<pass your project clone url>" master

Is it possible to add an HTML link in the body of a MAILTO link

It isn't possible as far as I can tell, since a link needs HTML, and mailto links don't create an HTML email.

This is probably for security as you could add javascript or iframes to this link and the email client might open up the end user for vulnerabilities.

XSLT - How to select XML Attribute by Attribute?

There are two problems with your xpath - first you need to remove the child selector from after Data like phihag mentioned. Also you forgot to include root in your xpath. Here is what you want to do:

select="/root/DataSet/Data[@Value1='2']/@Value2"

Convert date to YYYYMM format

Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).

To get yyyymm instead of yyyym, you can use this little trick:

select 
 right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
 + right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)

It's faster and more reliable than gettings parts of convert(..., 112).

How to execute powershell commands from a batch file?

This is what the code would look like in a batch file(tested, works):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"

Based on the information from:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

Meaning of = delete after function declaration

Are there any other "modifiers" (other than = 0 and = delete)?

Since it appears no one else answered this question, I should mention that there is also =default.

https://docs.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions#explicitly-defaulted-functions

moment.js get current time in milliseconds?

Since this thread is the first one from Google I found, one accurate and lazy way I found is :

const momentObject = moment().toObject();
// date doesn't exist with duration, but day does so use it instead
//   -1 because moment start from date 1, but a duration start from 0
const durationCompatibleObject = { ... momentObject, day: momentObject.date - 1 };
delete durationCompatibleObject.date;

const yourDuration = moment.duration(durationCompatibleObject);
// yourDuration.asMilliseconds()

now just add some prototypes (such as toDuration()) / .asMilliseconds() into moment and you can easily switch to milliseconds() or whatever !

Confirm Password with jQuery Validate

I'm implementing it in Play Framework and for me it worked like this:

1) Notice that I used data-rule-equalTo in input tag for the id inputPassword1. The code section of userform in my Modal:

<div class="form-group">
    <label for="pass1">@Messages("authentication.password")</label>
    <input class="form-control required" id="inputPassword1" placeholder="@Messages("authentication.password")" type="password" name="password" maxlength=10 minlength=5>
</div>
<div class="form-group">
    <label for="pass2">@Messages("authentication.password2")</label>
    <input class="form-control required" data-rule-equalTo="#inputPassword1" id="inputPassword2" placeholder="@Messages("authentication.password")" type="password" name="password2">
</div>

2)Since I used validator within a Modal

$(document).on("click", ".createUserModal", function () {
       $(this).find('#userform').validate({
           rules: {
               firstName: "required",
               lastName: "required",
               nationalId: {
                   required: true,
                   digits:true
               },
               email: {
                   required: true,
                   email: true
               },
               optradio: "required",
               password :{
                   required: true,
                   minlength: 5
               },
               password2: {
                   required: true
               }
           },
           highlight: function (element) {
               $(element).parent().addClass('error')
           },
           unhighlight: function (element) {
               $(element).parent().removeClass('error')
           },
           onsubmit: true
       });

   });

Hope it helps someone :).

How to Get True Size of MySQL Database?

SUM(Data_free) may or may not be valid. It depends on the history of innodb_file_per_table. More discussion is found here.

How to pass data in the ajax DELETE request other than headers

Read this Bug Issue: http://bugs.jquery.com/ticket/11586

Quoting the RFC 2616 Fielding

The DELETE method requests that the origin server delete the resource identified by the Request-URI.

So you need to pass the data in the URI

$.ajax({
    url: urlCall + '?' + $.param({"Id": Id, "bolDeleteReq" : bolDeleteReq}),
    type: 'DELETE',
    success: callback || $.noop,
    error: errorCallback || $.noop
});

How to get the current directory of the cmdlet being executed

Most answers don't work when debugging in the following IDEs:

  • PS-ISE (PowerShell ISE)
  • VS Code (Visual Studio Code)

Because in those the $PSScriptRoot is empty and Resolve-Path .\ (and similars) will result in incorrect paths.

Freakydinde's answer is the only one that resolves those situations, so I up-voted that, but I don't think the Set-Location in that answer is really what is desired. So I fixed that and made the code a little clearer:

$directorypath = if ($PSScriptRoot) { $PSScriptRoot } `
    elseif ($psise) { split-path $psise.CurrentFile.FullPath } `
    elseif ($psEditor) { split-path $psEditor.GetEditorContext().CurrentFile.Path }

Incorrect integer value: '' for column 'id' at row 1

This is because your data sending column type is integer and your are sending a string value to it.

So, the following way worked for me. Try with this one.

$insertQuery = "INSERT INTO workorders VALUES (
                    null,
                    '$priority',
                    '$requestType',
                    '$purchaseOrder',
                    '$nte',
                    '$jobSiteNumber'
                )";

Don't use 'null'. use it as null without single quotes.

How to use SearchView in Toolbar Android

Implementing the SearchView without the use of the menu.xml file and open through button

In your Activity we need to use the method of the onCreateOptionsMenumethod in which we will programmatically inflate the SearchView

private MenuItem searchMenu;
private String mSearchString="";

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);


        SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
        mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
        mSearchView.setMaxWidth(Integer.MAX_VALUE);

        searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
        searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);


        assert searchManager != null;
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        mSearchView.setIconifiedByDefault(false);

        SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
            public boolean onQueryTextChange(String newText) {
                mSearchString = newText;

                return true;
            }

            public boolean onQueryTextSubmit(String query) {
                mSearchString = query;

                searchMenu.collapseActionView();


                return true;
            }
        };

        mSearchView.setOnQueryTextListener(queryTextListener);


        return true;
    }

And in your Activity class, you can open the SearchView on any button click on toolbar like below

YOUR_BUTTON.setOnClickListener(view -> {

            searchMenu.expandActionView();

        });

How to hide Soft Keyboard when activity starts

Ed_Cat_Search = (EditText) findViewById(R.id.editText_Searc_Categories);

Ed_Cat_Search.setInputType(InputType.TYPE_NULL);

Ed_Cat_Search.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        Ed_Cat_Search.setInputType(InputType.TYPE_CLASS_TEXT);
        Ed_Cat_Search.onTouchEvent(event); // call native handler
        return true; // consume touch even
    }
});

this one worked for me

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

Find integer index of rows with NaN in pandas dataframe

Another simple solution is list(np.where(df['b'].isnull())[0])

Dynamic SQL results into temp table in SQL Stored procedure

CREATE PROCEDURE dbo.pdpd_DynamicCall 
AS
DECLARE @SQLString_2 NVARCHAR(4000)
SET NOCOUNT ON
Begin
    --- Create global temp table
    CREATE TABLE ##T1 ( column_1 varchar(10) , column_2 varchar(100) )

    SELECT @SQLString_2 = 'INSERT INTO ##T1( column_1, column_2) SELECT column_1 = "123", column_2 = "MUHAMMAD IMRON"'
    SELECT @SQLString_2 = REPLACE(@SQLString_2, '"', '''')

    EXEC SP_EXECUTESQL @SQLString_2

    --- Test Display records
    SELECT * FROM ##T1

    --- Drop global temp table 
    IF OBJECT_ID('tempdb..##T1','u') IS NOT NULL
    DROP TABLE ##T1
End

Reduce git repository size

Thanks for your replies. Here's what I did:

git gc
git gc --aggressive
git prune

That seemed to have done the trick. I started with around 10.5MB and now it's little more than 980KBs.

check android application is in foreground or not?

Below is updated solution for the latest Android SDK.

String PackageName = context.getPackageName();
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ComponentName componentInfo;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            List<ActivityManager.AppTask> tasks = manager.getAppTasks();
            componentInfo = tasks.get(0).getTaskInfo().topActivity;
        }
        else
        {
            List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(1);
            componentInfo = tasks.get(0).topActivity;
        }

        if (componentInfo.getPackageName().equals(PackageName))
            return true;
        return false;

Hope this helps, thanks.

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

Using android.support.v7.widget.CardView in my project (Eclipse)

I did what FD_ said and it crashed with errors as it was looking for "Landroid/support/v7/cardview/R$styleable;", which was not compiled with it

If you really want to use CardView before in eclipse before it gets its own library, you can extract the classes from the classes.jar, copy and paste them into your project, with the values.xml from above from Android Studio and change all the references to android.support.v7.R to yourpackagename.R in the copied classes. This worked and ran for me

Remove shadow below actionbar

For Xamarin Developers, please use : SupportActionBar.Elevation = 0; for AppCompatActivity or ActionBar.Elevation = 0; for non-compat Activities

Run C++ in command prompt - Windows

I really don't see what your problem is, the question is rather unspecific. Given Notepad++ I assume you use Windows.

You have so many options here, from the MinGW (using the GCC tool chain and GNU make) to using a modern MSVC. You can use the WDK (ddkbuild.bat/.cmd or plain build.exe), the Windows SDK (nmake.exe), other tools such as premake and CMake, or msbuild that comes with MSVC and the Windows SDK.

I mean the compiler names will differ, cl.exe for MSVC and the WDK and Windows SDK, gcc.exe for MinGW, but even from the console it is customary to organize your project in some way. This is what make and friends were invented for after all.

So to know the command line switches of your particular compiler consult the manual of that very compiler. To find ways to automate your build (i.e. the ability to run a simple command instead of a complex command line), you could sift through the list on Wikipedia or pick one of the tools I mentioned above and go with that.

Side-note: it isn't necessary to ask people not to mention IDEs. Most professional developers have automated their builds to run from a command line and not from within the IDE (as during the development cycle for example), because there are so many advantages to that approach.

Center div on the middle of screen

The best way to align a div in center both horizontally and vertically will be

HTML

<div></div>

CSS:

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

Shortcut to create properties in Visual Studio?

You could type "prop" and then press tab twice. That will generate the following.

public TYPE Type { get; set; }

Then you change "TYPE" and "Type":

public string myString {get; set;}

You can also get the full property typing "propfull" and then tab twice. That would generate the field and the full property.

private int myVar;

public int MyProperty
{
    get { return myVar;}
    set { myVar = value;}
}

How do I get the height of a div's full content with jQuery?

You can get it with .outerHeight().

Sometimes, it will return 0. For the best results, you can call it in your div's ready event.

To be safe, you should not set the height of the div to x. You can keep its height auto to get content populated properly with the correct height.

$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})

You can find a detailed post here.

Generate a range of dates using SQL

I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.

print("code sample");

select  top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
from (
select  1 as A union
select  2 union
select  3 union
select  4 union
select  5 union
select  6 union
select  7 union
select  8 union
select  9 union
select  10 union
select  11 union
select  12 union
select  13 union
select  14 union
select  15 union
select  16 union
select  17 union
select  18 union
select  19 union
select  20 union
select  21 
) l
cross join (
select 1 as A union
select 2 union
select 3 union
select 4 union
select 5 union
select 6 union
select 7 union
select 8 union
select 9 union
select 10 union
select 11 union
select 12 union
select 13 union
select 14 union
select 15 union
select 16 union
select 17 union
select 18
) r
print("code sample");

CSS set li indent

li{
    margin-left:50px;
}

or replace 50px with whatever you want.

Scroll to a specific Element Using html

Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.

For example (taken from the W3 specification):

You may read more about this in <A href="#section2">Section Two</A>.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to <A href="#section2">Section Two</A> above
for more details.

What does T&& (double ampersand) mean in C++11?

It denotes an rvalue reference. Rvalue references will only bind to temporary objects, unless explicitly generated otherwise. They are used to make objects much more efficient under certain circumstances, and to provide a facility known as perfect forwarding, which greatly simplifies template code.

In C++03, you can't distinguish between a copy of a non-mutable lvalue and an rvalue.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(const std::string&);

In C++0x, this is not the case.

std::string s;
std::string another(s);           // calls std::string(const std::string&);
std::string more(std::string(s)); // calls std::string(std::string&&);

Consider the implementation behind these constructors. In the first case, the string has to perform a copy to retain value semantics, which involves a new heap allocation. However, in the second case, we know in advance that the object which was passed in to our constructor is immediately due for destruction, and it doesn't have to remain untouched. We can effectively just swap the internal pointers and not perform any copying at all in this scenario, which is substantially more efficient. Move semantics benefit any class which has expensive or prohibited copying of internally referenced resources. Consider the case of std::unique_ptr- now that our class can distinguish between temporaries and non-temporaries, we can make the move semantics work correctly so that the unique_ptr cannot be copied but can be moved, which means that std::unique_ptr can be legally stored in Standard containers, sorted, etc, whereas C++03's std::auto_ptr cannot.

Now we consider the other use of rvalue references- perfect forwarding. Consider the question of binding a reference to a reference.

std::string s;
std::string& ref = s;
(std::string&)& anotherref = ref; // usually expressed via template

Can't recall what C++03 says about this, but in C++0x, the resultant type when dealing with rvalue references is critical. An rvalue reference to a type T, where T is a reference type, becomes a reference of type T.

(std::string&)&& ref // ref is std::string&
(const std::string&)&& ref // ref is const std::string&
(std::string&&)&& ref // ref is std::string&&
(const std::string&&)&& ref // ref is const std::string&&

Consider the simplest template function- min and max. In C++03 you have to overload for all four combinations of const and non-const manually. In C++0x it's just one overload. Combined with variadic templates, this enables perfect forwarding.

template<typename A, typename B> auto min(A&& aref, B&& bref) {
    // for example, if you pass a const std::string& as first argument,
    // then A becomes const std::string& and by extension, aref becomes
    // const std::string&, completely maintaining it's type information.
    if (std::forward<A>(aref) < std::forward<B>(bref))
        return std::forward<A>(aref);
    else
        return std::forward<B>(bref);
}

I left off the return type deduction, because I can't recall how it's done offhand, but that min can accept any combination of lvalues, rvalues, const lvalues.

Video streaming over websockets using JavaScript

Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.

Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).

You need to build a stream API and a Media Stream Transceiver to control the related media processing and transport.

How to search a Git repository by commit message?

To search the commit log (across all branches) for the given text:

git log --all --grep='Build 0051'

To search the actual content of commits through a repo's history, use:

git grep 'Build 0051' $(git rev-list --all)

to show all instances of the given text, the containing file name, and the commit sha1.

Finally, as a last resort in case your commit is dangling and not connected to history at all, you can search the reflog itself with the -g flag (short for --walk-reflogs:

git log -g --grep='Build 0051'

EDIT: if you seem to have lost your history, check the reflog as your safety net. Look for Build 0051 in one of the commits listed by

git reflog

You may have simply set your HEAD to a part of history in which the 'Build 0051' commit is not visible, or you may have actually blown it away. The git-ready reflog article may be of help.

To recover your commit from the reflog: do a git checkout of the commit you found (and optionally make a new branch or tag of it for reference)

git checkout 77b1f718d19e5cf46e2fab8405a9a0859c9c2889
# alternative, using reflog (see git-ready link provided)
# git checkout HEAD@{10}
git checkout -b build_0051 # make a new branch with the build_0051 as the tip

How do I link to part of a page? (hash?)

Just append a hash with an ID of an element to the URL. E.g.

<div id="about"></div>

and

http://mysite.com/#about

So the link would look like:

<a href="http://mysite.com/#about">About</a>

or just

<a href="#about">About</a>

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

You can do the same like this:

@Override
public FaqQuestions getFaqQuestionById(Long questionId) {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    FaqQuestions faqQuestions = null;
    try {
        faqQuestions = (FaqQuestions) session.get(FaqQuestions.class,
                questionId);
        Hibernate.initialize(faqQuestions.getFaqAnswers());

        tx.commit();
        faqQuestions.getFaqAnswers().size();
    } finally {
        session.close();
    }
    return faqQuestions;
}

Just use faqQuestions.getFaqAnswers().size()nin your controller and you will get the size if lazily intialised list, without fetching the list itself.

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Use this

create a user in admin group

add this user details in web config like below

<system.web>
   <identity impersonate="true"
    userName="User Name"
    password="Password" />
    `enter code here`</system.web>

restart the IIS and check again

-tony-

Put buttons at bottom of screen with LinearLayout?

Just add layout_weight="1" to in your linearLayout which having Buttons.

Edit :- let me make it simple

follow something like below, tags name may not be correct, it is just an Idea

<LL>// Top Parrent LinearLayout
   <LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
   <LL2 height="wrap_content" weight="1"  orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen

<LL/> TOP PARENT CLOSED

Making Maven run all tests, even when some fail

From the Maven Embedder documentation:

-fae,--fail-at-end Only fail the build afterwards; allow all non-impacted builds to continue

-fn,--fail-never NEVER fail the build, regardless of project result

So if you are testing one module than you are safe using -fae.

Otherwise, if you have multiple modules, and if you want all of them tested (even the ones that depend on the failing tests module), you should run mvn clean install -fn.
-fae will continue with the module that has a failing test (will run all other tests), but all modules that depend on it will be skipped.

Center a button in a Linear layout

It would be easier to use relative layouts, but for linear layouts I usually center by making sure the width matches parent :

    android:layout_width="match_parent"

and then just give margins to right and left accordingly.

    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"

Add leading zeroes to number in Java?

Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.

Python Pandas - Find difference between two data frames

Using the lambda function you can filter the rows with _merge value “left_only” to get all the rows in df1 which are missing from df2

df3 = df1.merge(df2, how = 'outer' ,indicator=True).loc[lambda x :x['_merge']=='left_only']
df

How to squash commits in git after they have been pushed?

A lot of problems can be avoided by only creating a branch to work on & not working on master:

git checkout -b mybranch

The following works for remote commits already pushed & a mixture of remote pushed commits / local only commits:

# example merging 4 commits

git checkout mybranch
git rebase -i mybranch~4 mybranch

# at the interactive screen
# choose fixup for commit: 2 / 3 / 4

git push -u origin +mybranch

I also have some pull request notes which may be helpful.

Write lines of text to a file in R

You could do that in a single statement

cat("hello","world",file="output.txt",sep="\n",append=TRUE)

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

I found the best way to fix this error: Bootstrap’s JavaScript requires jQuery version 1.9.1 or higher

In Wordpress..just ran this plugin and it fixed it. Thought I'd share jQuery Updater

How to skip over an element in .map()?

Answer sans superfluous edge cases:

const thingsWithoutNulls = things.reduce((acc, thing) => {
  if (thing !== null) {
    acc.push(thing);
  }
  return acc;
}, [])

Dynamic creation of table with DOM

You can create a dynamic table rows as below:

var tbl = document.createElement('table');
tbl.style.width = '100%';

for (var i = 0; i < files.length; i++) {

        tr = document.createElement('tr');

        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');

        ::::: // As many <td> you want

        td1.appendChild(document.createTextNode());
        td2.appendChild(document.createTextNode());
        td3.appendChild(document.createTextNode();

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        tbl.appendChild(tr);
}

Java Package Does Not Exist Error

You should add the following lines in your gradle build file (build.gradle)

dependencies { 
     compile files('/usr/share/stuff')
     ..
}

TLS 1.2 not working in cURL

TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1

Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0

You should consider an upgrade.

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

Linq code to select one item

That can better be condensed down to this.

var item = Items.First(x => x.Id == 123);

Your query is currently collecting all results (and there may be more than one) within the enumerable and then taking the first one from that set, doing more work than necessary.

Single/SingleOrDefault are worthwhile, but only if you want to iterate through the entire collection and verify that the match is unique in addition to selecting that match. First/FirstOrDefault will just take the first match and leave, regardless of how many duplicates actually exist.

how to implement a pop up dialog box in iOS

Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.

Here is a sample of how it looks in Swift:

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
    (UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
    () -> Void in
}

As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!

Updated for Swift 4.2

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

How to start an Intent by passing some parameters to it?

I think you want something like this:

Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);

or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I know it's a bit of a late answer for this post, but for reference...

CSS

ul {
    color: red;
}

li {
    color: black;
}

The bullet colour is defined on the ul tag and then we switch the li colour back.

CURL Command Line URL Parameters

The application/x-www-form-urlencoded Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:

curl -X DELETE "http://localhost:5000/locations?id=3"

or

curl -X GET "http://localhost:5000/locations?id=3"

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

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

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

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

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


callA();

How to check if click event is already bound - JQuery

Here's my version:

Utils.eventBoundToFunction = function (element, eventType, fCallback) {
    if (!element || !element.data('events') || !element.data('events')[eventType] || !fCallback) {
        return false;
    }

    for (runner in element.data('events')[eventType]) {
        if (element.data('events')[eventType][runner].handler == fCallback) {
            return true;
        }

    }

    return false;
};

Usage:

Utils.eventBoundToFunction(okButton, 'click', handleOkButtonFunction)

Show all current locks from get_lock

From MySQL 5.7 onwards, this is possible, but requires first enabling the mdl instrument in the performance_schema.setup_instruments table. You can do this temporarily (until the server is next restarted) by running:

UPDATE performance_schema.setup_instruments
SET enabled = 'YES'
WHERE name = 'wait/lock/metadata/sql/mdl';

Or permanently, by adding the following incantation to the [mysqld] section of your my.cnf file (or whatever config files MySQL reads from on your installation):

[mysqld]
performance_schema_instrument = 'wait/lock/metadata/sql/mdl=ON'

(Naturally, MySQL will need to be restarted to make the config change take effect if you take the latter approach.)

Locks you take out after the mdl instrument has been enabled can be seen by running a SELECT against the performance_schema.metadata_locks table. As noted in the docs, GET_LOCK locks have an OBJECT_TYPE of 'USER LEVEL LOCK', so we can filter our query down to them with a WHERE clause:

mysql> SELECT GET_LOCK('foobarbaz', -1);
+---------------------------+
| GET_LOCK('foobarbaz', -1) |
+---------------------------+
|                         1 |
+---------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM performance_schema.metadata_locks 
    -> WHERE OBJECT_TYPE='USER LEVEL LOCK'
    -> \G
*************************** 1. row ***************************
          OBJECT_TYPE: USER LEVEL LOCK
        OBJECT_SCHEMA: NULL
          OBJECT_NAME: foobarbaz
OBJECT_INSTANCE_BEGIN: 139872119610944
            LOCK_TYPE: EXCLUSIVE
        LOCK_DURATION: EXPLICIT
          LOCK_STATUS: GRANTED
               SOURCE: item_func.cc:5482
      OWNER_THREAD_ID: 35
       OWNER_EVENT_ID: 3
1 row in set (0.00 sec)

mysql> 

The meanings of the columns in this result are mostly adequately documented at https://dev.mysql.com/doc/refman/en/metadata-locks-table.html, but one point of confusion is worth noting: the OWNER_THREAD_ID column does not contain the connection ID (like would be shown in the PROCESSLIST or returned by CONNECTION_ID()) of the thread that holds the lock. Confusingly, the term "thread ID" is sometimes used as a synonym of "connection ID" in the MySQL documentation, but this is not one of those times. If you want to determine the connection ID of the connection that holds a lock (for instance, in order to kill that connection with KILL), you'll need to look up the PROCESSLIST_ID that corresponds to the THREAD_ID in the performance_schema.threads table. For instance, to kill the connection that was holding my lock above...

mysql> SELECT OWNER_THREAD_ID FROM performance_schema.metadata_locks
    -> WHERE OBJECT_TYPE='USER LEVEL LOCK'
    -> AND OBJECT_NAME='foobarbaz';
+-----------------+
| OWNER_THREAD_ID |
+-----------------+
|              35 |
+-----------------+
1 row in set (0.00 sec)

mysql> SELECT PROCESSLIST_ID FROM performance_schema.threads
    -> WHERE THREAD_ID=35;
+----------------+
| PROCESSLIST_ID |
+----------------+
|             10 |
+----------------+
1 row in set (0.00 sec)

mysql> KILL 10;
Query OK, 0 rows affected (0.00 sec)

Wait until ActiveWorkbook.RefreshAll finishes - VBA

Try executing:

ActiveSheet.Calculate

I use it in a worksheet in which control buttons change values of a dataset. On each click, Excel runs through this command and the graph updates immediately.

How to update only one field using Entity Framework?

I use ValueInjecter nuget to inject Binding Model into database Entity using following:

public async Task<IHttpActionResult> Add(CustomBindingModel model)
{
   var entity= await db.MyEntities.FindAsync(model.Id);
   if (entity== null) return NotFound();

   entity.InjectFrom<NoNullsInjection>(model);

   await db.SaveChangesAsync();
   return Ok();
}

Notice the usage of custom convention that doesn't update Properties if they're null from server.

ValueInjecter v3+

public class NoNullsInjection : LoopInjection
{
    protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
    {
        if (sp.GetValue(source) == null) return;
        base.SetValue(source, target, sp, tp);
    }
}

Usage:

target.InjectFrom<NoNullsInjection>(source);

Value Injecter V2

Lookup this answer

Caveat

You won't know whether the property is intentionally cleared to null OR it just didn't have any value it. In other words, the property value can only be replaced with another value but not cleared.

Changing file permission in Python

Simply include permissions integer in octal (works for both python 2 and python3):

os.chmod(path, 0o444)

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

Looking at the JDK, innermost constructor for Calendar.getInstance() has this:

public GregorianCalendar(TimeZone zone, Locale aLocale) {
    super(zone, aLocale);
    gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
    setTimeInMillis(System.currentTimeMillis());
}

so it already automatically does what you suggest. Date's default constructor holds this:

public Date() {
    this(System.currentTimeMillis());
}

So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-time to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.

AngularJS - Find Element with attribute

Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

In my case

  1. I have changed the port in postgresql.conf file
  2. and restart postgresql services in

Run => service.msc => Restart

  1. now retry

How do I create dynamic variable names inside a loop?

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

How do I define a method in Razor?

You mean inline helper?

@helper SayHello(string name)
{
    <div>Hello @name</div>
}

@SayHello("John")

Which Protocols are used for PING?

ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)

echo request and echo response are the two operation codes of ICMP used to implement ping.

Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.

ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.

Turning multiple lines into one comma separated line

perl -pi.bak -e 'unless(eof){s/\n/,/g}' your_file

This will create a backup of original file with an extension of .bak and then modifies the original file

Sql Server equivalent of a COUNTIF aggregate function

I usually do what Josh recommended, but brainstormed and tested a slightly hokey alternative that I felt like sharing.

You can take advantage of the fact that COUNT(ColumnName) doesn't count NULLs, and use something like this:

SELECT COUNT(NULLIF(0, myColumn))
FROM AD_CurrentView

NULLIF - returns NULL if the two passed in values are the same.

Advantage: Expresses your intent to COUNT rows instead of having the SUM() notation. Disadvantage: Not as clear how it is working ("magic" is usually bad).

MySQL Removing Some Foreign keys

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

alter table region drop foreign key region_ibfk_1;

or

more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

Attach IntelliJ IDEA debugger to a running Java process

Also, don't forget you need to add "-Xdebug" flag in app JAVA_OPTS if you want connect in debug mode.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

hi i'm using ruby on rails for csv generation. In our application we plan to go for the multi language(I18n) and we faced an issue while viewing I18n content in the CSV file of windows excel.

Was fine with Linux (Ubuntu) and mac.

We identified that windows excel need to be imported the data again to view the actual data. While import we will get more options to choose character set.

But this can’t be educated for each and every user, so solution we looking for is to open just by double click.

Then we identified the way of showing data by open mode and bom in windows excel with the help of aghuddleston gist. Added at reference.

Example I18n content

In Mac and Linux

Swedish : Förnamn English : First name

In Windows

Swedish : Förnamn English : First name

def user_information_report(report_file_path, user_id)
    user = User.find(user_id)
    I18n.locale = user.current_lang
    open_mode = "w+:UTF-16LE:UTF-8"
    bom = "\xEF\xBB\xBF"
    body user, open_mode, bom
  end

def headers
    headers = [
        "ID", "SDN ID",
        I18n.t('sys_first_name'), I18n.t('sys_last_name'), I18n.t('sys_dob'),
        I18n.t('sys_gender'), I18n.t('sys_email'), I18n.t('sys_address'),
        I18n.t('sys_city'), I18n.t('sys_state'), I18n.t('sys_zip'),
        I18n.t('sys_phone_number')
    ]
  end

def body tenant, open_mode, bom
    File.open(report_file_path, open_mode) do |f|
      csv_file = CSV.generate(col_sep: "\t") do |csv|
        csv << headers
        tenant.patients.find_each(batch_size: 10) do |patient|
          csv <<  [
              patient.id, patient.patientid,
              patient.first_name, patient.last_name, "#{patient.dob}",
              "#{translate_gender(patient.gender)}", patient.email, "#{patient.address_1.to_s} #{patient.address_2.to_s}",
              "#{patient.city}", "#{patient.state}",  "#{patient.zip}",
              "#{patient.phone_number}"
          ]
        end
      end
      f.write bom
      f.write(csv_file)
    end
  end

Important things to note here is open mode and bom

open_mode = "w+:UTF-16LE:UTF-8"

bom = "\xEF\xBB\xBF"

Before writing the CSV insert BOM

f.write bom

f.write(csv_file)

Windows and Mac

File can be opened directly by double clicking.

Linux (ubuntu)

While opening a file ask for the separator options -> choose “TAB” enter image description here

postgresql: INSERT INTO ... (SELECT * ...)

This notation (first seen here) looks useful too:

insert into postagem (
  resumopostagem,
  textopostagem,
  dtliberacaopostagem,
  idmediaimgpostagem,
  idcatolico,
  idminisermao,
  idtipopostagem
) select
  resumominisermao,
  textominisermao,
  diaminisermao,
  idmediaimgminisermao,
  idcatolico ,
  idminisermao,
  1
from
  minisermao    

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

How is an HTTP POST request made in node.js?

This is the simplest way I use to make request: using 'request' module.

Command to install 'request' module :

$ npm install request

Example code:

var request = require('request')

var options = {
  method: 'post',
  body: postData, // Javascript object
  json: true, // Use,If you are sending JSON data
  url: url,
  headers: {
    // Specify headers, If any
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.log('Error :', err)
    return
  }
  console.log(' Body :', body)

});

You can also use Node.js's built-in 'http' module to make request.

Assigning out/ref parameters in Moq

Moq version 4.8 (or later) has much improved support for by-ref parameters:

public interface IGobbler
{
    bool Gobble(ref int amount);
}

delegate void GobbleCallback(ref int amount);     // needed for Callback
delegate bool GobbleReturns(ref int amount);      // needed for Returns

var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny))  // match any value passed by-ref
    .Callback(new GobbleCallback((ref int amount) =>
     {
         if (amount > 0)
         {
             Console.WriteLine("Gobbling...");
             amount -= 1;
         }
     }))
    .Returns(new GobbleReturns((ref int amount) => amount > 0));

int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
    gobbleSomeMore = mock.Object.Gobble(ref a);
}

The same pattern works for out parameters.

It.Ref<T>.IsAny also works for C# 7 in parameters (since they are also by-ref).

Remove duplicates in the list using linq

Use Distinct() but keep in mind that it uses the default equality comparer to compare values, so if you want anything beyond that you need to implement your own comparer.

Please see http://msdn.microsoft.com/en-us/library/bb348436.aspx for an example.

Getting Textarea Value with jQuery

change id="#message" to id="message" on your textarea element.

and by the way, just use this:

$('#send-thoughts')

remember that you should only use ID's once and you can use classes over and over.

https://css-tricks.com/the-difference-between-id-and-class/

How to detect if CMD is running as Administrator/has elevated privileges?

Works for Win7 Enterprise and Win10 Enterprise

@if DEFINED SESSIONNAME (
    @echo.
    @echo You must right click to "Run as administrator"
    @echo Try again
    @echo.
    @pause
    @goto :EOF
)

Setting an environment variable before a command in Bash is not working for the second command in a pipe

A simple approach is to make use of ;

For example:

ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV"  deauthorize_users.yml --check

How do I check to see if my array includes an object?

This ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
   @suggested_horses<< horse
end

Should probably be this ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
   @suggested_horses<< horse
end

Resizing Images in VB.NET

Here is an article with full details on how to do this.

Private Sub btnScale_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnScale.Click
    ' Get the scale factor.
    Dim scale_factor As Single = Single.Parse(txtScale.Text)

    ' Get the source bitmap.
    Dim bm_source As New Bitmap(picSource.Image)

    ' Make a bitmap for the result.
    Dim bm_dest As New Bitmap( _
        CInt(bm_source.Width * scale_factor), _
        CInt(bm_source.Height * scale_factor))

    ' Make a Graphics object for the result Bitmap.
    Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

    ' Copy the source image into the destination bitmap.
    gr_dest.DrawImage(bm_source, 0, 0, _
        bm_dest.Width + 1, _
        bm_dest.Height + 1)

    ' Display the result.
    picDest.Image = bm_dest
End Sub

[Edit]
One more on the similar lines.

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Scroll Element into View with Selenium

A solution is:

public void javascriptclick(String element)
{
    WebElement webElement = driver.findElement(By.xpath(element));
    JavascriptExecutor js = (JavascriptExecutor) driver;

    js.executeScript("arguments[0].click();", webElement);
    System.out.println("javascriptclick" + " " + element);
}

How to check if a String contains any letter from a to z?

You can look for regular expression

Regex.IsMatch(str, @"^[a-zA-Z]+$");

Blur the edges of an image or background image with CSS

If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.

Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.

This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.

_x000D_
_x000D_
.container {_x000D_
 margin: auto;_x000D_
 width: 200px;_x000D_
 position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
 width: 100%;_x000D_
}_x000D_
_x000D_
.block {_x000D_
 width: 100%;_x000D_
 position: absolute;_x000D_
 bottom: 0px;_x000D_
 top: 0px;_x000D_
 box-shadow: inset 0px 0px 10px 20px white;_x000D_
}
_x000D_
<div class="container">_x000D_
 <img src="http://lorempixel.com/200/200/city">_x000D_
 <div class="block"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AngularJS : Custom filters and ng-repeat

If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

How to POST a FORM from HTML to ASPX page

Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running Fiddler2, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)