Programs & Examples On #Zend controller plugin

How to do something before on submit?

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

Dynamic WHERE clause in LINQ

I came up with a solution that even I can understand... by using the 'Contains' method you can chain as many WHERE's as you like. If the WHERE is an empty string, it's ignored (or evaluated as a select all). Here is my example of joining 2 tables in LINQ, applying multiple where clauses and populating a model class to be returned to the view. (this is a select all).

public ActionResult Index()
    {
        string AssetGroupCode = "";
        string StatusCode = "";
        string SearchString = "";

        var mdl = from a in _db.Assets
                  join t in _db.Tags on a.ASSETID equals t.ASSETID
                  where a.ASSETGROUPCODE.Contains(AssetGroupCode)
                  && a.STATUSCODE.Contains(StatusCode)
                  && (
                  a.PO.Contains(SearchString)
                  || a.MODEL.Contains(SearchString)
                  || a.USERNAME.Contains(SearchString)
                  || a.LOCATION.Contains(SearchString)
                  || t.TAGNUMBER.Contains(SearchString)
                  || t.SERIALNUMBER.Contains(SearchString)
                  )
                  select new AssetListView
                  {
                      AssetId = a.ASSETID,
                      TagId = t.TAGID,
                      PO = a.PO,
                      Model = a.MODEL,
                      UserName = a.USERNAME,
                      Location = a.LOCATION,
                      Tag = t.TAGNUMBER,
                      SerialNum = t.SERIALNUMBER
                  };


        return View(mdl);
    }

Datetime BETWEEN statement not working in SQL Server

Does the second query return any results from the 17th, or just from the 18th?

The first query will only return results from the 17th, or midnight on the 18th.

Try this instead

select * 
from LOGS 
where check_in >= CONVERT(datetime,'2013-10-17') 
and check_in< CONVERT(datetime,'2013-10-19')

CSS: Position text in the middle of the page

Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.

HTML:

<h1>Hello world!</h1>

Javascript (jQuery):

$(document).ready(function(){
  $('h1').css({ 'width':'100%', 'text-align':'center' });
  var h1 = $('h1').height();
  var h = h1/2;
  var w1 = $(window).height();
  var w = w1/2;
  var m = w - h
  $('h1').css("margin-top",m + "px")
});

This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top of the h1. The beauty of this method is that it works on multiple-line h1s.

EDIT: I modified it so that it centered it every time the window is resized.

Count characters in textarea

A more generic version so you can use the function for more than one field.

<script src="../site/jquery/jquery.min.js" ></script>
<script type="text/javascript">

function countChar(inobj, maxl, outobj) {
    var len = inobj.value.length;
    var msg = ' chr left';
    if (len >= maxl) {
        inobj.value = inobj.value.substring(0, maxl);
        $(outobj).text(0 + msg);
    } else {
        $(outobj).text(maxl - len + msg);
    }
}


$(document).ready(function(){

    //set up summary field character count
    countChar($('#summary').get(0),500, '#summarychrs'); //show inital value on page load
    $('#summary').keyup(function() {
        countChar(this, 500, '#summarychrs'); //set up on keyup event function
    });

});
</script>

<textarea name="summary" id="summary" cols="60" rows="3" ><?php echo $summary ?></textarea> 
<span id="summarychrs">0</span>

Disable validation of HTML5 form elements

Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.

window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
    if(!window.submittingForm){
        window.submittingForm = true;
        $(e.target.form).submit();
        setTimeout(function(){window.submittingForm = false;}, 100);
    }
    e.preventDefault();
    return false;
});

PHP: maximum execution time when importing .SQL data file

  1. Never change original config.default.php file.
  2. Changing general executing time in php.ini has no effect on phpmyadmin scripts.
  3. Use a new config.inc.php or the config.sample.inc.php provided in the /phpMyAdmin folder instead.
  4. You can set $cfg[‘ExecTimeLimit’] = 0; means endless execution in the config.inc.php as recommended above. Be aware this is not a "normal" ini file. Its a php script, so you need a open <?php at the beginning of that file.
  5. But most important: Do not use this procedure at all! phpmyadmin is okay for small database but not for huge databases with several MB or GB.

You have other tools on a server to handle the import.

a) If you have a server admin system like Plesk, use there database import tool.

b) use ssh commands to make database dump or to write databases directly in mysql via ssh. Commands below.

Create a database dump:

mysqldump DBname --add-drop-table -h DBhostname -u DBusername -pPASSWORD > databasefile.sql

Write a database to mysql:

mysql -h rdbms -u DBusername -pPASSWORD DBname < databasefile.sql

How do I install PIL/Pillow for Python 3.6?

For python version 2.x you can simply use

  • pip install pillow

But for python version 3.X you need to specify

  • (sudo) pip3 install pillow

when you enter pip in bash hit tab and you will see what options you have

How do I set up NSZombieEnabled in Xcode 4?

In Xcode 4.x press

??R

(or click Menubar > Product > Scheme > Edit Scheme)

select the "Diagnostics" tab and click "Enable Zombie Objects":

Click "Enable Zombie Objects"

This turns released objects into NSZombie instances that print console warnings when used again. This is a debugging aid that increases memory use (no object is really released) but improves error reporting.

A typical case is when you over-release an object and you don't know which one:

  • With zombies: -[UITableView release]: message sent to deallocated instance
  • Without zombies: EXC_BAD_ACCESS

This Xcode setting is ignored when you archive the application for App Store submission. You don't need to touch anything before releasing your application.

Pressing ??R is the same as selecting Product > Run while keeping the Alt key pressed.
Clicking the "Enable Zombie Objects" checkbox is the same as manually adding "NSZombieEnabled = YES" in the section "Environment Variables" of the tab Arguments.

How to configure log4j.properties for SpringJUnit4ClassRunner?

I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:

  1. Open run dialog (click the little arrow next to the play button and go to run configurations)
  2. Go to the "classpath" tab
  3. Select the "User Entries" and click the "Advanced" button on the right side.
  4. Now select the "Add External folder" radio button.
  5. Select the resources folder

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

The linker takes some environment variables into account. one is LD_PRELOAD

from man 8 ld-linux:

LD_PRELOAD
          A whitespace-separated list of additional,  user-specified,  ELF
          shared  libraries  to  be loaded before all others.  This can be
          used  to  selectively  override  functions   in   other   shared
          libraries.   For  setuid/setgid  ELF binaries, only libraries in
          the standard search directories that are  also  setgid  will  be
          loaded.

Therefore the linker will try to load libraries listed in the LD_PRELOAD variable before others are loaded.

What could be the case that inside the variable is listed a library that can't be pre-loaded. look inside your .bashrc or .bash_profile environment where the LD_PRELOAD is set and remove that library from the variable.

AngularJS: how to implement a simple file upload with multipart form?

I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!

<input type="file" multiple ng-simple-upload web-api-url="/api/post"
       callback-fn="myCallback" />

ng-simple-upload more on Github with an example using Web API.

How do you print in a Go test using the "testing" package?

The *_test.go file is a Go source like the others, you can initialize a new logger every time if you need to dump complex data structure, here an example:

// initZapLog is delegated to initialize a new 'log manager'
func initZapLog() *zap.Logger {
    config := zap.NewDevelopmentConfig()
    config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
    config.EncoderConfig.TimeKey = "timestamp"
    config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
    logger, _ := config.Build()
    return logger
}

Then, every time, in every test:

func TestCreateDB(t *testing.T) {
    loggerMgr := initZapLog()
    // Make logger avaible everywhere
    zap.ReplaceGlobals(loggerMgr)
    defer loggerMgr.Sync() // flushes buffer, if any
    logger := loggerMgr.Sugar()
    logger.Debug("START")
    conf := initConf()
    /* Your test here
    if false {
        t.Fail()
    }*/
}

How does a PreparedStatement avoid or prevent SQL injection?

In Prepared Statements the user is forced to enter data as parameters . If user enters some vulnerable statements like DROP TABLE or SELECT * FROM USERS then data won't be affected as these would be considered as parameters of the SQL statement

Does C# have extension properties?

Update (thanks to @chaost for pointing this update out):

Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"

Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/


I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.

Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.

So instead of doing this...

public static class IntExtensions
{
   public static bool Even(this int value)
   {
        return value % 2 == 0;
   }
}

We'll be finally able to do it like so...

public extension IntExtension extends int
{
    public bool Even => this % 2 == 0;
}

Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/

Checking for duplicate strings in JavaScript array

Using ES6 features

function checkIfDuplicateExists(w){
    return new Set(w).size !== w.length 
}

console.log(
    checkIfDuplicateExists(["a", "b", "c", "a"])
// true
);

console.log(
    checkIfDuplicateExists(["a", "b", "c"]))
//false

Sibling package imports

You don't need and shouldn't hack sys.path unless it is necessary and in this case it is not. Use:

import api.api_key # in tests, examples

Run from the project directory: python -m tests.test_one.

You should probably move tests (if they are api's unittests) inside api and run python -m api.test to run all tests (assuming there is __main__.py) or python -m api.test.test_one to run test_one instead.

You could also remove __init__.py from examples (it is not a Python package) and run the examples in a virtualenv where api is installed e.g., pip install -e . in a virtualenv would install inplace api package if you have proper setup.py.

Changing the JFrame title

newTitle is a local variable where you create the fields. So when that functions ends, the variable newTitle, does not exist anymore. (The JTextField that was referenced by newTitle does still exist however.)

Thus, increase the scope of the variable, so that you can access it another method.

public SomeFrame extends JFrame {
   JTextField myTitle;//can be used anywhere in this class

   creationOfTheFields()
   {
   //other code
      myTitle = new JTextField("spam");  
      myTitle.setBounds(80, 40, 225, 20);
      options.add(myTitle);
   //blabla other code
   }

   private void New_Name()  
   {  
      this.setTitle(myTitle.getText());  
   } 
}

How can I replace newline or \r\n with <br/>?

There is already the nl2br() function that inserts <br> tags before new line characters:

Example (codepad):

<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";

echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

But if it is still not working make sure the text $desciption is double-quoted.

That's because single quotes do not 'expand' escape sequences such as \n comparing to double quoted strings. Quote from PHP documentation:

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

Can I stop 100% Width Text Boxes from extending beyond their containers?

Just came across this problem myself, and the only solution I could find that worked in all my test browsers (IE6, IE7, Firefox) was the following:

  1. Wrap the input field in two separate DIVs
  2. Set the outer DIV to width 100%, this prevents our container from overflowing the document
  3. Put padding in the inner DIV of the exact amount to compensate for the horizontal overflow of the input.
  4. Set custom padding on the input so it overflows by the same amount as I allowed for in the inner DIV

The code:

<div style="width: 100%">
    <div style="padding-right: 6px;">
        <input type="text" style="width: 100%; padding: 2px; margin: 0;
                                  border : solid 1px #999" />
    </div>
</div>

Here, the total horizontal overflow for the input element is 6px - 2x(padding + border) - so we set a padding-right for the inner DIV of 6px.

How to set image for bar button with swift?

I have achieved that programatically with this code:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        //set image for button
        button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
        //add function for button
        button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
        //set frame
        button.frame = CGRectMake(0, 0, 53, 31)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        println("Share to fb")
    }
}

And result will be:

enter image description here

Same way you can set button for left side too this way:

self.navigationItem.leftBarButtonItem = barButton

And result will be:

enter image description here

And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:

func backButtonPressed(sender:UIButton) {
    navigationController?.popViewControllerAnimated(true)
}

For swift 3.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton.init(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
        //add function for button
        button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        print("Share to fb")
    }
}

For swift 4.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: .normal)
        //add function for button
        button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    @objc func fbButtonPressed() {

        print("Share to fb")
    }
}

download and install visual studio 2008

For Microsoft Visual C++ 2008, not the general Visual Studio (go.microsoft.com/?linkid=7729279?)

Google Visual Studio 2008 Express instead of just Visual Studio 2008. Click to the first link that appears which is a download link from Microsoft mentioned above.

How to check if an option is selected?

If you only want to check if an option is selected, then you do not need to iterate through all options. Just do

if($('#mySelectBox').val()){
    // do something
} else {
    // do something else
}

Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null

Add a pipe separator after items in an unordered list unless that item is the last on a line

This is possible with flex-box

The keys to this technique:

  • A container element set to overflow: hidden.
  • Set justify-content: space-between on the ul (which is a flex-box) to force its flex-items to stretch to the left and right edges.
  • Set margin-left: -1px on the ul to cause its left edge to overflow the container.
  • Set border-left: 1px on the li flex-items.

The container acts as a mask hiding the borders of any flex-items touching its left edge.

_x000D_
_x000D_
.flex-list {
    position: relative;
    margin: 1em;
    overflow: hidden;
}
.flex-list ul {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-left: -1px;
}
.flex-list li {
    flex-grow: 1;
    flex-basis: auto;
    margin: .25em 0;
    padding: 0 1em;
    text-align: center;
    border-left: 1px solid #ccc;
    background-color: #fff;
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>
<div class="flex-list">
    <ul>
        <li>Dogs</li>
        <li>Cats</li>
        <li>Lions</li>
        <li>Tigers</li>
        <li>Zebras</li>
        <li>Giraffes</li>
        <li>Bears</li>
        <li>Hippopotamuses</li>
        <li>Antelopes</li>
        <li>Unicorns</li>
        <li>Seagulls</li>
    </ul>
</div>
_x000D_
_x000D_
_x000D_

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
{
    public string Name, Email;
    
    public Person(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
class Data
{
    public string Mail, SlackId;
    
    public Data(string mail, string slackId)
    {
        Mail = mail;
        SlackId = slackId;
    }
}

Now, let's Prepare data to work with:

var people = new Person[]
    {
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    };
    
    var records = new Data[]
    {
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")
    };

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});
    Console.WriteLine(query);

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
    }

Let's also output the result for GroupJoin:

Console.WriteLine(
    
        people.GroupJoin(
            records,
            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
            }
        ));

You will notice that the GroupJoin will put all SlackIds in a single group.

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

There is no difference until you compile to same target architecture. I suppose you are compiling for 32 bit architecture in both cases.

It's worth mentioning that OutOfMemoryException can also be raised if you get 2GB of memory allocated by a single collection in CLR (say List<T>) on both architectures 32 and 64 bit.

To be able to benefit from memory goodness on 64 bit architecture, you have to compile your code targeting 64 bit architecture. After that, naturally, your binary will run only on 64 bit, but will benefit from possibility having more space available in RAM.

Are there any naming convention guidelines for REST APIs?

I have a list of guidelines at http://soaprobe.blogspot.co.uk/2012/10/soa-rest-service-naming-guideline.html which we have used in prod. Guidelines are always debatable... I think consistency is sometimes more important than getting things perfect (if there is such a thing).

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

How can we draw a vertical line in the webpage?

There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.

Try this:

CSS

.vr {
    width:10px;
    background-color:#000;
    position:absolute;
    top:0;
    bottom:0;
    left:150px;
}

HTML

<div class="vr">&nbsp;</div>

Demo

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Parsing GET request parameters in a URL that contains another URL

You may have to use urlencode on the string 'http://google.com/?var=234&key=234'

Reverse a comparator in Java 8

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

In result you get a easy reusable Class File, testable unit step and clear javadoc.

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}

How do you change video src using jQuery?

JQUERY

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
  var videoID = 'videoclip';_x000D_
  var sourceID = 'mp4video';_x000D_
  var newmp4 = 'media/video2.mp4';_x000D_
  var newposter = 'media/video-poster2.jpg';_x000D_
 _x000D_
  $('#videolink1').click(function(event) {_x000D_
    $('#'+videoID).get(0).pause();_x000D_
    $('#'+sourceID).attr('src', newmp4);_x000D_
    $('#'+videoID).get(0).load();_x000D_
     //$('#'+videoID).attr('poster', newposter); //Change video poster_x000D_
    $('#'+videoID).get(0).play();_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111 check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null

What is the proper declaration of main in C++?

The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).

The name main is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.

You can declare a function named main as a member function or in a namespace, but such a function would not be the main function that designates where the program starts.

The main function cannot be declared as static or inline. It also cannot be overloaded; there can be only one function named main in the global namespace.

The main function cannot be used in your program: you are not allowed to call the main function from anywhere in your code, nor are you allowed to take its address.

The return type of main must be int. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main with a return type of void; this is probably the most frequently violated rule concerning the main function).

There are two declarations of main that must be allowed:

int main()               // (1)
int main(int, char*[])   // (2)

In (1), there are no parameters.

In (2), there are two parameters and they are conventionally named argc and argv, respectively. argv is a pointer to an array of C strings representing the arguments to the program. argc is the number of arguments in the argv array.

Usually, argv[0] contains the name of the program, but this is not always the case. argv[argc] is guaranteed to be a null pointer.

Note that since an array type argument (like char*[]) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:

int main(int argc, char* argv[])
int main(int argc, char** argv)

Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.

main() is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return statement in main(): if you let main() return without an explicit return statement, it's the same as if you had written return 0;. The following two main() functions have the same behavior:

int main() { }
int main() { return 0; }

There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined in <cstdlib> that can also be returned from main() to indicate success and failure, respectively.

The value returned by main() is passed to the exit() function, which terminates the program.

Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main() function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

Python truncate a long string

info = data[:75] + ('..' if len(data) > 75 else '')

Deactivate or remove the scrollbar on HTML

put this code in your html header:

<style type="text/css">
html {
        overflow: auto;
}
</style>

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

Resolve issue Immediate, It's related to internal security

We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.

As investigate in server log found

[error] (13)Permission denied: proxy: AJP: attempt to connect to
   10.x.x.x:8069 (virtualhost.virtualdomain.com) failed

Audit log found similar port issue

type=AVC msg=audit(1265039669.305:14): avc:  denied  { name_connect } for  pid=4343 comm="httpd" dest=8069 
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket

Due to internal default security of linux, this cause, now to fix (temporary)

 /usr/sbin/setsebool httpd_can_network_connect 1

Resolve Permanent Issue

/usr/sbin/setsebool -P httpd_can_network_connect 1

How to check if array element exists or not in javascript?

Someone please correct me if i'm wrong, but AFAIK the following is true:

  1. Arrays are really just Objects under the hood of JS
  2. Thus, they have the prototype method hasOwnProperty "inherited" from Object
  3. in my testing, hasOwnProperty can check if anything exists at an array index.

So, as long as the above is true, you can simply:

const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

usage:

arrayHasIndex([1,2,3,4],4); outputs: false

arrayHasIndex([1,2,3,4],2); outputs: true

Creating folders inside a GitHub repository without using Git

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

For example, if I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub blog):

Enter image description here

Oracle : how to subtract two dates and get minutes of the result

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

Parsing date string in Go

I will suggest using time.RFC3339 constant from time package. You can check other constants from time package. https://golang.org/pkg/time/#pkg-constants

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Time parsing");
    dateString := "2014-11-12T11:45:26.371Z"
    time1, err := time.Parse(time.RFC3339,dateString);
    if err!=nil {
    fmt.Println("Error while parsing date :", err);
    }
    fmt.Println(time1); 
}

Purge or recreate a Ruby on Rails database

I use the following one liner in Terminal.

$ rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare

I put this as a shell alias and named it remigrate

By now, you can easily "chain" Rails tasks:

$ rake db:drop db:create db:migrate db:schema:dump db:test:prepare # db:test:prepare no longer available since Rails 4.1.0.rc1+

Order by multiple columns with Doctrine

In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.

For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.

To add multiple order by's you need to use 'add' function. And it will be like this.

->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.

More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api

Hope this helps. Cheers!

Module 'tensorflow' has no attribute 'contrib'

If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Generally Server JDK version will be lower than the deployed application (built with higher jdk version)

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

I had this same problem, because my line of code was:

txtTotalInvoice.setText(var1.divide(var2).doubleValue() + "");

I change to this, reading previous Answer, because I was not writing decimal precision:

txtTotalInvoice.setText(var1.divide(var2,4, RoundingMode.HALF_UP).doubleValue() + "");

4 is Decimal Precison

AND RoundingMode are Enum constants, you could choose any of this UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP

In this Case HALF_UP, will have this result:

2.4 = 2   
2.5 = 3   
2.7 = 3

You can check the RoundingMode information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/

Service Reference Error: Failed to generate code for the service reference

I get the same error in Silverlight 5 (VS2012)

You can also remove the references to:

  • System.ServiceModel.DomainServices.Client
  • System.ServiceModel.DomainServices.Client.Web

After you've updated the service references, be sure to add them back in.

How to calculate the angle between a line and the horizontal axis?

deltaY = Math.Abs(P2.y - P1.y);
deltaX = Math.Abs(P2.x - P1.x);

angleInDegrees = Math.atan2(deltaY, deltaX) * 180 / PI

if(p2.y > p1.y) // Second point is lower than first, angle goes down (180-360)
{
  if(p2.x < p1.x)//Second point is to the left of first (180-270)
    angleInDegrees += 180;
  else //(270-360)
    angleInDegrees += 270;
}
else if (p2.x < p1.x) //Second point is top left of first (90-180)
  angleInDegrees += 90;

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

In my case, one of the exported child module was not returning a proper react component.

const Component = <div> Content </div>;

instead of

const Component = () => <div>Content</div>;

The error shown was for the parent, hence couldn't figure out.

True and False for && logic and || Logic table

You probably mean a truth table for the boolean operators, which displays the result of the usual boolean operations (&&, ||). This table is not language-specific, but can be found e.g. here.

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

What are the differences between char literals '\n' and '\r' in Java?

It depends on which Platform you work. To get the correct result use -

System.getProperty("line.separator")

`&mdash;` or `&#8212;` is there any difference in HTML output?

They are exactly the same character. See: http://en.wikipedia.org/wiki/Dash

Barring browser bugs they will display the same in all cases, so the only difference would be concerning code readability, which would point to &mdash;.

Or, if you are using UTF-8 as a charset in your HTML document, you could enter the character directly. That would also display exactly the same.

Any reason to prefer getClass() over instanceof when generating .equals()?

Angelika Langers Secrets of equals gets into that with a long and detailed discussion for a few common and well-known examples, including by Josh Bloch and Barbara Liskov, discovering a couple of problems in most of them. She also gets into the instanceof vs getClass. Some quote from it

Conclusions

Having dissected the four arbitrarily chosen examples of implementations of equals() , what do we conclude?

First of all: there are two substantially different ways of performing the check for type match in an implementation of equals() . A class can allow mixed-type comparison between super- and subclass objects by means of the instanceof operator, or a class can treat objects of different type as non-equal by means of the getClass() test. The examples above illustrated nicely that implementations of equals() using getClass() are generally more robust than those implementations using instanceof .

The instanceof test is correct only for final classes or if at least method equals() is final in a superclass. The latter essentially implies that no subclass must extend the superclass's state, but can only add functionality or fields that are irrelevant for the object's state and behavior, such as transient or static fields.

Implementations using the getClass() test on the other hand always comply to the equals() contract; they are correct and robust. They are, however, semantically very different from implementations that use the instanceof test. Implementations using getClass() do not allow comparison of sub- with superclass objects, not even when the subclass does not add any fields and would not even want to override equals() . Such a "trivial" class extension would for instance be the addition of a debug-print method in a subclass defined for exactly this "trivial" purpose. If the superclass prohibits mixed-type comparison via the getClass() check, then the trivial extension would not be comparable to its superclass. Whether or not this is a problem fully depends on the semantics of the class and the purpose of the extension.

Dynamically add item to jQuery Select2 control that uses AJAX

This is a lot easier to do starting in select2 v4. You can create a new Option, and append it to the select element directly. See my codepen or the example below:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $("#state").select2({_x000D_
      tags: true_x000D_
    });_x000D_
      _x000D_
    $("#btn-add-state").on("click", function(){_x000D_
      var newStateVal = $("#new-state").val();_x000D_
      // Set the value, creating a new option if necessary_x000D_
      if ($("#state").find("option[value=" + newStateVal + "]").length) {_x000D_
        $("#state").val(newStateVal).trigger("change");_x000D_
      } else { _x000D_
        // Create the DOM option that is pre-selected by default_x000D_
        var newState = new Option(newStateVal, newStateVal, true, true);_x000D_
        // Append it to the select_x000D_
        $("#state").append(newState).trigger('change');_x000D_
      } _x000D_
    });  _x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select id="state" class="js-example-basic-single" type="text" style="width:90%">_x000D_
  <option value="AL">Alabama</option>_x000D_
  <option value="WY">Wyoming</option>_x000D_
</select>_x000D_
<br>_x000D_
<br>_x000D_
<input id="new-state" type="text" />_x000D_
<button type="button" id="btn-add-state">Set state value</button>
_x000D_
_x000D_
_x000D_

Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.

  public static String toCamelCase(String value) {
    StringBuilder sb = new StringBuilder();

    final char delimChar = '_';
    boolean lower = false;
    for (int charInd = 0; charInd < value.length(); ++charInd) {
      final char valueChar = value.charAt(charInd);
      if (valueChar == delimChar) {
        lower = false;
      } else if (lower) {
        sb.append(Character.toLowerCase(valueChar));
      } else {
        sb.append(Character.toUpperCase(valueChar));
        lower = true;
      }
    }

    return sb.toString();
  }

A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.

Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.

Using Node.js require vs. ES6 import/export

The most important thing to know is that ES6 modules are, indeed, an official standard, while CommonJS (Node.js) modules are not.

In 2019, ES6 modules are supported by 84% of browsers. While Node.js puts them behind an --experimental-modules flag, there is also a convenient node package called esm, which makes the integration smooth.

Another issue you're likely to run into between these module systems is code location. Node.js assumes source is kept in a node_modules directory, while most ES6 modules are deployed in a flat directory structure. These are not easy to reconcile, but it can be done by hacking your package.json file with pre and post installation scripts. Here is an example isomorphic module and an article explaining how it works.

Update multiple rows using select statement

If you have ids in both tables, the following works:

update table2
    set value = (select value from table1 where table1.id = table2.id)

Perhaps a better approach is a join:

update table2
    set value = table1.value
    from table1
    where table1.id = table2.id

Note that this syntax works in SQL Server but may be different in other databases.

How to fix Error: listen EADDRINUSE while using nodejs?

Error: listen EADDRINUSE means the port which you want to assign/bind to your application server is already in use. You can either assign another port to your application.

Or if you want to assign the same port to the app. Then kill the application that is running at your desired port.

For a node application what you can try is, find the process id for the node app by :

ps -aux | grep node

After getting the process id, do

kill process_id

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

I'd create a cte and do an inner join. It's not efficient but it's convenient

with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER() 
OVER (PARTITION BY DATE, STATUS,  TITLE ORDER BY QUANTITY ASC) AS Row_Num
 FROM TABLE)

select *

from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table 
group by date, status, title) t2  
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title

Unexpected character encountered while parsing value

I had the same problem with webapi in ASP.NET core, in my case it was because my application needs authentication, then it assigns the annotation [AllowAnonymous] and it worked.

[AllowAnonymous]
public async Task <IList <IServic >> GetServices () {
        
}

Intercept and override HTTP requests from WebView

As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is

@Override public void onLoadResource(WebView view, String url)

This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...

Javascript - sort array based on another array

Use intersection of two arrays.

Ex:

var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort) 

=> ['a', 'b', 'e']

if 'z and 's' are out of range of first array, append it at the end of result

How to change users in TortoiseSVN

When you use Integrated Windows Authentication (i.e., Active Directory Single Sign-On), you authenticate to AD resources automatically with your AD credentials. You've are already signed in to AD and these credentials are reused automatically. Therefore if your server is IWA-enabled (e.g., VisualSVN Server), the server does not ask you to enter username and password, passing --username and --password does not work, and the SVN client does not cache your credentials on disk, too.

When you want to change the user account that's used to contact the server, you need use the Windows Credential Manager on client side. This is also helpful when your computer is not domain joined and you need to store your AD credentials to access your domain resources.

Follow these steps to save the user's domain credentials to Windows Credential Manager on the user's computer:

  1. Start Control Panel | Credential Manager on the client computer.
  2. Click Add a Windows Credential.
  3. As Internet or network address enter the FQDN of the server machine (e.g., svn.example.com).
  4. As Username enter your domain account's username in the DOMAIN\Username format.
  5. Complete the password field and click OK.

Now when you will contact https://svn.example.com/svn/MyRepo or a similar URL, the client or web browser will use the credentials saved in the Credential Manager to authenticate to the server.

enter image description here

How can I nullify css property?

An initial keyword is being added in CSS3 to allow authors to explicitly specify this initial value.

How to pass url arguments (query string) to a HTTP request on Angular?

The HttpClient methods allow you to set the params in it's options.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

import {HttpClientModule} from '@angular/common/http';

@NgModule({
  imports: [ BrowserModule, HttpClientModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

After that you can inject the HttpClient and use it to do the request.

import {HttpClient} from '@angular/common/http'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(private httpClient: HttpClient) {
    this.httpClient.get('/url', {
      params: {
        appid: 'id1234',
        cnt: '5'
      },
      observe: 'response'
    })
    .toPromise()
    .then(response => {
      console.log(response);
    })
    .catch(console.log);
  }
}

For angular versions prior to version 4 you can do the same using the Http service.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The search field of that object can be used to set a string or a URLSearchParams object.

An example:

 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('appid', StaticSettings.API_KEY);
 params.set('cnt', days.toString());

 //Http request-
 return this.http.get(StaticSettings.BASE_URL, {
   search: params
 }).subscribe(
   (response) => this.onGetForecastResult(response.json()), 
   (error) => this.onGetForecastError(error.json()), 
   () => this.onGetForecastComplete()
 );

The documentation for the Http class has more details. It can be found here and an working example here.

Algorithm: efficient way to remove duplicate integers from an array

1. Using O(1) extra space, in O(n log n) time

This is possible, for instance:

  • first do an in-place O(n log n) sort
  • then walk through the list once, writing the first instance of every back to the beginning of the list

I believe ejel's partner is correct that the best way to do this would be an in-place merge sort with a simplified merge step, and that that is probably the intent of the question, if you were eg. writing a new library function to do this as efficiently as possible with no ability to improve the inputs, and there would be cases it would be useful to do so without a hash-table, depending on the sorts of inputs. But I haven't actually checked this.

2. Using O(lots) extra space, in O(n) time

  • declare a zero'd array big enough to hold all integers
  • walk through the array once
  • set the corresponding array element to 1 for each integer.
  • If it was already 1, skip that integer.

This only works if several questionable assumptions hold:

  • it's possible to zero memory cheaply, or the size of the ints are small compared to the number of them
  • you're happy to ask your OS for 256^sizepof(int) memory
  • and it will cache it for you really really efficiently if it's gigantic

It's a bad answer, but if you have LOTS of input elements, but they're all 8-bit integers (or maybe even 16-bit integers) it could be the best way.

3. O(little)-ish extra space, O(n)-ish time

As #2, but use a hash table.

4. The clear way

If the number of elements is small, writing an appropriate algorithm is not useful if other code is quicker to write and quicker to read.

Eg. Walk through the array for each unique elements (ie. the first element, the second element (duplicates of the first having been removed) etc) removing all identical elements. O(1) extra space, O(n^2) time.

Eg. Use library functions which do this. efficiency depends which you have easily available.

Where does SVN client store user authentication data?

Read SVNBook | Client Credentials.

With modern SVN you can just run svn auth to display the list of cached credentials. Don't forget to make sure that you run up-to-date SVN client version because svn auth was introduced in version 1.9. The last line will specify the path to credential store which by default is %APPDATA%\Subversion\auth on Windows and ~/.subversion/auth/ on Unix-like systems.

PS C:\Users\MyUser> svn auth
------------------------------------------------------------------------
Credential kind: svn.simple
Authentication realm: <https://svn.example.local:443> VisualSVN Server
Password cache: wincrypt
Password: [not shown]
Username: user

Credentials cache in 'C:\Users\MyUser\AppData\Roaming\Subversion' contains 5 credentials

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

For me (also XAMPP on Windows 7), this is what worked:

<Directory "C:\projects\myfolder\htdocs">`
   AllowOverride All
   Require all granted
   Options Indexes FollowSymLinks
</Directory>` 

It is this line that would cause the 403:

Order allow,deny

Multiple "order by" in LINQ

use the following line on your DataContext to log the SQL activity on the DataContext to the console - then you can see exactly what your linq statements are requesting from the database:

_db.Log = Console.Out

The following LINQ statements:

var movies = from row in _db.Movies 
             orderby row.CategoryID, row.Name
             select row;

AND

var movies = _db.Movies.OrderBy(m => m.CategoryID).ThenBy(m => m.Name);

produce the following SQL:

SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].CategoryID, [t0].[Name]

Whereas, repeating an OrderBy in Linq, appears to reverse the resulting SQL output:

var movies = from row in _db.Movies 
             orderby row.CategoryID
             orderby row.Name
             select row;

AND

var movies = _db.Movies.OrderBy(m => m.CategoryID).OrderBy(m => m.Name);

produce the following SQL (Name and CategoryId are switched):

SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].[Name], [t0].CategoryID

How to call a function in shell Scripting?

You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:

#!/bin/sh

Please remember to tag future questions with the shell type, as this will help the community answer your question.

You need to define your functions before you call them. Using ():

process_install()
{
    echo "Performing process_install() commands, using arguments [${*}]..."
}

process_exit()
{
    echo "Performing process_exit() commands, using arguments [${*}]..."
}

Then you can call your functions, just as if you were calling any command:

if [ "$choice" = "true" ]
then
    process_install foo bar
elif [ "$choice" = "false" ]
then
    process_exit baz qux

You may also wish to check for invalid choices at this juncture...

else
    echo "Invalid choice [${choice}]..."
fi

See it run with three different values of ${choice}.

Good luck!

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

Centering a button vertically in table cell, using Twitter Bootstrap

To fix this, i put this class on the webpage

<style>                        
    td.vcenter {
        vertical-align: middle !important;
        text-align: center !important;
    }
</style>

and this in my TemplateField

<asp:TemplateField ItemStyle-CssClass="vcenter">

as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.

Hope it helps

How to highlight text using javascript

Fast forward to 2019, Web API now has natively support for highlighting texts:

const selection = document.getSelection();
selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);

And you are good to go! anchorNode is the selection starting node, focusNode is the selection ending node. And, if they are text nodes, offset is the index of the starting and ending character in the respective nodes. Here is the documentation

They even have a live demo

JQuery html() vs. innerHTML

Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)

if (/(msie|trident)/i.test(navigator.userAgent)) {
 var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
 var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
 Object.defineProperty(HTMLElement.prototype, "innerHTML", {
  get: function () {return innerhtml_get.call (this)},
  set: function(new_html) {
   var childNodes = this.childNodes
   for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
    this.removeChild (childNodes[0])
   }
   innerhtml_set.call (this, new_html)
  }
 })
}

var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)

document.body.innerHTML = ""
console.log (mydiv.innerHTML)

http://jsfiddle.net/DLLbc/9/

How to write and read java serialized objects into a file

Why not serialize the whole list at once?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);

Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.

In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.

I want to declare an empty array in java and then I want do update it but the code is not working

You need to give the array a size:

public static void main(String args[])
{
    int array[] = new int[4];
    int number = 5, i = 0,j = 0;
    while (i<4){
        array[i]=number;
        i=i+1;
    }
    while (j<4){
        System.out.println(array[j]);
        j++;
    }
}

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

What is a "callable"?

__call__ makes any object be callable as a function.

This example will output 8:

class Adder(object):
  def __init__(self, val):
    self.val = val

  def __call__(self, val):
    return self.val + val

func = Adder(5)
print func(3)

C++ Object Instantiation

There is an additional reason, which no one else has mentioned, why you might choose to create your object dynamically. Dynamic, heap based objects allow you to make use of polymorphism.

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

Is it possible to set the stacking order of pseudo-elements below their parent element?

There are two issues are at play here:

  1. The CSS 2.1 specification states that "The :beforeand :after pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element." Given the way z-indexes are implemented in most browsers, it's pretty difficult (read, I don't know of a way) to move content lower than the z-index of their parent element in the DOM that works in all browsers.

  2. Number 1 above does not necessarily mean it's impossible, but the second impediment to it is actually worse: Ultimately it's a matter of browser support. Firefox didn't support positioning of generated content at all until FF3.6. Who knows about browsers like IE. So even if you can find a hack to make it work in one browser, it's very likely it will only work in that browser.

The only thing I can think of that's going to work across browsers is to use javascript to insert the element rather than CSS. I know that's not a great solution, but the :before and :after pseudo-selectors just really don't look like they're gonna cut it here.

GoogleMaps API KEY for testing

Updated Answer

As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.

This answer is no longer valid

As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.

Android ADB commands to get the device properties

You should use adb shell getprop command and grep specific info about your current device, For additional information you can read documentation: Android Debug Bridge documentation

I added some examples below:

  1. language - adb shell getprop | grep language

    [persist.sys.language]: [en]

    [ro.product.locale.language]: [en]

  2. boot complete ( device ready after reset) - adb shell getprop | grep boot_completed

    [sys.boot_completed]: [1]

  3. device model - adb shell getprop | grep model

    [ro.product.model]: [Nexus 4]

  4. sdk version - adb shell getprop | grep sdk

    [ro.build.version.sdk]: [22]

  5. time zone - adb shell getprop | grep timezone

    [persist.sys.timezone]: [Asia/China]

  6. serial number - adb shell getprop | grep serialno

    [ro.boot.serialno]: [1234567]

Installing a dependency with Bower from URL and specify version

Here's a handy short-hand way to install a specific tag or commit from GitHub via bower.json.

{
  "dependencies": {
    "your-library-name": "<GITHUB-USERNAME>/<REPOSITORY-NAME>#<TAG-OR-COMMIT>"
  }
}

For example:

{
  "dependencies": {
    "custom-jquery": "jquery/jquery#2.0.3"
  }
}

How to copy sheets to another workbook using vba?

    Workbooks.Open Filename:="Path(Ex: C:\Reports\ClientWiseReport.xls)"ReadOnly:=True


    For Each Sheet In ActiveWorkbook.Sheets

        Sheet.Copy After:=ThisWorkbook.Sheets(1)

    Next Sheet

How to handle Pop-up in Selenium WebDriver using Java

You can use the below code inside your code when you get any web browser pop-up alert message box.

// Accepts (Click on OK) Chrome Alert Browser for RESET button.

Alert alertOK = driver.switchTo().alert();
alertOK.accept();



//Rejects (Click on Cancel) Chrome Browser Alert for RESET button.

Alert alertCancel = driver.switchTo().alert();
alertCancel.dismiss();

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

SET I=1
DO
 PRINT I
 SET I=I+1
WHILE I<=10

Here is the equivalent T-SQL code using goto:

DECLARE @I INT=1;
START:                -- DO
  PRINT @I;
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

DECLARE @I INT=1;
WHILE (1=1)              -- DO
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10
 END

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.


REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

SET I=1
REPEAT
  PRINT I
  SET I=I+1
UNTIL I>10

... and the GOTO based solution in T-SQL:

DECLARE @I INT=1;
START:                    -- REPEAT
  PRINT @I;
  SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

DECLARE @I INT=1;
WHILE (1=1)       -- REPEAT
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10
 END

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

Invalid application of sizeof to incomplete type with a struct

Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

Access XAMPP Localhost from Internet

I guess you can do this in 5 minute without any further IP/port forwarding, for presenting your local websites temporary.

All you need to do it, go to http://ngrok.com Download small tool extract and run that tool as administrator enter image description here

Enter command
ngrok http 80

You will see it will connect to server and will create a temporary URL for you which you can share to your friend and let him browse localhost or any of its folder.

You can see detailed process here.
How do I access/share xampp or localhost website from another computer

Difference between System.DateTime.Now and System.DateTime.Today

The DateTime.Now property returns the current date and time, for example 2011-07-01 10:09.45310.

The DateTime.Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000.

The DateTime.Today property actually is implemented to return DateTime.Now.Date:

public static DateTime Today {
  get {
    DateTime now = DateTime.Now;
    return now.Date;
  }
}

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:

Use:

df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.

Link

Can not change UILabel text color

May be the better way is

UIColor *color = [UIColor greenColor];
[self.myLabel setTextColor:color];

Thus we have colored text

Facebook API error 191

in the facebook App Page, goto the basic tab. find "Website with Facebook Login" Option.

you will find Site URL: input there put the full URL ( for example http://Mywebsite.com/MyLogin.aspx ). this is the URL you can use with the call like If the APP ID is 123456789

https://graph.facebook.com/oauth/authorize?client_id=123456789&redirect_uri=http://Mywebsite/MyLogin.aspx&scope=publish_actions

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

How to split a single column values to multiple column values?

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
      FROM somenames
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

Add a tooltip to a div

you can do it with simple css... jsfiddle here you can see the example

below css code for tooltip

[data-tooltip] {
  position: relative;
  z-index: 2;
  cursor: pointer;
}

/* Hide the tooltip content by default */
[data-tooltip]:before,
[data-tooltip]:after {
  visibility: hidden;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0;
  pointer-events: none;
}

/* Position tooltip above the element */
[data-tooltip]:before {
  position: absolute;
  bottom: 150%;
  left: 50%;
  margin-bottom: 5px;
  margin-left: -80px;
  padding: 7px;
  width: 160px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  background-color: #000;
  background-color: hsla(0, 0%, 20%, 0.9);
  color: #fff;
  content: attr(data-tooltip);
  text-align: center;
  font-size: 14px;
  line-height: 1.2;
}

/* Triangle hack to make tooltip look like a speech bubble */
[data-tooltip]:after {
  position: absolute;
  bottom: 150%;
  left: 50%;
  margin-left: -5px;
  width: 0;
  border-top: 5px solid #000;
  border-top: 5px solid hsla(0, 0%, 20%, 0.9);
  border-right: 5px solid transparent;
  border-left: 5px solid transparent;
  content: " ";
  font-size: 0;
  line-height: 0;
}

/* Show tooltip content on hover */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
  visibility: visible;
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
  filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);
  opacity: 1;
}

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

How to mark a build unstable in Jenkins when running shell scripts

You should use Jenkinsfile to wrap your build script and simply mark the current build as UNSTABLE by using currentBuild.result = "UNSTABLE".

   stage {
      status = /* your build command goes here */
      if (status === "MARK-AS-UNSTABLE") {
        currentBuild.result = "UNSTABLE"
      }
   }

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

Properly close mongoose's connection once you're done

Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:

let db;
mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
    db = dbConnection;
    afterwards();
});


function afterwards(){

    //do stuff

    db.disconnect();
}

or if inside Async function:

(async ()=>{
    const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: 
                  true })

    //do stuff

    db.disconnect()
})

otherwise when i was checking it in my environment it has an error.

Checking for a null int value from a Java ResultSet

I think, it is redundant. rs.getObject("ID_PARENT") should return an Integer object or null, if the column value actually was NULL. So it should even be possible to do something like:

if (rs.next()) {
  Integer idParent = (Integer) rs.getObject("ID_PARENT");
  if (idParent != null) {
    iVal = idParent; // works for Java 1.5+
  } else {
    // handle this case
  }      
}

How to set dialog to show in full screen?

try

Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen)

What determines the monitor my app runs on?

I've noticed that if I put a shortcut on my desktop on one screen the launched application may appear on that screen (if that app doesn't reposition itself).

This also applies to running things from Windows Explorer - if Explorer is on one screen the launched application will pick that monitor to use.

Again - I think this is when the launching application specifies the default (windows managed) position. Most applications seem to override this default behavior in some way.

A simple window created like so will do this:

hWnd = CreateWindow(windowClass, windowTitle, WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, SW_SHOW, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL);

ValueError: all the input arrays must have same number of dimensions

The reason why you get your error is because a "1 by n" matrix is different from an array of length n.

I recommend using hstack() and vstack() instead. Like this:

import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:]                    # last column of that matrix.

result = np.hstack((a,b))       # stack them horizontally like this:
#array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
#       [16, 17, 18, 19, 20, 21, 22, 23, 23],
#       [24, 25, 26, 27, 28, 29, 30, 31, 31]])

Notice the repeated "7, 15, 23, 31" column. Also, notice that I used a[:,-1:] instead of a[:,-1]. My version generates a column:

array([[7],
       [15],
       [23],
       [31]])

Instead of a row array([7,15,23,31])


Edit: append() is much slower. Read this answer.

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).

Also, make sure your user is allowed to connect to whatever database you're trying to select.

Handling 'Sequence has no elements' Exception

I had the same issue, i realized i had deleted the default image that was in the folder just update the media missing, on the specific file

How do I open a URL from C++?

I've had MUCH better luck using ShellExecuteA(). I've heard that there are a lot of security risks when you use "system()". This is what I came up with for my own code.

void SearchWeb( string word )
{    
    string base_URL = "http://www.bing.com/search?q=";
    string search_URL = "dummy";
    search_URL = base_URL + word;

    cout << "Searching for: \"" << word << "\"\n";

    ShellExecuteA(NULL, "open", search_URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
}

p.s. Its using WinAPI if i'm correct. So its not multiplatform solution.

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Javascript split regex question

try this instead

date.split(/\W+/)

How to create a DataTable in C# and how to add rows?

DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`

dt.Columns.Add(Age);

DataRow dr=dt.NewRow();

dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();

dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();

Double precision floating values in Python?

Python's built-in float type has double precision (it's a C double in CPython, a Java double in Jython). If you need more precision, get NumPy and use its numpy.float128.

Electron: jQuery is not defined

This works for me.

<script languange="JavaScript">
     if (typeof module === 'object') {window.module = module; module = undefined;}
</script>

Things to consider:

1) Put this in section right before </head>

2) Include Jquery.min.js or Jquery.js right before the </body> tag

Where are environment variables stored in the Windows Registry?

Here's where they're stored on Windows XP through Windows Server 2012 R2:

User Variables

HKEY_CURRENT_USER\Environment

System Variables

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Is there a way to compile node.js source files?

EncloseJS.

You get a fully functional binary without sources.

Native modules also supported. (must be placed in the same folder)

JavaScript code is transformed into native code at compile-time using V8 internal compiler. Hence, your sources are not required to execute the binary, and they are not packaged.

Perfectly optimized native code can be generated only at run-time based on the client's machine. Without that info EncloseJS can generate only "unoptimized" code. It runs about 2x slower than NodeJS.

Also, node.js runtime code is put inside the executable (along with your code) to support node API for your application at run-time.

Use cases:

  • Make a commercial version of your application without sources.
  • Make a demo/evaluation/trial version of your app without sources.
  • Make some kind of self-extracting archive or installer.
  • Make a closed source GUI application using node-thrust.
  • No need to install node and npm to deploy the compiled application.
  • No need to download hundreds of files via npm install to deploy your application. Deploy it as a single independent file.
  • Put your assets inside the executable to make it even more portable. Test your app against new node version without installing it.

How to debug in Django, the good way?

I use pyDev with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.

WCF Exception: Could not find a base address that matches scheme http for the endpoint

Your configuration should look similar to that. You may have to change <transport clientCredentialType="None" proxyCredentialType="None" /> depending on your needs for authentication. The config below doesn't require any authentication.

<bindings>
    <basicHttpBinding>
        <binding name="basicHttpBindingConfiguration">
            <security mode="Transport">
                <transport clientCredentialType="None" proxyCredentialType="None" />
            </security>
        </binding>       
    </basicHttpBinding>
</bindings>

<services>
    <service name="XXX">
        <endpoint
            name="AAA"
            address=""
            binding="basicHttpBinding"
            bindingConfiguration="basicHttpBindingConfiguration"
            contract="YourContract" />
    </service>
<services>

That will allow a WCF service with basicHttpBinding to use HTTPS.

SQL server stored procedure return a table

You can use an out parameter instead of the return value if you want both a result set and a return value

CREATE PROCEDURE proc_name 
@param int out
AS
BEGIN
    SET @param = value
SELECT ... FROM [Table] WHERE Condition
END
GO

How to open a new HTML page using jQuery?

You need to use ajax.

http://api.jquery.com/jQuery.ajax/

<code>
$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});
</code>

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

I had the same problem and this is how I solved it. I'm on rails 5.1.0rc1

Make sure to add require jquery and tether inside your application.js file they must be at the very top like this

//= require jquery
//= require tether

Just make sure to have tether installed

How to get current user who's accessing an ASP.NET application?

The general consensus answer above seems to have have a compatibility issue with CORS support. In order to use the HttpContext.Current.User.Identity.Name attribute you must disable anonymous authentication in order to force Windows authentication to provide the authenticated user information. Unfortunately, I believe you must have anonymous authentication enabled in order to process the pre-flight OPTIONS request in a CORS scenario.

You can get around this by leaving anonymous authentication enabled and using the HttpContext.Current.Request.LogonUserIdentity attribute instead. This will return the authenticated user information (assuming you are in an intranet scenario) even with anonymous authentication enabled. The attribute returns a WindowsUser data structure and both are defined in the System.Web namespace

        using System.Web;
        WindowsIdentity user;
        user  = HttpContext.Current.Request.LogonUserIdentity;

How to check if NSString begins with a certain character

NSString *stringWithoutAsterisk(NSString *string) {
    NSRange asterisk = [string rangeOfString:@"*"];
    return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}

How to implement a custom AlertDialog View

The android documents have been edited to correct the errors.

The view inside the AlertDialog is called android.R.id.custom

http://developer.android.com/reference/android/app/AlertDialog.html

jQuery get text as number

If anyone came here trying to do this with a decimal like me:

myFloat = parseFloat(myString);

If you just need an Int, that's well covered in the other answers.

How to append binary data to a buffer in node.js

Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.

However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.

How to install multiple python packages at once using pip

Complementing the other answers, you can use the option --no-cache-dir to disable caching in pip. My virtual machine was crashing when installing many packages at once with pip install -r requirements.txt. What solved for me was:

pip install --no-cache-dir -r requirements.txt

How do I enable Java in Microsoft Edge web browser?

You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.

Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.

Work-arounds

There are a couple of things that you can do:

Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets). IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe). Just pin this exe to your task bar for easy access.

Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

Pass mouse events through absolutely-positioned element

Also nice to know...
Pointer-events can be disabled for a parent element (probably transparent div) and yet be enabled for child elements. This is helpful if you work with multiple overlapping div layers, where you want to be able click the child elements of any layer. For this all parenting divs get pointer-events: none and click-children get pointer-events reenabled by pointer-events: all

.parent {
    pointer-events:none;        
}
.child {
    pointer-events:all;
}

<div class="some-container">
   <ul class="layer-0 parent">
     <li class="click-me child"></li>
     <li class="click-me child"></li>
   </ul>

   <ul class="layer-1 parent">
     <li class="click-me-also child"></li>
     <li class="click-me-also child"></li>
   </ul>
</div>

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

Java Scanner class reading strings

It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.

Here a small change that you can do:

int nnames;
    String names[];

    System.out.print("How many names are you going to save: ");
    Scanner in = new Scanner(System.in);
    nnames = Integer.parseInt(in.nextLine());
    names = new String[nnames];

    for (int i = 0; i < names.length; i++){
            System.out.print("Type a name: ");
            names[i] = in.nextLine();
    }

How to know the size of the string in bytes?

System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);

Or

System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);

Microsoft Azure: How to create sub directory in a blob container

If you use Microsoft Azure Storage Explorer, there is a "New Folder" button that allows you to create a folder in a container. This is actually a virtual folder:

enter image description here

grep exclude multiple strings

You can use regular grep like this:

tail -f admin.log | grep -v "Nopaging the limit is\|keyword to remove is"

How to open the command prompt and insert commands using Java?

You just need to append your command after start in the string that you are passing.

String command = "cmd.exe /c start "+"*your command*";

Process child = Runtime.getRuntime().exec(command);

Dynamically fill in form values with jQuery

If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() { 
  $.ajax({ url: 'script/ajax', 
           type: json
           data: $foo,  
           success: function(data) {
             $('input .targetAjax').val(data.newValue);
           });
  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.

Maintain/Save/Restore scroll position when returning to a ListView

You can maintain the scroll state after a reload if you save the state before you reload and restore it after. In my case I made a asynchronous network request and reloaded the list in a callback after it completed. This is where I restore state. Code sample is Kotlin.

val state = myList.layoutManager.onSaveInstanceState()

getNewThings() { newThings: List<Thing> ->

    myList.adapter.things = newThings
    myList.layoutManager.onRestoreInstanceState(state)
}

How to replace a string in a SQL Server Table Column

If target column type is other than varchar/nvarchar like text, we need to cast the column value as string and then convert it as:

update URL_TABLE
set Parameters = REPLACE ( cast(Parameters as varchar(max)), 'india', 'bharat')
where URL_ID='150721_013359670'

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Getting multiple values with scanf()

Yes.

int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

They are viewport meta tags, and is most applicable on mobile browsers.

width=device-width

This means, we are telling to the browser “my website adapts to your device width”.

initial-scale

This defines the scale of the website, This parameter sets the initial zoom level, which means 1 CSS pixel is equal to 1 viewport pixel. This parameter help when you're changing orientation, or preventing default zooming. Without this parameter, responsive site won't work.

maximum-scale

Maximum-scale defines the maximum zoom. When you access the website, top priority is maximum-scale=1, and it won’t allow the user to zoom.

minimum-scale

Minimum-scale defines the minimum zoom. This works the same as above, but it defines the minimum scale. This is useful, when maximum-scale is large, and you want to set minimum-scale.

user-scalable

User-scalable assigned to 1.0 means the website is allowing the user to zoom in or zoom out.

But if you assign it to user-scalable=no, it means the website is not allowing the user to zoom in or zoom out.

How to change TextBox's Background color?

In WinForms and WebForms you can do:

txtName.BackColor = Color.Aqua;

How can I mock the JavaScript window object using Jest?

In your Jest configuration, add setupFilesAfterEnv: ["./setupTests.js"], create that file, and add the code you want to run before the tests:

// setupTests.js
window.crypto = {
   .....
};

Reference: setupFilesAfterEnv [array]

Remove all newlines from inside a string

If the file includes a line break in the middle of the text neither strip() nor rstrip() will not solve the problem,

strip family are used to trim from the began and the end of the string

replace() is the way to solve your problem

>>> my_name = "Landon\nWO"
>>> print my_name
   Landon
   WO

>>> my_name = my_name.replace('\n','')
>>> print my_name
LandonWO

PHP 7 RC3: How to install missing MySQL PDO

Since eggyal didn't provided his comment as answer after he gave right advice in a comment - i am posting it here: In my case I had to install module php-mysql. See comments under the question for details.

how to find array size in angularjs

You can find the number of members in a Javascript array by using its length property:

var number = $scope.names.length;

Docs - Array.prototype.length

How to install python-dateutil on Windows?

First confirm that you have in C:/python##/Lib/Site-packages/ a folder dateutil, perhaps you download it, you should already have pip,matplotlib, six##,,confirm you have installed dateutil by--- go to the cmd, cd /python, you should have a folder /Scripts. cd to Scripts, then type --pip install python-dateutil -- ----This applies to windows 7 Ultimate 32bit, Python 3.4------

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

I also had the same problem and able to resolve after using below command

/root/mysql-sandboxes/3320/bin/mysqld --defaults-file=/root/mysql-sandboxes/3320/my.cnf  --user=root &

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

Same applies for guard statements. The same error message lead me to this post and answer (thanks @nhgrif).

The code: Print the last name of the person only if the middle name is less than four characters.

func greetByMiddleName(name: (first: String, middle: String?, last: String?)) {
    guard let Name = name.last where name.middle?.characters.count < 4 else {
        print("Hi there)")
        return
    }
    print("Hey \(Name)!")
}

Until I declared last as an optional parameter I was seeing the same error.

Find text string using jQuery?

this function should work. basically does a recursive lookup till we get a distinct list of leaf nodes.

function distinctNodes(search, element) {
    var d, e, ef;
    e = [];
    ef = [];

    if (element) {
        d = $(":contains(\""+ search + "\"):not(script)", element);
    }
    else {
            d = $(":contains(\""+ search + "\"):not(script)");
    }

    if (d.length == 1) {
            e.push(d[0]);
    }
    else {
        d.each(function () {
            var i, r = distinctNodes(search, this);
            if (r.length === 0) {
                e.push(this);
            }
            else {
                for (i = 0; i < r.length; ++i) {
                    e.push(r[i]);
                }
            }
        });
    }
    $.each(e, function () {
        for (var i = 0; i < ef.length; ++i) {
            if (this === ef[i]) return;
        }
        ef.push(this);
    });
    return ef;
}

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

long long in C/C++

The letters 100000000000 make up a literal integer constant, but the value is too large for the type int. You need to use a suffix to change the type of the literal, i.e.

long long num3 = 100000000000LL;

The suffix LL makes the literal into type long long. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.

Make absolute positioned div expand parent div height

This question was asked in 2012 before flexbox. The correct way to solve this problem using modern CSS is with a media query and a flex column reversal for mobile devices. No absolute positioning is needed.

https://jsfiddle.net/tnhsaesop/vjftq198/3/

HTML:

<div class="parent">
  <div style="background-color:lightgrey;">
    <p>
      I stay on top on desktop and I'm on bottom on mobile
    </p>
  </div>
  <div style="background-color:grey;">
    <p>
      I stay on bottom on desktop and I'm on top on mobile
    </p>
  </div>
</div>

CSS:

.parent {
  display: flex;
  flex-direction: column;
}

@media (max-width: 768px) {
  .parent {
    flex-direction: column-reverse;
  }
}

Is there a way to @Autowire a bean that requires constructor arguments?

An alternative would be instead of passing the parameters to the constructor you might have them as getter and setters and then in a @PostConstruct initialize the values as you want. In this case Spring will create the bean using the default constructor. An example is below

@Component
public class MyConstructorClass{

  String var;

  public void setVar(String var){
     this.var = var;
  }

  public void getVar(){
    return var;
  }

  @PostConstruct
  public void init(){
     setVar("var");
  }
...
}


@Service
public class MyBeanService{
  //field autowiring
  @Autowired
  MyConstructorClass myConstructorClass;

  ....
}

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

What is a vertical tab?

Microsoft Word uses VT as a line separator in order to distinguish it from the normal new line function, which is used as a paragraph separator.

How do I clear a search box with an 'x' in bootstrap 3?

Super-simple HTML 5 Solution:

_x000D_
_x000D_
<input type="search" placeholder="Search..." />
_x000D_
_x000D_
_x000D_

Source: HTML 5 Tutorial - Input Type: Search

That works in at least Chrome 8, Edge 14, IE 10, and Safari 5 and does not require Bootstrap or any other library. (Unfortunately, it seems Firefox does not support the search clear button yet.)

After typing in the search box, an 'x' will appear which can be clicked to clear the text. This will still work as an ordinary edit box (without the 'x' button) in other browsers, such as Firefox, so Firefox users could instead select the text and press delete, or...

If you really need this nice-to-have feature supported in Firefox, then you could implement one of the other solutions posted here as a polyfill for input[type=search] elements. A polyfill is code that automatically adds a standard browser feature when the user's browser doesn't support the feature. Over time, the hope is that you'd be able to remove polyfills as browsers implement the respective features. And in any case, a polyfill implementation can help to keep the HTML code cleaner.

By the way, other HTML 5 input types (such as "date", "number", "email", etc.) will also degrade gracefully to a plain edit box. Some browsers might give you a fancy date picker, a spinner control with up/down buttons, or (on mobile phones) a special keyboard that includes the '@' sign and a '.com' button, but to my knowledge, all browsers will at least show a plain text box for any unrecognized input type.


Bootstrap 3 & HTML 5 Solution

Bootstrap 3 resets a lot of CSS and breaks the HTML 5 search cancel button. After the Bootstrap 3 CSS has been loaded, you can restore the search cancel button with the CSS used in the following example:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<style>_x000D_
  input[type="search"]::-webkit-search-cancel-button {_x000D_
    -webkit-appearance: searchfield-cancel-button;_x000D_
  }_x000D_
</style>_x000D_
<div class="form-inline">_x000D_
  <input type="search" placeholder="Search..." class="form-control" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Source: HTML 5 Search Input Does Not Work with Bootstrap

I have tested that this solution works in the latest versions of Chrome, Edge, and Internet Explorer. I am not able to test in Safari. Unfortunately, the 'x' button to clear the search does not appear in Firefox, but as above, a polyfill could be implemented for browsers that don't support this feature natively (i.e. Firefox).

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

Here an alternative using SUBSTRING

SELECT
            SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
            SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
    FROM 
            [Fields]

with fiddle

sudo echo "something" >> /etc/privilegedFile doesn't work

I would note, for the curious, that you can also quote a heredoc (for large blocks):

sudo bash -c "cat <<EOIPFW >> /etc/ipfw.conf
<?xml version=\"1.0\" encoding=\"UTF-8\"?>

<plist version=\"1.0\">
  <dict>
    <key>Label</key>
    <string>com.company.ipfw</string>
    <key>Program</key>
    <string>/sbin/ipfw</string>
    <key>ProgramArguments</key>
    <array>
      <string>/sbin/ipfw</string>
      <string>-q</string>
      <string>/etc/ipfw.conf</string>
    </array>
    <key>RunAtLoad</key>
    <true></true>
  </dict>
</plist>
EOIPFW"

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Quick and Dirty Way!

It's not a good way, but for me it seems the most simplest.

Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)

<a href="" data-toggle="modal" data-target="#myModal" id="myModalShower"></a>

Now,

Inside the angular controller, from where you want to trigger the modal just use

angular.element('#myModalShower').trigger('click');

This will mimic a click to the button based on the angular code and the modal will appear.

How to keep indent for second line in ordered lists via CSS?

You can set the margin and padding of either an ol or ul in CSS

ol {
margin-left: 0;
padding-left: 3em;
list-style-position: outside;
}

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

package android.support.v4.app does not exist ; in Android studio 0.8

@boernard 's answer solves this from the Android Studio IDE, but if you want to understand what's happening under the covers, it's a simple gradle build file update:

You can edit the build.gradle file from within the IDE (left pane: Gradle Scripts -> build.gradle (Module: app)) or use the raw path (<proj_dir>/app/build.gradle) and add/update the following dependency section:

dependencies {
    //
    // IDE setting pulls in the specific version of v4 support you have installed:
    //
    //compile 'com.android.support:support-v4:21.0.3'

    //
    // generic directive pulls in any available version of v4 support:
    //
    compile 'com.android.support:support-v4:+'
}

Using the above generic compile directive, allows you to ship your code to anyone, provided they have some level of the Android Support Libraries v4 installed.

How do I get to IIS Manager?

First of all, you need to check that the IIS is installed in your machine, for that you can go to:

Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'

If not, check it, and Press Accept to install it.

Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).

Edit: You should have something like this: enter image description here

"CSV file does not exist" for a filename with embedded quotes

I also experienced the same problem I solved as follows:

dataset = pd.read_csv('C:\\Users\\path\\to\\file.csv')

How do I block comment in Jupyter notebook?

Try using the / from the numeric keyboard. Ctrl + / in Chrome wasn't working for me, but when I used the /(division symbol) from the numeric it worked.

Override browser form-filling and input highlighting with HTML/CSS

You can disable auto-completion as of HTML5 (via autocomplete="off"), but you CAN'T override the browser's highlighting. You could try messing with ::selection in CSS (most browsers require a vendor prefix for that to work), but that probably won't help you either.

Unless the browser vendor specifically implemented a vendor-specific way of overriding it, you can't do anything about such styles that are already intended to override the site's stylesheet for the user. These are usually applied after your stylesheets are applied and ignore ! important overrides, too.

How to manually force a commit in a @Transactional method?

I know that due to this ugly anonymous inner class usage of TransactionTemplate doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.

In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional on the test methods. Why? Because @Transactional may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate can be perfect for controlling transaction boundries when we want that control.

React-Router External link

I was able to achieve a redirect in react-router-dom using the following

<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />

For my case, I was looking for a way to redirect users whenever they visit the root URL http://myapp.com to somewhere else within the app http://myapp.com/newplace. so the above helped.

Passing an array using an HTML form hidden element

<input type="hidden" name="item[]" value="[anyvalue]">

Let it be in a repeated mode it will post this element in the form as an array and use the

print_r($_POST['item'])

To retrieve the item

How to enable scrolling of content inside a modal?

After using all these mentioned solution, i was still not able to scroll using mouse scroll, keyboard up/down button were working for scrolling content.

So i have added below css fixes to make it working

.modal-open {
    overflow: hidden;
}

.modal-open .modal {
    overflow-x: hidden;
    overflow-y: auto;
    **pointer-events: auto;**
}

Added pointer-events: auto; to make it mouse scrollable.

go to link on button click - jquery

You need to specify the domain:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

Convert YYYYMMDD to DATE

Use SELECT CONVERT(date, '20140327')

In your case,

SELECT [FIRST_NAME],
       [MIDDLE_NAME],
       [LAST_NAME],
       CONVERT(date, [GRADUATION_DATE])     
FROM mydb

How to create a file in memory for user to download, but not through server?

Solution that work on IE10: (I needed a csv file, but it's enough to change type and filename to txt)

var csvContent=data; //here we load our csv data 
var blob = new Blob([csvContent],{
    type: "text/csv;charset=utf-8;"
});

navigator.msSaveBlob(blob, "filename.csv")

Not able to launch IE browser using Selenium2 (Webdriver) with Java

It needs to set same Security level in all zones. To do that follow the steps below:

  1. Open IE
  2. Go to Tools -> Internet Options -> Security
  3. Set all zones (Internet, Local intranet, Trusted sites, Restricted sites) to the same protected mode, enabled or disabled should not matter.

Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
                       .getClassLoader().getResource("sql/script.sql");

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password https://xyz.com/changelog-6.40.txt

How to add google-play-services.jar project dependency so my project will run and present map

Be Careful, Follow these steps and save your time

  1. Right Click on your Project Explorer.

  2. Select New-> Project -> Android Application Project from Existing Code

  3. Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"

  4. Be careful brose only upto - google_play_services and not upto google_play_services_lib

  5. And this way you are able to import the google play service lib.

Let me know if you have any queries regarding the same.

Thanks

Java program to find the largest & smallest number in n numbers without using arrays

@user3168844: try the below code:

import java.util.Scanner;

public class LargestSmallestNum {

    public void findLargestSmallestNo() {

        int smallest = Integer.MAX_VALUE;
        int large = 0;
        int num;

        System.out.println("enter the number");

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();

        for (int i = 0; i < n; i++) {

            num = input.nextInt();

            if (num > large)
                large = num;

            if (num < smallest)
                smallest = num;

            System.out.println("the largest is:" + large);
            System.out.println("Smallest no is : "  + smallest);
        }
    }

    public static void main(String...strings){
        LargestSmallestNum largestSmallestNum = new LargestSmallestNum();
        largestSmallestNum.findLargestSmalestNo();
    }
}

Epoch vs Iteration when training neural networks

I guess in the context of neural network terminology:

  • Epoch: When your network ends up going over the entire training set (i.e., once for each training instance), it completes one epoch.

In order to define iteration (a.k.a steps), you first need to know about batch size:

  • Batch size: You probably wouldn't like to process the entire training instances all at one forward pass as it is inefficient and needs a huge deal of memory. So what is commonly done is splitting up training instances into subsets (i.e., batches), performing one pass over the selected subset (i.e., batch), and then optimizing the network through backpropagation. The number of training instances within a subset (i.e., batch) is called batch_size.

  • Iteration: (a.k.a training steps) You know that your network has to go over all training instances in one pass in order to complete one epoch. But wait! when you are splitting up your training instances into batches, that means you can only process one batch (a subset of training instances) in one forward pass, so what about the other batches? This is where the term Iteration comes into play:

  • Definition: The number of forward passes (The number of batches that you have created) that your network has to do in order to complete one epoch (i.e., going over all training instances) is called Iteration.

For example, when you have 10000 training instances and you want to do batching with size of 10; you have to do 10000/10 = 1000 iterations to complete 1 epoch.

Hope this could answer your question!

SyntaxError: unexpected EOF while parsing

elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'

The error comes at the end of the line where you have the (') sign; this error always means that you have a syntax error.

How to draw text using only OpenGL methods?

Drawing text in plain OpenGL isn't a straigth-forward task. You should probably have a look at libraries for doing this (either by using a library or as an example implementation).

Some good starting points could be GLFont, OpenGL Font Survey and NeHe Tutorial for Bitmap Fonts (Windows).

Note that bitmaps are not the only way of achieving text in OpenGL as mentioned in the font survey.

Set a request header in JavaScript

For people looking this up now:

It seems that now setting the User-Agent header is allowed since Firefox 43. See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name for the current list of forbidden headers.

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

Django ChoiceField

If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .

Example:

views.py:

def my_view(request, interview_pk):
    interview = Interview.objects.get(pk=interview_pk)
    all_rounds = interview.round_set.order_by('created_at')
    all_round_names = [rnd.name for rnd in all_rounds]
    form = forms.AddRatingForRound(all_round_names)
    return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})

forms.py

class AddRatingForRound(forms.ModelForm):

    def __init__(self, round_list, *args, **kwargs):
        super(AddRatingForRound, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))

    class Meta:
        model = models.RatingSheet
        fields = ('name', )

template:

<form method="post">
    {% csrf_token %}
    {% if interview %}
         {{ interview }}
    {% endif %}
    {% if rounds %}
    <hr>
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    {% else %}
        <h3>No rounds found</h3>
    {% endif %}

</form>

Differences between git pull origin master & git pull origin/master

git pull origin master will pull changes from the origin remote, master branch and merge them to the local checked-out branch.

git pull origin/master will pull changes from the locally stored branch origin/master and merge that to the local checked-out branch. The origin/master branch is essentially a "cached copy" of what was last pulled from origin, which is why it's called a remote branch in git parlance. This might be somewhat confusing.

You can see what branches are available with git branch and git branch -r to see the "remote branches".

How to push local changes to a remote git repository on bitbucket

This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.

To push all local branches to the remote repository, use --all:

git push REMOTENAME --all
git push --all

or specify all branches you want to push:

git push REMOTENAME master exp-branch-a anotherbranch bugfix

In addition, it's useful to add -u to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.

How to deal with SettingWithCopyWarning in Pandas

This should work:

quote_df.loc[:,'TVol'] = quote_df['TVol']/TVOL_SCALE