Programs & Examples On #Buttonclick

An event that occurs when a user clicks a button element located within a user interface

How to launch another aspx web page upon button click?

Edited and fixed (thanks to Shredder)

If you mean you want to open a new tab, try the below:

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.Target = "_blank";
}

protected void Button1_Click(object sender, EventArgs e)
{

    Response.Redirect("Otherpage.aspx");
}

This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.

-J

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

How to make a button redirect to another page using jQuery or just Javascript

You can use window.location

window.location="/newpage.php";

Or you can just make the form that the search button is in have a action of the page you want.

How to press/click the button using Selenium if the button does not have the Id?

    You can achieve this by using cssSelector 
    // Use of List web elements:
    String cssSelectorOfLoginButton="input[type='button'][id='login']"; 
    //****Add cssSelector of your 1st webelement
    //List<WebElement> button 
    =driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
    button.get(0).click();

    I hope this work for you

How do I view executed queries within SQL Server Management Studio?

Use SQL Profiler and use a filter on it to get the most expensive queries.

TypeError: no implicit conversion of Symbol into Integer

myHash.each{|item|..} is returning you array object for item iterative variable like the following :--

[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]

You should do this:--

def format
  output = Hash.new
  myHash.each do |k, v|
    output[k] = cleanup(v)
  end
  output
end

jQuery has deprecated synchronous XMLHTTPRequest

If we load script in partial view then this issue coming

  1. I removed script in partial view and moved to main view.

This solution working fine for me

How to analyze a JMeter summary report?

Sample: Number of requests sent.

The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.

The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.

The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.

Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.

Min and Max are the minimum and maximum response time.

An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!

Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.

The following equation show how the standard deviation (s) is calculated:

s = 1/n * v Si=1…n (xi-µ)2

For Details, see here!!

So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.

Kb/sec: The throughput measured in Kilobytes per second.

Error % : Percent of requests with errors.

An example is always better to understand!!! I think, this article will help you.

Can I invoke an instance method on a Ruby module without including it?

If you want to call these methods without including module in another class then you need to define them as module methods:

module UsefulThings
  def self.get_file; ...
  def self.delete_file; ...

  def self.format_text(x); ...
end

and then you can call them with

UsefulThings.format_text("xxx")

or

UsefulThings::format_text("xxx")

But anyway I would recommend that you put just related methods in one module or in one class. If you have problem that you want to include just one method from module then it sounds like a bad code smell and it is not good Ruby style to put unrelated methods together.

How can I set a custom baud rate on Linux?

I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>. Just a forewarning, I think I ran into problems including both it and the regular <termios.h> file at the same time.

Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>:

struct termios2 tio;

ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);

Mark error in form using Bootstrap

Can use CSS to show error message only on error.

.form-group.has-error .help-block {
    display: block;
}

.form-group .help-block {
    display: none;
}


<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>
</div>

How to hide a View programmatically?

You can call view.setVisibility(View.GONE) if you want to remove it from the layout.

Or view.setVisibility(View.INVISIBLE) if you just want to hide it.

From Android Docs:

INVISIBLE

This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

GONE

This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.

How to check if an object is an array?

Here's what I use:

function isArray(input) {
  if (input instanceof Array || Object.prototype.toString.call(input) === '[object Array]') {
        return true;
  } else return false;
}

Select All as default value for Multivalue parameter

Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.

This page didn't load Google Maps correctly. See the JavaScript console for technical details

You could also get the error if your Billing is not set up correctly.

Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.

enter image description here

Displaying a vector of strings in C++

vector.size() returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
    vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        userString.push_back(word);
        sentence += userString[i] + " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    int SIZE;
    cin>>SIZE;    //what will be the size of the vector
    for (int i = 0; i < SIZE; i++)
    {
        cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
    system("PAUSE");
    return 0;
}

and if you want to enter string until the user wish , code will be like this:

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;


int main(int a, char* b [])
{
   // vector<string> userString;
    string word;
    string sentence = "";
    //int SIZE;
    //cin>>SIZE;    //what will be the size of the vector
    while(cin>>word)
    {
        //cin >> word;
        sentence += word+ " ";
    }
    cout << sentence;
  //  system("PAUSE");
    return 0;
}

PHP - remove <img> tag from string

Try dropping the \ in front of the >.

Edit: I just tested your regex and it works fine. This is what I used:

<?
    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;
?>

The result is:

this is something with an (image)  in it.

Spring MVC UTF-8 Encoding

To solve this issue you need below three steps:

  1. Set page encoding to UTF-8 like below:

    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@ page contentType="text/html;charset=UTF-8" %>
    
  2. Set filter in web.xml file as below:

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  3. Set resource encoding to UTF-8, in case if you are writing any UTF-8 characters in Java code or JSP directly.

What does "hashable" mean in Python?

Let me give you a working example to understand the hashable objects in python. I am taking 2 Tuples for this example.Each value in a tuple has a unique Hash Value which never changes during its lifetime. So based on this has value, the comparison between two tuples is done. We can get the hash value of a tuple element using the Id().

Comparison between 2 tuplesEquivalence between 2 tuples

PostgreSQL how to see which queries have run

You can see in pg_log folder if the log configuration is enabled in postgresql.conf with this log directory name.

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

The previous code was

<p class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></p>

So I have to changed it to

<div class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></div>

It was the easy fix. And the CSS for the above code is

.item {
    position: relative;
    border: 1px solid green;
    height: 30px;
}

.item .name {
    position: absolute;
    top: 0px;
    left: 0px;
}

.item .price {
    position: absolute;
    right: 0px;
    bottom: 0px;
}

So div tag can contain other elements. P should not be forced to do that.

Java : Cannot format given Object as a Date

This worked for me:

String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);

error TS2339: Property 'x' does not exist on type 'Y'

I was getting this error on Vue 3. It was because defineComponent must be imported like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "HelloWorld",
    props: {
        msg: String,
    },
    created() {
        this.testF();
    },
    methods: {
        testF() {
            console.log("testF");
        },
    },
});
</script>

How to call a PHP function on the click of a button

Here is an example which you could use:

<html>
    <body>
        <form action="btnclick.php" method="get">
            <input type="submit" name="on" value="on">
            <input type="submit" name="off" value="off">
        </form>
    </body>
</html>
<?php
    if(isset($_GET['on'])) {
        onFunc();
    }
    if(isset($_GET['off'])) {
        offFunc();
    }

    function onFunc(){
        echo "Button on Clicked";
    }
    function offFunc(){
        echo "Button off clicked";
    }
?>

FileProvider - IllegalArgumentException: Failed to find configured root

Be aware that external-path is not pointing to your secondary storage, aka "removable storage" (despite the name "external"). If you're getting "Failed to find configured root" you may add this line to your XML file.

<root-path name="root" path="." />

See more details here FileProvider and secondary external storage

Can I get "&&" or "-and" to work in PowerShell?

Use:

if (start-process filename1.exe) {} else {start-process filename2.exe}

It's a little longer than "&&", but it accomplishes the same thing without scripting and is not too hard to remember.

How to list only top level directories in Python?

os.walk

Use os.walk with next item function:

next(os.walk('.'))[1]

For Python <=2.5 use:

os.walk('.').next()[1]

How this works

os.walk is a generator and calling next will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the [1] index returns only the dirnames from that tuple.

git push rejected

First, attempt to pull from the same refspec that you are trying to push to.

If this does not work, you can force a git push by using git push -f <repo> <refspec>, but use caution: this method can cause references to be deleted on the remote repository.

How to include "zero" / "0" results in COUNT aggregate?

To change even less on your original query, you can turn your join into a RIGHT join

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM appointment
RIGHT JOIN person ON person.person_id = appointment.person_id
GROUP BY person.person_id;

This just builds on the selected answer, but as the outer join is in the RIGHT direction, only one word needs to be added and less changes. - Just remember that it's there and can sometimes make queries more readable and require less rebuilding.

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

PHP: date function to get month of the current date

To compare with an int do this:

<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
    echo "They are the same";
}
?>

How to convert an Stream into a byte[] in C#?

Ok, maybe I'm missing something here, but this is the way I do it:

public static Byte[] ToByteArray(this Stream stream) {
    Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
    Byte[] buffer = new Byte[length];
    stream.Read(buffer, 0, length);
    return buffer;
}

Representing EOF in C code?

No. EOF is not a character, but a state of the filehandle.

While there are there are control characters in the ASCII charset that represents the end of the data, these are not used to signal the end of files in general. For example EOT (^D) which in some cases almost signals the same.

When the standard C library uses signed integer to return characters and uses -1 for end of file, this is actually just the signal to indicate than an error happened. I don't have the C standard available, but to quote SUSv3:

If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgetc() shall return EOF. If a read error occurs, the error indicator for the stream shall be set, fgetc() shall return EOF, and shall set errno to indicate the error.

How to set max width of an image in CSS

You can write like this:

img{
    width:100%;
    max-width:600px;
}

Check this http://jsfiddle.net/ErNeT/

Good ways to manage a changelog using git?

For a GNU style changelog, I've cooked the function

gnuc() {
  {
    printf "$(date "+%Y-%m-%d")  John Doe  <[email protected]>\n\n"
    git diff-tree --no-commit-id --name-only -r HEAD | sed 's/^/\t* /'
  } | tee /dev/tty | xsel -b
}

With this:

  • I commit my changes periodically to backup and rebase them before doing the final edit to the ChangeLog
  • then run: gnuc

and now my clipboard contains something like:

2015-07-24  John Doe  <[email protected]>

        * gdb/python/py-linetable.c (): .
        * gdb/python/py-symtab.c (): .

Then I use the clipboard as a starting point to update the ChangeLog.

It is not perfect (e.g. files should be relative to their ChangeLog path, so python/py-symtab.c without gdb/ since I will edit the gdb/ChangeLog), but is a good starting point.

More advanced scripts:

I have to agree with Tromey though: duplicating git commit data in the ChangeLog is useless.

If you are going to make a changelog, make it a good summary of what is going on, possibly as specified at http://keepachangelog.com/

Android EditText Hint

I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText, and as soon it gains focus, set the hint to be nothing with something like editText.setHint(""):

This may not be exactly what you have to do, but it may be something like this-

myEditText.setOnFocusListener(new OnFocusListener(){
  public void onFocus(){
    myEditText.setHint("");
  }
});

pass post data with window.location.href

Have you considered simply using Local/Session Storage? -or- Depending on the complexity of what you're building; you could even use indexDB.

note:

Local storage and indexDB are not secure - so you want to avoid storing any sensitive / personal data (i.e names, addresses, emails addresses, DOB etc) in either of these.

Session Storage is a more secure option for anything sensitive, it's only accessible to the origin that set the items and also clears as soon as the browser / tab is closed.

IndexDB is a little more [but not much more] complicated and is a 30MB noSQL database built into every browser (but can be basically unlimited if the user opts in) -> next time you're using Google docs, open you DevTools -> application -> IndexDB and take a peak. [spoiler alert: it's encrypted].

Focusing on Local and Session Storage; these are both dead simple to use:

// To Set 
sessionStorage.setItem( 'key' , 'value' );

// e.g.
sessionStorage.setItem( 'formData' , { name: "Mr Manager", company: "Bluth's Frozen Bananas", ...  } );    

// Get The Data 
const fromData = sessionStorage.getItem( 'key' );     

// e.g. (after navigating to next location)
const fromData = sessionStorage.getItem( 'formData' );

// Remove 
sessionStorage.removeItem( 'key' );

// Remove _all_ saved data sessionStorage
sessionStorage.clear( ); 

If simple is not your thing -or- maybe you want to go off road and try a different approach all together -> you can probably use a shared web worker... y'know, just for kicks.

Execute stored procedure with an Output parameter?

With this query you can execute any stored procedure(With or Without output parameter):

DECLARE @temp varchar(100)  
EXEC my_sp
    @parameter1 = 1, 
    @parameter2 = 2, 
    @parameter3 = @temp output, 
    @parameter4 = 3, 
    @parameter5 = 4
PRINT @temp

Here datatype of @temp should be same as @parameter3 within SP.

Hope this helps..

CSS technique for a horizontal line with words in the middle

Solution for IE8 and newer...

Issues worth noting:

Using background-color to mask a border might not be the best solution. If you have a complex (or unknown) background color (or image), masking will ultimately fail. Also, if you resize the text, you'll notice that white background color (or whatever you set) will start covering up the text on the line above (or below).

You also don't want to "guesstimate" how wide the the sections are either, because it makes the styles very inflexible and almost impossible to implement on a responsive site where the width of the content is changing.

Solution:

(View JSFiddle)

Instead of "masking" a border with a background-color, use your display property.

HTML

<div class="group">
    <div class="item line"></div>
    <div class="item text">This is a test</div>
    <div class="item line"></div>
</div>

CSS

.group { display: table; width: 100%; }
.item { display: table-cell; }
.text { white-space: nowrap; width: 1%; padding: 0 10px; }
.line { border-bottom: 1px solid #000; position: relative; top: -.5em; }

Resize your text by placing your font-size property on the .group element.

Limitations:

  • No multi-line text. Single lines only.
  • HTML markup isn't as elegant
  • top property on .line element needs to be half of line-height. So, if you have a line-height of 1.5em, then the top should be -.75em. This is a limitation because it's not automated, and if you are applying these styles on elements with different line-heights, then you might need to reapply your line-height style.

For me, these limitations outweigh the "issues" I noted at the beginning of my answer for most implementations.

Session 'app': Error Launching activity

Same issue, but for me problem was that Android Studio couldn't find my Default Activity. When I specified the intent filter to catch the MAIN action intent, I didn't specify the LAUNCHER category, and that caused the 'Error Launching activity' issue.

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />  <-- forgot
    </intent-filter>

apache redirect from non www to www

I found it easier (and more usefull) to use ServerAlias when using multiple vhosts.

<VirtualHost x.x.x.x:80>
    ServerName www.example.com
    ServerAlias example.com
    ....
</VirtualHost>

This also works with https vhosts.

405 method not allowed Web API

I was getting the 405 on my GET call, and the problem turned out that I named the parameter in the GET server-side method Get(int formId), and I needed to change the route, or rename it Get(int id).

How to unload a package without restarting R

When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.

if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE) 

Including this at the top of a script might be helpful.

I hope that makes your day!

horizontal scrollbar on top and bottom of table

There is an issue with scroll direction: rtl. It seems the plugin doesn't support it correctly. Here is the fiddle: fiddle

Note that it works correctly in Chrome, but in all other popular browsers the top scroll bar direction remains left.

MySQL : transaction within a stored procedure

This is just an explanation not addressed in other answers

At least in recent versions of Mysql, your first query is not committed.

If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.

What's going on?

When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.

So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE, UPDATE, INSERT or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).

That's why the solution involves declaring handlers to immediately ROLLBACK when an error happens.

Extra

Inside the handler you can also re-raise the error using RESIGNAL, otherwise the stored procedure executes "Successfully"

BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
        BEGIN
            ROLLBACK;
            RESIGNAL;
        END;

    START TRANSACTION;
        #.. Query 1 ..
        #.. Query 2 ..
        #.. Query 3 ..
    COMMIT;
END

Is it possible to write to the console in colour in .NET?

Yes. See this article. Here's an example from there:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");

enter image description here

How do I make the scrollbar on a div only visible when necessary?

You can try with below one:

  <div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>

Creating runnable JAR with Gradle

Both JB Nizet and Jorge_B's answers are correct.

In its simplest form, creating an executable JAR with Gradle is just a matter of adding the appropriate entries to the manifest. However, it's much more common to have dependencies that need to be included on the classpath, making this approach tricky in practice.

The application plugin provides an alternate approach; instead of creating an executable JAR, it provides:

  • a run task to facilitate easily running the application directly from the build
  • an installDist task that generates a directory structure including the built JAR, all of the JARs that it depends on, and a startup script that pulls it all together into a program you can run
  • distZip and distTar tasks that create archives containing a complete application distribution (startup scripts and JARs)

A third approach is to create a so-called "fat JAR" which is an executable JAR that includes not only your component's code, but also all of its dependencies. There are a few different plugins that use this approach. I've included links to a few that I'm aware of; I'm sure there are more.

Swift - Integer conversion to Hours/Minutes/Seconds

convert a number into time as a string

func convertToHMS(number: Int) -> String {
  let hour    = number / 3600;
  let minute  = (number % 3600) / 60;
  let second = (number % 3600) % 60 ;
  
  var h = String(hour);
  var m = String(minute);
  var s = String(second);
  
  if h.count == 1{
      h = "0\(hour)";
  }
  if m.count == 1{
      m = "0\(minute)";
  }
  if s.count == 1{
      s = "0\(second)";
  }
  
  return "\(h):\(m):\(s)"
}
print(convertToHMS(number:3900))

dplyr mutate with conditional values

It looks like derivedFactor from the mosaic package was designed for this. In this example, it would look something like:

library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
    "1" = (V1==1 & V2!=4),
    "2" = (V2==4 & V3!=1),
    .method = "first",
    .default = 0
    ))

(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor with an as.numeric.)

Note that the .default option combined with .method = "first" sets the "else" condition -- this approach is described in the help file for derivedFactor.

How to remove the first and the last character of a string

You could regex it:

"string".replace(/^\/?|\/?$/, "")
"/installers/services/".replace(/^\/?|\/?$/, "") // -> installers/services

The regex explained:
- Optional first slash: ^/?, escaped -> ^\/? (the ^ means beginning of string)
- The pipe ( | ) can be read as or
- Than the option slash at the end -> /?$, escaped -> \/?$ ( the $ means end of string)

Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash

Mocking Extension Methods with Moq

I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.

See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.

Turn off display errors using file "php.ini"

Let me quickly summarize this for reference:

  • error_reporting() adapts the currently active setting for the default error handler.

  • Editing the error reporting ini options also changes the defaults.

    • Here it's imperative to edit the correct php.ini version - it's typically /etc/php5/fpm/php.ini on modern servers, /etc/php5/mod_php/php.ini alternatively; while the CLI version has a distinct one.

    • Alternatively you can use depending on SAPI:

      • mod_php: .htaccess with php_flag options
      • FastCGI: commonly a local php.ini
      • And with PHP above 5.3 also a .user.ini

    • Restarting the webserver as usual.

If your code is unwieldy and somehow resets these options elsewhere at runtime, then an alternative and quick way is to define a custom error handler that just slurps all notices/warnings/errors up:

set_error_handler(function(){});

Again, this is not advisable, just an alternative.

What is the best way to concatenate two vectors?

All the solutions are correct, but I found it easier just write a function to implement this. like this:

template <class T1, class T2>
void ContainerInsert(T1 t1, T2 t2)
{
    t1->insert(t1->end(), t2->begin(), t2->end());
}

That way you can avoid the temporary placement like this:

ContainerInsert(vec, GetSomeVector());

How to get the position of a character in Python?

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:

path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')]

How to draw a filled triangle in android canvas?

Ok I've done it. I'm sharing this code in case someone else will need it:

super.draw(canvas, mapView, true);

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);     
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);

Point point1_draw = new Point();        
Point point2_draw = new Point();    
Point point3_draw = new Point();

mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);

Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();

canvas.drawPath(path, paint);

//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);

return true;

Thanks for the hint Nicolas!

Why is my CSS bundling not working with a bin deployed MVC4 app?

I had this issue while adding some packages from nuget and forgot to do an update

So first do an update of all packages installed in the project

Update-Package

In the Global.asax.cs add the following

BundleTable.EnableOptimizations = true;

How can I generate an ObjectId with mongoose?

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.

You can read more about the Types object at Mongoose#Types documentation.

Could not find any resources appropriate for the specified culture or the neutral culture

It happens because the *.res? is excluded from migration.

  • Right click on your ResourceFile
  • Click on the menu item "Include in project"

Remove trailing comma from comma-separated string

Or something like this:

private static String myRemComa(String input) { 
        String[] exploded = input.split(",");
        input="";
        boolean start = true;
        for(String str : exploded) {

         str=str.trim();
         if (str.length()>0) {
             if (start) {
                 input = str;
                    start = false;
                } else {
                    input = input + "," + str;
                }
         }
        }

        return input;
    }

What does "implements" do on a class?

Interfaces are implemented through classes. They are purely abstract classes, if you will.

In PHP when a class implements from an interface, the methods defined in that interface are to be strictly followed. When a class inherits from a parent class, method parameters may be altered. That is not the case for interfaces:

interface ImplementMeStrictly {
   public function foo($a, $b);
}

class Obedient implements ImplementMeStrictly {
   public function foo($a, $b, $c) 
      {
      }
}

will cause an error, because the interface wasn't implemented as defined. Whereas:

class InheritMeLoosely {
   public function foo($a)
      {
      }
}

class IDoWhateverWithFoo extends InheritMeLoosely {
   public function foo()
      {
      }
}

Is allowed.

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

i don't know if it's the answer to your question but you can try setting the background color in the xml layout like this. It is easy, it always works

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

 android:background="0xfff00000"

  >


<TextView

    android:id="@+id/text_view"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />



</LinearLayout>

You can also do more fancy things with backgrounds by creating an xml background file with gradients which are cool and semi transparent, and refer to it for other use see example below:

the background.xml layout

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <gradient
            android:angle="90"
            android:startColor="#f0000000"
            android:endColor="#ff444444"
            android:type="linear" />
    </shape>
</item>
</selector>

your layout

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

 android:background="@layout/background"


    >


<TextView

    android:id="@+id/text_view"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />



</LinearLayout>

Splitting a string into chunks of a certain size

Modified (now it accepts any non null string and any positive chunkSize) Konstantin Spirin's solution:

public static IEnumerable<String> Split(String value, int chunkSize) {
  if (null == value)
    throw new ArgumentNullException("value");
  else if (chunkSize <= 0)
    throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");

  return Enumerable
    .Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
    .Select(index => (index + 1) * chunkSize < value.Length 
      ? value.Substring(index * chunkSize, chunkSize)
      : value.Substring(index * chunkSize));
}

Tests:

  String source = @"ABCDEF";

  // "ABCD,EF"
  String test1 = String.Join(",", Split(source, 4));
  // "AB,CD,EF"
  String test2 = String.Join(",", Split(source, 2));
  // "ABCDEF"
  String test3 = String.Join(",", Split(source, 123));

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

If @Region is not a null value (lets say @Region = 'South') it will not return rows where the Region field is null, regardless of the value of ANSI_NULLS.

ANSI_NULLS will only make a difference when the value of @Region is null, i.e. when your first query essentially becomes the second one.

In that case, ANSI_NULLS ON will not return any rows (because null = null will yield an unknown boolean value (a.k.a. null)) and ANSI_NULLS OFF will return any rows where the Region field is null (because null = null will yield true)

How to unset (remove) a collection element after fetching it?

If you know the key which you unset then put directly by comma separated

unset($attr['placeholder'], $attr['autocomplete']);

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

Display Adobe pdf inside a div

may be you can do by using AJAX or jquery...
just send that file url on one page and then open like normally open pdf file in that page and use ajax.

1)so as soon as user will click on the button. then u call that function in which u above tast. So by this way there will be only one page and by that you can show as many pdf without refreshing page.

2) if u don't have many pdf and if u don't know then just upload that file on google docs and then just put the share link file....and then just use ajax or jquery.

i prefer jquery if u don't have use AJAX.

How to clear text area with a button in html using javascript?

Change in your html with adding the function on the button click

 <input type="button" value="Clear" onclick="javascript:eraseText();"> 
    <textarea id='output' rows=20 cols=90></textarea>

Try this in your js file:

function eraseText() {
    document.getElementById("output").value = "";
}

Converting Python dict to kwargs?

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

ssh remote host identification has changed

Use this command:

truncate -s 0 /home/SYSTEM_NAME/.ssh/known_hosts

How can I check if a var is a string in JavaScript?

The typeof operator isn't an infix (so the LHS of your example doesn't make sense).

You need to use it like so...

if (typeof a_string == 'string') {
    // This is a string.
}

Remember, typeof is an operator, not a function. Despite this, you will see typeof(var) being used a lot in the wild. This makes as much sense as var a = 4 + (1).

Also, you may as well use == (equality comparison operator) since both operands are Strings (typeof always returns a String), JavaScript is defined to perform the same steps had I used === (strict comparison operator).

As Box9 mentions, this won't detect a instantiated String object.

You can detect for that with....

var isString = str instanceof String;

jsFiddle.

...or...

var isString = str.constructor == String;

jsFiddle.

But this won't work in a multi window environment (think iframes).

You can get around this with...

var isString = Object.prototype.toString.call(str) == '[object String]';

jsFiddle.

But again, (as Box9 mentions), you are better off just using the literal String format, e.g. var str = 'I am a string';.

Further Reading.

Python: convert string to byte array

This work in both Python 2 and 3:

>>> bytearray(b'ABCD')
bytearray(b'ABCD')

Note string started with b.

To get individual chars:

>>> print("DEC HEX ASC")
... for b in bytearray(b'ABCD'):
...     print(b, hex(b), chr(b))
DEC HEX ASC
65 0x41 A
66 0x42 B
67 0x43 C
68 0x44 D

Hope this helps

How do I inject a controller into another controller in AngularJS

If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require a controller (instance of a component) from a another component that follows a certain hierarchy.

For example:

//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
  ...,
  controller : function WizardController() {
    this.disableNext = function() { 
      //disable next step... some implementation to disable the next button hosted by the wizard
    }
  },
  ...
});

//some child component
myModule.component('onboardingStep', {
 ...,
 controller : function OnboadingStepController(){

    this.$onInit = function() {
      //.... you can access this.container.disableNext() function
    }

    this.onChange = function(val) {
      //..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
      if(notIsValid(val)){
        this.container.disableNext();
      }
    }
 },
 ...,
 require : {
    container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
 },
 ...
});

Now the usage of these above components might be something like this:

<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->

<on-boarding-step ...>
 <!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>

There are many ways you can set up require.

(no prefix) - Locate the required controller on the current element. Throw an error if not found.

? - Attempt to locate the required controller or pass null to the link fn if not found.

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

^^ - Locate the required controller by searching the element's parents. Throw an error if not found.

?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.

?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.



Old Answer:

You need to inject $controller service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.

Example:

app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
   var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
   //Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
   //In this case it is the child scope of this scope.
   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });
   testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);

In any case you cannot call TestCtrl1.myMethod() because you have attached the method on the $scope and not on the controller instance.

If you are sharing the controller, then it would always be better to do:-

.controller('TestCtrl1', ['$log', function ($log) {
    this.myMethod = function () {
        $log.debug("TestCtrl1 - myMethod");
    }
}]);

and while consuming do:

.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
     var testCtrl1ViewModel = $controller('TestCtrl1');
     testCtrl1ViewModel.myMethod();
}]);

In the first case really the $scope is your view model, and in the second case it the controller instance itself.

Insert into ... values ( SELECT ... FROM ... )

In informix it works as Claude said:

INSERT INTO table (column1, column2) 
VALUES (value1, value2);    

Is it possible to get multiple values from a subquery?

A Subquery in the Select clause, as in your case, is also known as a Scalar Subquery, which means that it's a form of expression. Meaning that it can only return one value.

I'm afraid you can't return multiple columns from a single Scalar Subquery, no.

Here's more about Oracle Scalar Subqueries:

http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions010.htm#i1033549

How to update ruby on linux (ubuntu)?

Generally the verions of programs are linked to the version of your operating system. So if you were running gutsy you would either have to upgrade to the new jaunty jackalope version which has ruby 1.9 or add the respoistories for jaunty to your /etc/apt/sources.list file. Once you have done that you can start up the synaptic package manager and you should see it in there.

1067 error on attempt to start MySQL

I run MariaDB (MySQL compatible) on two machines locally. I'm not sure what prompted the error and nothing I tried worked. So I stopped the service, deleted everything in MariaDB's directory (except the data directory) and copied the files from my secondary machine and everything is working well enough as far as I can tell.

For a live server it'd be a bit different and a super-guru might be able to add an insight comment (e.g. something outside of the data directory might have something to do with preventing data corruption or indexes in example?). I would just stop the service and copy the entire directory once every month or so and then start the service again.

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Converting a double to an int in Javascript without rounding

Use parseInt().

var num = 2.9
console.log(parseInt(num, 10)); // 2

You can also use |.

var num = 2.9
console.log(num | 0); // 2

Changing Font Size For UITableView Section Headers

Swift 4 version of Leo Natan answer is

UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)

If you wanted to set a custom font you could use

if let font = UIFont(name: "font-name", size: 12) {
    UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}

How do I do a Date comparison in Javascript?

I would rather use the Date valueOf method instead of === or !==

Seems like === is comparing internal Object's references and nothing concerning date.

Calculating distance between two geographic locations

Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.

Location selected_location = new Location("locationA");
            selected_location.setLatitude(17.372102);
            selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
            near_locations.setLatitude(17.375775);
            near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);

here "distance" is distance between locationA & locationB (in Meters)

How to split a comma-separated value to columns

I think this is cool

SELECT value,
    PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
    PARSENAME(REPLACE(String,',','.'),1) 'Sur Name'
FROM table WITH (NOLOCK)

Mysql service is missing

I also face the same problem. do the simple steps

  1. Go to bin directory copy the path and set it as a environment variable.
  2. Run the command prompt as admin and cd to bin directory:
  3. Run command : mysqld –install
  4. Now the services are successfully installed
  5. Start the service in service windows of os
  6. Type mysql and go

httpd-xampp.conf: How to allow access to an external IP besides localhost?

In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .

i hope this will resolve your problem

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

HTML -- two tables side by side

You can place your tables in a div and add style to your table "float: left"

<div>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
  <table style="float: left">
    <tr>
      <td>..</td>
    </tr>
  </table>
</div>

or simply use css:

div>table {
  float: left
}

How to check Oracle database for long running queries

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

jQuery vs document.querySelectorAll

$("#id") vs document.querySelectorAll("#id")

The deal is with the $() function it makes an array and then breaks it up for you but with document.querySelectorAll() it makes an array and you have to break it up.

How do I use WPF bindings with RelativeSource?

This is an example of the use of this pattern that worked for me on empty datagrids.

<Style.Triggers>
    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
        <Setter Property="Background">
            <Setter.Value>
                <VisualBrush Stretch="None">
                    <VisualBrush.Visual>
                        <TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Setter.Value>
        </Setter>
    </DataTrigger>
</Style.Triggers>

set up device for development (???????????? no permissions)

Nothing worked for me until I finally found the answer here: http://ptspts.blogspot.co.il/2011/10/how-to-fix-adb-no-permissions-error-on.html

I'm copying the text here in case it disappears in the future.

Create a file named /tmp/android.rules with the following contents (hex vendor numbers were taken from the vendor list page):

SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0e79", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0502", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0b05", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="413c", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0489", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="091e", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="12d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="24e3", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2116", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0482", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="17ef", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1004", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="22b8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0409", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2080", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2257", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="10a9", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1d4d", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0471", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04da", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="05c6", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1f53", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04e8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04dd", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0fce", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0930", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="19d2", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1bbb", MODE="0666"

Run the following commands:

sudo cp /tmp/android.rules /etc/udev/rules.d/51-android.rules
sudo chmod 644   /etc/udev/rules.d/51-android.rules
sudo chown root. /etc/udev/rules.d/51-android.rules
sudo service udev restart
sudo killall adb

Disconnect the USB cable between the phone and the computer.

Reconnect the phone.

Run adb devices to confirm that now it has permission to access the phone.

Please note that it's possible to use , USER="$LOGINNAME" instead of , MODE="0666" in the .rules file, substituting $LOGINNAME for your login name, i.e. what id -nu prints.

In some cases it can be necessary to give the udev rules file a name that sorts close to the end, such as z51-android.rules.

Why use 'virtual' for class properties in Entity Framework model definitions?

I understand the OPs frustration, this usage of virtual is not for the templated abstraction that the defacto virtual modifier is effective for.

If any are still struggling with this, I would offer my view point, as I try to keep the solutions simple and the jargon to a minimum:

Entity Framework in a simple piece does utilize lazy loading, which is the equivalent of prepping something for future execution. That fits the 'virtual' modifier, but there is more to this.

In Entity Framework, using a virtual navigation property allows you to denote it as the equivalent of a nullable Foreign Key in SQL. You do not HAVE to eagerly join every keyed table when performing a query, but when you need the information -- it becomes demand-driven.

I also mentioned nullable because many navigation properties are not relevant at first. i.e. In a customer / Orders scenario, you do not have to wait until the moment an order is processed to create a customer. You can, but if you had a multi-stage process to achieve this, you might find the need to persist the customer data for later completion or for deployment to future orders. If all nav properties were implemented, you'd have to establish every Foreign Key and relational field on the save. That really just sets the data back into memory, which defeats the role of persistence.

So while it may seem cryptic in the actual execution at run time, I have found the best rule of thumb to use would be: if you are outputting data (reading into a View Model or Serializable Model) and need values before references, do not use virtual; If your scope is collecting data that may be incomplete or a need to search and not require every search parameter completed for a search, the code will make good use of reference, similar to using nullable value properties int? long?. Also, abstracting your business logic from your data collection until the need to inject it has many performance benefits, similar to instantiating an object and starting it at null. Entity Framework uses a lot of reflection and dynamics, which can degrade performance, and the need to have a flexible model that can scale to demand is critical to managing performance.

To me, that always made more sense than using overloaded tech jargon like proxies, delegates, handlers and such. Once you hit your third or fourth programming lang, it can get messy with these.

Angular - "has no exported member 'Observable'"

use return Observable.of(HEROES);

Angular 4 img src is not found

Check in your.angular-cli.json under app -> assets:[] if you have included assets folder.

Or perhaps something here: https://github.com/angular/angular-cli/issues/2231, can help.

jquery: change the URL address without redirecting?

You can't do what you ask (and the linked site does not do exactly that either).

You can, however, modify the part of the url after the # sign, which is called the fragment, like this:

window.location.hash = 'something';

Fragments do not get sent to the server (so, for example, Google itself cannot tell the difference between http://www.google.com/ and http://www.google.com/#something), but they can be read by Javascript on your page. In turn, this Javascript can decide to perform a different AJAX request based on the value of the fragment, which is how the site you linked to probably does it.

ComboBox.SelectedText doesn't give me the SelectedText

To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:

string myItem = comboBox1.SelectedItem.ToString(); //this does the trick

How to Set Opacity (Alpha) for View in Android

For API < 11 for textView color I did the following:

int textViewColor = textView.getTextColors().getDefaultColor(); 
textView.setTextColor(Color.argb(128, Color.red(textViewColor), Color.green(textViewColor), Color.blue(textViewColor))); //50% transparent

A little cumbersome, but hey, it works :-)

Android replace the current fragment with another fragment

Latest Stuff

Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

  1. Add Kotlin extension for Fragments to your project.

In your app level build.gradle file add the following,

dependencies {
    def fragment_version = "1.2.5"

    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
  1. Then simple code to replace the fragment,

In your activity

supportFragmentManager.commit {
    replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
    addToBackStack(null)
}

References

Check latest version of Fragment extension

More on Fragments

Protect image download

As other answers said, if you can see it you can copy/download it.

To add up to the other answers, just for your information, you can add invisible or tricky watermarks to your images: http://www.cgrats.com/create-an-invisible-watermark-in-photoshop.html (just an example, there are more techniques, just google for invisible watermarks)

Anyway if you want to prove the ownership of your image a good way is to have a bigger resolution copy for yourself, and always publish a lower resolution / size one. Or publish it also on a "public" media like ... deviantart or flickr or something where people can't change the upload date. This way you can prove you had that image before anybody else

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

How to get the Development/Staging/production Hosting Environment in ConfigureServices

You can easily access it in ConfigureServices, just persist it to a property during Startup method which is called first and gets it passed in, then you can access the property from ConfigureServices.

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
    ...your code here...
    CurrentEnvironment = env;
}

private IHostingEnvironment CurrentEnvironment{ get; set; } 

public void ConfigureServices(IServiceCollection services)
{
    string envName = CurrentEnvironment.EnvironmentName;
    ... your code here...
}

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

Auto-refreshing div with jQuery - setTimeout or another method?

$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  setInterval(function() {
    $('#notice_div').load('response.php');
  }, 3000); // the "3000" 
});

Does Android support near real time push notification?

If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).

If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.

You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

How to trigger an event after using event.preventDefault()

You can do something like

$(this).unbind('click').click();

How to install JDK 11 under Ubuntu?

Now it is possible to install openjdk-11 this way:

sudo apt-get install openjdk-11-jdk

(Previously it installed openjdk-10, but not anymore)

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

creating batch script to unzip a file without additional zip tools

Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.

Excel VBA code to copy a specific string to clipboard

To write text to (or read text from) the Windows clipboard use this VBA function:

Function Clipboard$(Optional s$)
    Dim v: v = s  'Cast to variant for 64-bit VBA support
    With CreateObject("htmlfile")
    With .parentWindow.clipboardData
        Select Case True
            Case Len(s): .setData "text", v
            Case Else:   Clipboard = .getData("text")
        End Select
    End With
    End With
End Function

'Three examples of copying text to the clipboard:
Clipboard "Excel Hero was here."
Clipboard var1 & vbLF & var2
Clipboard 123

'To read text from the clipboard:
MsgBox Clipboard

This is a solution that does NOT use MS Forms nor the Win32 API. Instead it uses the Microsoft HTML Object Library which is fast and ubiquitous and NOT deprecated by Microsoft like MS Forms. And this solution respects line feeds. This solution also works from 64-bit Office. Finally, this solution allows both writing to and reading from the Windows clipboard. No other solution on this page has these benefits.

Remove #N/A in vlookup result

If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.

=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))

or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.

=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")

in earlier versions you need to repeat the VLOOKUP, e.g.

=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))

Routing with multiple Get methods in ASP.NET Web API

  // this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
  // define two types of routes 1. DefaultActionApi  and 2. DefaultApi as below

   config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
   config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });

  // decorate the controller action method with [ActionName("Default")] which need to invoked with below url
  // http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
  // http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
  // http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller


 public class DemoController : ApiController
 {
    // Mark the method with ActionName  attribute (defined in MapRoutes) 
    [ActionName("Default")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
    }

    public HttpResponseMessage GetAll()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
    }

    public HttpResponseMessage GetById()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage DemoGet()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage CustomGetDetails()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
    }
}

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You can find more debugging info just simply adding the option -loglevel debug, full command will be

ffmpeg -i INPUT OUTPUT -loglevel debug -v verbose

Javascript : Send JSON Object with Ajax?

If you`re not using jQuery then please make sure:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

And for the php receiving end:

 $_POST['json_name'] 

using if else with eval in aspx page

If you are trying to bind is a Model class, you can add a new readonly property to it like:

public string FormattedPercentage
{
    get
    {
        If(this.Percentage < 50)
            return "0 %";
        else 
            return string.Format("{0} %", this.Percentage)        
     }
}

Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself

Can't create handler inside thread that has not called Looper.prepare()

Try this, when you see runtimeException due to Looper not prepared before handler.

Handler handler = new Handler(Looper.getMainLooper()); 

handler.postDelayed(new Runnable() {
  @Override
  public void run() {
  // Run your task here
  }
}, 1000 );

BehaviorSubject vs Observable?

app.component.ts

behaviourService.setName("behaviour");

behaviour.service.ts

private name = new BehaviorSubject("");
getName = this.name.asObservable();`

constructor() {}

setName(data) {
    this.name.next(data);
}

custom.component.ts

behaviourService.subscribe(response=>{
    console.log(response);    //output: behaviour
});

correct PHP headers for pdf file download

I had the same problem recently and this helped me:

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="FILENAME"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize("PATH/TO/FILE")); 
    ob_clean(); 
    flush(); 
    readfile(PATH/TO/FILE);      
    exit();

I found this answer here

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

How to make a WPF window be on top of all other windows of my app (not system wide)?

The best way is set this two events to all of windows of your app:

GotKeyboardFocus
LostKeyboardFocus

in this way:

WiondowOfMyApp_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
    windowThatShouldBeTopMost.TopMost = true;
}

WiondowOfMyApp_LostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
    windowThatShouldBeTopMost.TopMost = false;
}
  • and surely all of the windows that you wanted to be top, should be accessible from other windows of your app. in my case I have a base window and another some windows that should be top of my base window, so this was not bad to my base window has instance of each another windows.

C++ convert hex string to signed integer

This worked for me:

string string_test = "80123456";
unsigned long x;
signed long val;

std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val;  // if I try this val = 0
val = (signed long)x;  // However, if I cast the unsigned result I get val = 0x80123456 

Progress during large file copy (Copy-Item & Write-Progress?)

Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:

  1. I really liked Graham's command with time estimations and speed readings.
  2. I also really liked the significant speed increase of using BITS as my transfer method.

Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.

function Copy-File {
    # ref: https://stackoverflow.com/a/55527732/3626361
    param([string]$From, [string]$To)

    try {
        $job = Start-BitsTransfer -Source $From -Destination $To `
            -Description "Moving: $From => $To" `
            -DisplayName "Backup" -Asynchronous

        # Start stopwatch
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        Write-Progress -Activity "Connecting..."

        while ($job.JobState.ToString() -ne "Transferred") {
            switch ($job.JobState.ToString()) {
                "Connecting" {
                    break
                }
                "Transferring" {
                    $pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
                    $elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000

                    if ($elapsed -eq 0) {
                        $xferrate = 0.0
                    }
                    else {
                        $xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
                    }

                    if ($job.BytesTransferred % 1mb -eq 0) {
                        if ($pctcomp -gt 0) {
                            $secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
                        }
                        else {
                            $secsleft = 0
                        }

                        Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
                            -PercentComplete $pctcomp `
                            -SecondsRemaining $secsleft
                    }
                    break
                }
                "Transferred" {
                    break
                }
                Default {
                    throw $job.JobState.ToString() + " unexpected BITS state."
                }
            }
        }

        $sw.Stop()
        $sw.Reset()
    }
    finally {
        Complete-BitsTransfer -BitsJob $job
        Write-Progress -Activity "Completed" -Completed
    }
}

ojdbc14.jar vs. ojdbc6.jar

Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet, OracleStatement) moved from package oracle.jdbc.driver to oracle.jdbc.

How to hide console window in python?

This will hide your console. Implement these lines in your code first to start hiding your console at first.

import win32gui, win32con

the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)

Update May 2020 :

If you've got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32.Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con.

To show back your program again win32con.SW_SHOW works fine:

win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)

MongoDB inserts float when trying to insert integer

If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.

var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)

Installation error: INSTALL_FAILED_OLDER_SDK

This means the version of android of your avd is older than the version being used to compile the code

How to print a string in C++

You need to access the underlying buffer:

printf("%s\n", someString.c_str());

Or better use cout << someString << endl; (you need to #include <iostream> to use cout)

Additionally you might want to import the std namespace using using namespace std; or prefix both string and cout with std::.

How to uncheck a radio button?

Just put the following code for jQuery :

jQuery("input:radio").removeAttr("checked");

And for javascript :

$("input:radio").removeAttr("checked");

There is no need to put any foreach loop , .each() fubction or any thing

Select first occurring element after another element

For your literal example you'd want to use the adjacent selector (+).

h4 + p {color:red}//any <p> that is immediately preceded by an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>

However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).

h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>

It's known to be buggy in IE 7+ unfortunately.

How to check if a file exists in a shell script

Here is an alternative method using ls:

(ls x.txt && echo yes) || echo no

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null:

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

SQL Server Management Studio alternatives to browse/edit tables and run queries

TOAD for MS SQL looks pretty good. I've never used it personally but I have used Quest's other products and they're solid.

Is it possible to make a Tree View with Angular?

Not complicated.

<div ng-app="Application" ng-controller="TreeController">
    <table>
        <thead>
            <tr>
                <th>col 1</th>
                <th>col 2</th>
                <th>col 3</th>
            </tr>
        </thead>
        <tbody ng-repeat="item in tree">
            <tr>
                <td>{{item.id}}</td>
                <td>{{item.fname}}</td>
                <td>{{item.lname}}</td>
            </tr>
            <tr ng-repeat="children in item.child">
                <td style="padding-left:15px;">{{children.id}}</td>
                <td>{{children.fname}}</td>
            </tr>
        </tbody>
     </table>
</div>

controller code:

angular.module("myApp", []).
controller("TreeController", ['$scope', function ($scope) {
    $scope.tree = [{
        id: 1,
        fname: "tree",
        child: [{
            id: 1,
            fname: "example"
        }],
        lname: "grid"
    }];


}]);

Key error when selecting columns in pandas dataframe after read_csv

The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':

You could also try:

import csv
import pandas as pd
import re
    with open (filename, "r") as file:
        df = pd.read_csv(file, delimiter = ",")
        df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
        print(df.columns)

How to run a task when variable is undefined in ansible?

Strictly stated you must check all of the following: defined, not empty AND not None.

For "normal" variables it makes a difference if defined and set or not set. See foo and bar in the example below. Both are defined but only foo is set.

On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz and xyz.msg in the example below:

cat > test.yml <<EOF
- hosts: 127.0.0.1

  vars:
    foo: ""          # foo is defined and foo == '' and foo != None
    bar:             # bar is defined and bar != '' and bar == None

  tasks:

  - debug:
      msg : ""
    register: xyz    # xyz is defined and xyz != '' and xyz != None
                     # xyz.msg is defined and xyz.msg == '' and xyz.msg != None

  - debug:
      msg: "foo is defined and foo == '' and foo != None"
    when: foo is defined and foo == '' and foo != None

  - debug:
      msg: "bar is defined and bar != '' and bar == None"
    when: bar is defined and bar != '' and bar == None

  - debug:
      msg: "xyz is defined and xyz != '' and xyz != None"
    when: xyz is defined and xyz != '' and xyz != None
  - debug:
      msg: "{{ xyz }}"

  - debug:
      msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
    when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
  - debug:
      msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml

Call one constructor from another

Yeah, you can call other method before of the call base or this!

public class MyException : Exception
{
    public MyException(int number) : base(ConvertToString(number)) 
    {
    }

    private static string ConvertToString(int number) 
    { 
      return number.toString()
    }

}

How do you get the magnitude of a vector in Numpy?

use the function norm in scipy.linalg (or numpy.linalg)

>>> from scipy import linalg as LA
>>> a = 10*NP.random.randn(6)
>>> a
  array([  9.62141594,   1.29279592,   4.80091404,  -2.93714318,
          17.06608678, -11.34617065])
>>> LA.norm(a)
    23.36461979210312

>>> # compare with OP's function:
>>> import math
>>> mag = lambda x : math.sqrt(sum(i**2 for i in x))
>>> mag(a)
     23.36461979210312

How to map with index in Ruby?

module Enumerable
  def map_with_index(&block)
    i = 0
    self.map { |val|
      val = block.call(val, i)
      i += 1
      val
    }
  end
end

["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]

Find index of a value in an array

int keyIndex = Array.FindIndex(words, w => w.IsKey);

That actually gets you the integer index and not the object, regardless of what custom class you have created

Do Java arrays have a maximum size?

Going by this article http://en.wikipedia.org/wiki/Criticism_of_Java#Large_arrays:

Java has been criticized for not supporting arrays of more than 231-1 (about 2.1 billion) elements. This is a limitation of the language; the Java Language Specification, Section 10.4, states that:

Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.

Supporting large arrays would also require changes to the JVM. This limitation manifests itself in areas such as collections being limited to 2 billion elements and the inability to memory map files larger than 2 GiB. Java also lacks true multidimensional arrays (contiguously allocated single blocks of memory accessed by a single indirection), which limits performance for scientific and technical computing.

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

Regex to get string between curly braces

You want to use regex lookahead and lookbehind. This will give you only what is inside the curly braces:

(?<=\{)(.*?)(?=\})

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

Accessing session from TWIG template

I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals() method. Rather than using $_SESSION, it's also better to use Symfony's Session class since it handles automatically starting/stopping the session.

I've got the following extension in /src/AppBundle/Twig/AppExtension.php:

<?php    
namespace AppBundle\Twig;

use Symfony\Component\HttpFoundation\Session\Session;

class AppExtension extends \Twig_Extension {

    public function getGlobals() {
        $session = new Session();
        return array(
            'session' => $session->all(),
        );
    }

    public function getName() {
        return 'app_extension';
    }
}

Then add this in /app/config/services.yml:

services:
    app.twig_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

Then the session can be accessed from any view using:

{{ session.my_variable }}

Android Studio - Importing external Library/Jar

you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.) http://developer.android.com/intl/es/sdk/installing/migrate.html

Auto detect mobile browser (via user-agent?)

for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM

 <script language="javascript"> <!--
     var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
              if (mobile) {
                  alert("MOBILE DEVICE DETECTED");
                  document.write("<b>------------------------------------------<br>")
                  document.write("<b>" + navigator.userAgent + "<br>")
                  document.write("<b>------------------------------------------<br>")
                  var userAgent = navigator.userAgent.toLowerCase();
                  if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
                         document.write("<b> ANDROID MOBILE <br>")
                   else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
                       document.write("<b> ANDROID TABLET <br>")
                   else if ((userAgent.search("blackberry") > -1))
                       document.write("<b> BLACKBERRY DEVICE <br>")
                   else if ((userAgent.search("iphone") > -1))
                       document.write("<b> IPHONE DEVICE <br>")              
                   else if ((userAgent.search("ipod") > -1))
                       document.write("<b> IPOD DEVICE <br>")
               else if ((userAgent.search("ipad") > -1))
                       document.write("<b> IPAD DEVICE <br>")
                       else
                   document.write("<b> UNKNOWN DEVICE <br>")
              }
              else
                  alert("NO MOBILE DEVICE DETECTED"); //--> </script>

Using %s in C correctly - very basic level

%s is the representation of an array of char

char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map

character = 'a'; // assign 'a' to character
printf("character %c  ",a); //we will display 'a' to stout

so string is an array of char we can assign multiple character per space of memory

string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends

this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined

toy can also assign values to the array of chars assigning it with functions like strcpy;

strcpy(string,"hello" );

this do the same as the example and automatically add the (char) 0 at the end

so if you print it with %S printf("my string %s",string);

and how string is a array we can just display part of it

//                         the array    one char
printf("first letter of wrd %s     is    :%c ",string,string[1]  );

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

I got trouble to get it so I post pictures showing different options:

Chrome 75.0.3770.142 [29 July 2018]

Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]

In tab Sources :

enter image description here

When button is activated, you can Pause On Caught Exceptions with the checkbox below: enter image description here


Previous versions

Chrome 32.0.1700.102 [03 feb 2014]

enter image description here

enter image description here enter image description here enter image description here

Chrome 27.0.1453.93 Stable

Debug options

Get list of passed arguments in Windows batch script (.bat)

The way to retrieve all the args to a script is here:

@ECHO off
ECHO The %~nx0 script args are...
for %%I IN (%*) DO ECHO %%I
pause

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

How to align iframe always in the center

If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:

html {
    width: 100%;
    height: 100%;
    display: table;
}

body {
    text-align: center;
    vertical-align: middle;
    display: table-cell;
}

And then the HTML is just:

<html>
  <body>
     <iframe ...></iframe>
  </body>
</html>

If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.

Fiddle.

Also this looks even simpler.

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

What is the most efficient way to loop through dataframes with pandas?

As @joris pointed out, iterrows is much slower than itertuples and itertuples is approximately 100 times fater than iterrows, and I tested speed of both methods in a DataFrame with 5027505 records the result is for iterrows, it is 1200it/s, and itertuples is 120000it/s.

If you use itertuples, note that every element in the for loop is a namedtuple, so to get the value in each column, you can refer to the following example code

>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]},
                      index=['a', 'b'])
>>> df
   col1  col2
a     1   0.1
b     2   0.2
>>> for row in df.itertuples():
...     print(row.col1, row.col2)
...
1, 0.1
2, 0.2

@UniqueConstraint annotation in Java

Way1 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})

-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

Way2 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

-- Here both column1 and column2 combined values acts as unique constraints

Convert from java.util.date to JodaTime

java.util.Date date = ...
DateTime dateTime = new DateTime(date);

Make sure date isn't null, though, otherwise it acts like new DateTime() - I really don't like that.

Configuring IntelliJ IDEA for unit testing with JUnit

Press Ctrl+Shift+T in the code editor. It will show you popup with suggestion to create a test.

Mac OS: ? Cmd+Shift+T

LOAD DATA INFILE Error Code : 13

If you are using XAMPP on Mac, this worked for me:

Moving the CSV/TXT file to /Applications/XAMPP/xamppfiles/htdocs/ as following

LOAD DATA LOCAL INFILE '/Applications/XAMPP/xamppfiles/htdocs/file.csv' INTO TABLE `tablename` FIELDS TERMINATED BY ',' LINES TERMINATED BY ';'

Powershell: Get FQDN Hostname

(Get-ADComputer $(hostname)).DNSHostName

Convert byte[] to char[]

byte[] a = new byte[50];

char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();

From the URL thedixon posted

http://bytes.com/topic/c-sharp/answers/250261-byte-char

You cannot ToCharArray the byte without converting it to a string first.

To quote Jon Skeet there

There's no need for the copying here - just use Encoding.GetChars. However, there's no guarantee that ASCII is going to be the appropriate encoding to use.

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

How can I perform a reverse string search in Excel without using VBA?

=RIGHT(TRIM(A1),LEN(TRIM(A1))-FIND(CHAR(7),SUBSTITUTE(" "&TRIM(A1)," ",CHAR(7),
LEN(TRIM(A1))-LEN(SUBSTITUTE(" "&TRIM(A1)," ",""))+1))+1)

This is very robust--it works for sentences with no spaces, leading/trailing spaces, multiple spaces, multiple leading/trailing spaces... and I used char(7) for the delimiter rather than the vertical bar "|" just in case that is a desired text item.

target="_blank" vs. target="_new"

This may have been asked before but:

"every link that specifies target="_new" looks for and finds that window by name, and opens in it.

If you use target="_blank," a brand new window will be created each time, on top of the current window."

from here: http://thedesignspace.net/MT2archives/000316.html

Python style - line continuation with strings?

Another possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))

Import data into Google Colaboratory

  1. You can mount to google drive by running following

    from google.colab import drive drive.mount('/content/drive')

  2. Afterwards For training copy data from gdrive to colab root folder.

!cp -r '/content/drive/My Drive/Project_data' '/content'

where first path is gdrive path and second is colab root folder.

This way training is faster for large data.

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

Replace line break characters with <br /> in ASP.NET MVC Razor view

Try the following:

@MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "<br />"))

Update:

According to marcind's comment on this related question, the ASP.NET MVC team is looking to implement something similar to the <%: and <%= for the Razor view engine.

Update 2:

We can turn any question about HTML encoding into a discussion on harmful user inputs, but enough of that already exists.

Anyway, take care of potential harmful user input.

@MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "<br />"))

Update 3 (Asp.Net MVC 3):

@Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "<br />"))

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

Fitting iframe inside a div

I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:

div {
    width: 100%;
    height: 0;
    padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
    position: relative;
}

div iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0;
    left: 0;
}

Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/

jquery if div id has children

You can also check whether div has specific children or not,

if($('#myDiv').has('select').length>0)
{
   // Do something here.
   console.log("you can log here");

}

Email Address Validation for ASP.NET

Preventing XSS is a different issue from validating input.

Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.

Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

Increase days to php current Date()

<?php
$dt = new DateTime;
if(isset($_GET['year']) && isset($_GET['week'])) {
    $dt->setISODate($_GET['year'], $_GET['week']);
} else {
    $dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>

<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a> 
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<table width="100%" style="height: 75px; border: 1px solid #00A2FF;">
<tr>
<td style="display: table-cell;
    vertical-align: middle;
    cursor: pointer;
    width: 75px;
    height: 75px;
    border: 4px solid #00A2FF;
    border-radius: 50%;">Employee</td>
<?php
do {
    echo "<td>" . $dt->format('M') . "<br>" . $dt->format('d M Y') . "</td>\n";
    $dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>

How to find time complexity of an algorithm

O(n) is big O notation used for writing time complexity of an algorithm. When you add up the number of executions in an algoritm you'll get an expression in result like 2N+2, in this expression N is the dominating term(the term having largest effect on expression if its value increases or decreases). Now O(N) is the time comlexity while N is dominating term. Example

For i= 1 to n;
  j= 0;
while(j<=n);
  j=j+1;

here total number of executions for inner loop are n+1 and total number of executions for outer loop are n(n+1)/2, so total number of executions for whole algorithm are n+1+n(n+1/2) = (n^2+3n)/2. here n^2 is the dominating term so the time complexity for this algorithm is O(n^2)

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

How to select different app.config for several build configurations

I have solved this topic with the solution I have found here: http://www.blackwasp.co.uk/SwitchConfig.aspx

In short what they state there is: "by adding a post-build event.[...] We need to add the following:

if "Debug"=="$(ConfigurationName)" goto :nocopy
del "$(TargetPath).config"
copy "$(ProjectDir)\Release.config" "$(TargetPath).config"
:nocopy

Jquery href click - how can I fire up an event?

You are binding the click event to anchors with an href attribute with value sign_new.

Either bind anchors with class sign_new or bind anchors with href value #sign_up. I would prefer the former.

Bootstrap Dropdown with Hover

Updated with a proper plugin

I have published a proper plugin for the dropdown hover functionality, in which you can even define what happens when clicking on the dropdown-toggle element:

https://github.com/istvan-ujjmeszaros/bootstrap-dropdown-hover


Why I made it, when there are many solutions already?

I had issues with all the previously existing solutions. The simple CSS ones are not using the .open class on the .dropdown, so there will be no feedback on the dropdown toggle element when the dropdown is visible.

The js ones are interfering with clicking on .dropdown-toggle, so the dropdown shows up on hover, then hides it when clicking on an opened dropdown, and moving out the mouse will trigger the dropdown to show up again. Some of the js solutions are braking iOS compatibility, some plugins are not working on modern desktop browsers which are supporting the touch events.

That's why I made the Bootstrap Dropdown Hover plugin which prevents all these issues by using only the standard Bootstrap javascript API, without any hack.

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

C# RSA encryption/decryption with transmission

I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:

        ...
        var signature = Get(url); // base64_encoded signature received from server
        var inputtext= "inputtext"; // this is main text signature was created for
        bool result = VerifySignature(inputtext, signature);
        ...

    private bool VerifySignature(string input, string signature)
    {
        var result = false;
        using (var cps=new RSACryptoServiceProvider())
        {
            // converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
            byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
            byte[] signatureBytes  = Convert.FromBase64String(signature);

            cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
            result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes  );
        }

        return result;
    }

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

VBA Go to last empty row

If you are certain that you only need column A, then you can use an End function in VBA to get that result.

If all the cells A1:A100 are filled, then to select the next empty cell use:

Range("A1").End(xlDown).Offset(1, 0).Select

Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.

If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:

Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select

Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.

Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select

The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.

Webdriver Screenshot

Use driver.save_screenshot('/path/to/file') or driver.get_screenshot_as_file('/path/to/file'):

import selenium.webdriver as webdriver
import contextlib

@contextlib.contextmanager
def quitting(thing):
    yield thing
    thing.quit()

with quitting(webdriver.Firefox()) as driver:
    driver.implicitly_wait(10)
    driver.get('http://www.google.com')
    driver.get_screenshot_as_file('/tmp/google.png') 
    # driver.save_screenshot('/tmp/google.png')

Resetting Select2 value in dropdown with reset button

You can also reset select2 value using

$(function() {
  $('#d').select2('data', null)
})

alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.

Double precision floating values in Python?

Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..

import random
from decimal import Decimal

GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)

How to tell if a file is git tracked (by shell exit code)?

EDIT

If you need to use git from bash there is --porcelain option to git status:

--porcelain

Give the output in a stable, easy-to-parse format for scripts. Currently this is identical to --short output, but is guaranteed not to change in the future, making it safe for scripts.

Output looks like this:

> git status --porcelain
 M starthudson.sh
?? bla

Or if you do only one file at a time:

> git status --porcelain bla
?? bla

ORIGINAL

do:

git status

You will see report stating which files were updated and which ones are untracked.

You can see bla.sh is tracked and modified and newbla is not tracked:

# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#       modified:   bla.sh
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       newbla
no changes added to commit (use "git add" and/or "git commit -a")

ComboBox: Adding Text and Value to an Item (no Binding Source)

I had the same problem, what I did was add a new ComboBox with just the value in the same index then the first one, and then when I change the principal combo the index in the second one change at same time, then I take the value of the second combo and use it.

This is the code:

public Form1()
{
    eventos = cliente.GetEventsTypes(usuario);

    foreach (EventNo no in eventos)
    {
        cboEventos.Items.Add(no.eventno.ToString() + "--" +no.description.ToString());
        cboEventos2.Items.Add(no.eventno.ToString());
    }
}

private void lista_SelectedIndexChanged(object sender, EventArgs e)
{
    lista2.Items.Add(lista.SelectedItem.ToString());
}

private void cboEventos_SelectedIndexChanged(object sender, EventArgs e)
{
    cboEventos2.SelectedIndex = cboEventos.SelectedIndex;
}

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

Prevent typing non-numeric in input type number

Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a

let lastCharacterEntered

outside of the input and then onKeyPress

e => {
          var allowedChars = "0123456789.";
          function contains(stringValue, charValue) {
            return stringValue.indexOf(charValue) > -1;
          }
          var invalidKey =
            (e.key.length === 1 && !contains(allowedChars, e.key)) ||
            (e.key === "." && contains(e.target.value, "."));
          console.log(e.target.value);
          invalidKey && e.preventDefault();
          if (!invalidKey) {
            if (lastCharacterEntered === "." && e.key === ".") {
              e.preventDefault();
            } else {
              lastCharacterEntered = e.key;
            }
          }
        }

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

Range of values in C Int and Long 32 - 64 bits

It is better to include stdlib.h. Since without stdlibg it takes long as long

PHP Checking if the current date is before or after a set date

I have used this one and it served the purpose:

if($date < date("Y-m-d") ) {
                echo "Date is in the past";}

BR

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

JavaFX open new window

I use the following method in my JavaFX applications.

newWindowButton.setOnMouseClicked((event) -> {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
        /* 
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 600, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }
});

How to create standard Borderless buttons (like in the design guideline mentioned)?

If you want to achieve the same programmatically :

(this is C# but easily transatable to Java)

Button button = new Button(new ContextThemeWrapper(Context, Resource.Style.Widget_AppCompat_Button_Borderless_Colored), null, Resource.Style.Widget_AppCompat_Button_Borderless_Colored);

Match

    <Button
       style="@style/Widget.AppCompat.Button.Borderless.Colored"
    .../>

Automatically size JPanel inside JFrame

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);

This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.

Jenkins restrict view of jobs per user

You can install "Extended Read Permission" plug-in. Then in either "Global Settings" or in individual job configuration, you can give the user "Extended Read" permission.

Why is exception.printStackTrace() considered bad practice?

You are touching multiple issues here:

1) A stack trace should never be visibile to end users (for user experience and security purposes)

Yes, it should be accessible to diagnose problems of end-users, but end-user should not see them for two reasons:

  • They are very obscure and unreadable, the application will look very user-unfriendly.
  • Showing a stack trace to end-user might introduce a potential security risk. Correct me if I'm wrong, PHP actually prints function parameters in stack trace - brilliant, but very dangerous - if you would you get exception while connecting to the database, what are you likely to in the stacktrace?

2) Generating a stack trace is a relatively expensive process (though unlikely to be an issue in most 'exception'al circumstances)

Generating a stack trace happens when the exception is being created/thrown (that's why throwing an exception comes with a price), printing is not that expensive. In fact you can override Throwable#fillInStackTrace() in your custom exception effectively making throwing an exception almost as cheap as a simple GOTO statement.

3) Many logging frameworks will print the stack trace for you (ours does not and no, we can't change it easily)

Very good point. The main issue here is: if the framework logs the exception for you, do nothing (but make sure it does!) If you want to log the exception yourself, use logging framework like Logback or Log4J, to not put them on the raw console because it is very hard to control it.

With logging framework you can easily redirect stack traces to file, console or even send them to a specified e-mail address. With hardcoded printStackTrace() you have to live with the sysout.

4) Printing the stack trace does not constitute error handling. It should be combined with other information logging and exception handling.

Again: log SQLException correctly (with the full stack trace, using logging framework) and show nice: "Sorry, we are currently not able to process your request" message. Do you really think the user is interested in the reasons? Have you seen StackOverflow error screen? It's very humorous, but does not reveal any details. However it ensures the user that the problem will be investigated.

But he will call you immediately and you need to be able to diagnose the problem. So you need both: proper exception logging and user-friendly messages.


To wrap things up: always log exceptions (preferably using logging framework), but do not expose them to the end-user. Think carefully and about error-messages in your GUI, show stack traces only in development mode.

What's the difference between Docker Compose vs. Dockerfile

Dockerfiles are to build an image for example from a bare bone Ubuntu, you can add mysql called mySQL on one image and mywordpress on a second image called mywordpress.

Compose YAML files are to take these images and run them cohesively. For example, if you have in your docker-compose.yml file a service called db:

services:
   db:
     image: mySQL  --- image that you built.

and a service called wordpress such as:

wordpress: 
    image: mywordpress

then inside the mywordpress container you can use db to connect to your mySQL container. This magic is possible because your docker host create a network bridge (network overlay).