Programs & Examples On #Roleprovider

Built-in and custom implementations of ASP.NET's Role Provider, as part of Membership functionality in the System.Web.Security namespace.

The Role Manager feature has not been enabled

I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.

Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:

  1. Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
  2. Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
  3. Click on the Install button in both of them and close the NuGet window;
  4. Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:

    <roleManager defaultProvider="DefaultRoleProvider">
        <providers>
           <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
        </providers>
    </roleManager>
    
  5. Add enabled="true" like so:

    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
    
  6. Press F6 to Build and now it should be OK to proceed to a database update without having that exception:

    1. Press Ctrl+Q, type manager, click on "Package Manager Console";
    2. Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
    3. Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

I had the same error and I started the SQL Server Express service and it worked. Hope this helps.

Simple way to repeat a string

Consolidated for quick reference:

public class StringRepeat {

// Java 11 has built-in method - str.repeat(3);
// Apache - StringUtils.repeat(3);
// Google - Strings.repeat("",n);
// System.arraycopy

static String repeat_StringBuilderAppend(String str, int n) {

    if (str == null || str.isEmpty())
        return str;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
        sb.append(str);
    }
    return sb.toString();
}

static String repeat_ArraysFill(String str, int n) {
    String[] strs = new String[n];
    Arrays.fill(strs, str);
    return Arrays.toString(strs).replaceAll("\\[|\\]|,| ", "");
}

static String repeat_Recursion(String str, int n) {
    if (n <= 0)
        return "";
    else
        return str + repeat_Recursion(str, n - 1);
}

static String repeat_format1(String str, int n) {
    return String.format(String.format("%%%ds", n), " ").replace(" ", str);
}

static String repeat_format2(String str, int n) {
    return new String(new char[n]).replace("\0", str);
}

static String repeat_format3(String str, int n) {
    return String.format("%0" + n + "d", 0).replace("0", str);
}

static String repeat_join(String str, int n) {
    return String.join("", Collections.nCopies(n, str));
}

static String repeat_stream(String str, int n) {
    return Stream.generate(() -> str).limit(n).collect(Collectors.joining());
}

public static void main(String[] args) {
    System.out.println(repeat_StringBuilderAppend("Mani", 3));
    System.out.println(repeat_ArraysFill("Mani", 3));
    System.out.println(repeat_Recursion("Mani", 3));
    System.out.println(repeat_format1("Mani", 3));
    System.out.println(repeat_format2("Mani", 3));
    System.out.println(repeat_format3("Mani", 3));
    System.out.println(repeat_join("Mani", 3));
    System.out.println(repeat_stream("Mani", 3));

}

}

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

C#: Looping through lines of multiline string

Here's a quick code snippet that will find the first non-empty line in a string:

string line1;
while (
    ((line1 = sr.ReadLine()) != null) &&
    ((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }

if(line1 == null){ /* Error - no non-empty lines in string */ }

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

CustomErrors mode="Off"

If you're using the MVC preview 4, you could be experiencing this because you're using the HandleErrorAttribute. The behavior changed in 5 so that it doesn't handle exceptions if you turn off custom errors.

Is it possible to get all arguments of a function as single object inside that function?

In ES6 you can do something like this:

_x000D_
_x000D_
function foo(...args) _x000D_
{_x000D_
   let [a,b,...c] = args;_x000D_
_x000D_
   console.log(a,b,c);_x000D_
}_x000D_
_x000D_
_x000D_
foo(1, null,"x",true, undefined);
_x000D_
_x000D_
_x000D_

Overflow Scroll css is not working in the div

You are missing the height CSS property.

Adding it you will notice that scroll bar will appear.

.wrapper{ 
    // width: 1000px;
    width:600px; 
    overflow-y:scroll; 
    position:relative;
    height: 300px;
}

JSFIDDLE

From documentation:

overflow-y

The overflow-y CSS property specifies whether to clip content, render a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

This is a straightforward example Ravi Wallau's solution:

public String buildSafeURL(String partialURL, String documentName)
        throws ScriptException {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager
            .getEngineByName("JavaScript");

    String urlSafeDocumentName = String.valueOf(scriptEngine
            .eval("encodeURIComponent('" + documentName + "')"));
    String safeURL = partialURL + urlSafeDocumentName;

    return safeURL;
}

public static void main(String[] args) {
    EncodeURIComponentDemo demo = new EncodeURIComponentDemo();
    String partialURL = "https://www.website.com/document/";
    String documentName = "Tom & Jerry Manuscript.pdf";

    try {
        System.out.println(demo.buildSafeURL(partialURL, documentName));
    } catch (ScriptException se) {
        se.printStackTrace();
    }
}

Output: https://www.website.com/document/Tom%20%26%20Jerry%20Manuscript.pdf

It also answers the hanging question in the comments by Loren Shqipognja on how to pass a String variable to encodeURIComponent(). The method scriptEngine.eval() returns an Object, so it can converted to String via String.valueOf() among other methods.

Trim Cells using VBA in Excel

Works fine for me with one change - fourth line should be:

cell.Value = Trim(cell.Value)

Edit: If it appears to be stuck in a loop, I'd add

Debug.Print cell.Address

inside your For ... Next loop to get a bit more info on what's happening.

I also suspect that Trim only strips spaces - are you sure you haven't got some other kind of non-display character in there?

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I also faced the same issue. But I forgot to add google-services.json in my project. You can get this file from Google.

'\r': command not found - .bashrc / .bash_profile

In EditPlus you do this from the Document ? File Format (CR/LF) ? Change File Format... menu and then choose the Unix / Mac OS X radio button.

React js onClick can't pass value to method

I realize this is pretty late to the party, but I think a much simpler solution could satisfy many use cases:

    handleEdit(event) {
        let value = event.target.value;
    }

    ...

    <button
        value={post.id}
        onClick={this.handleEdit} >Edit</button>

I presume you could also use a data- attribute.

Simple, semantic.

How to set connection timeout with OkHttp

This worked for me:

OkHttpClient client = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .retryOnConnectionFailure(false) <-- not necessary but useful!
    .build();

Source: https://github.com/square/okhttp/issues/3553

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Fixed width buttons with Bootstrap

Expanding @kravits88 answer:

This will stretch the buttons to fit whole width:

<div className="btn-group-justified">
<div className="btn-group">
  <button type="button" className="btn btn-primary">SAVE MY DEAR!</button>
</div>
<div className="btn-group">
  <button type="button" className="btn btn-default">CANCEL</button>
</div>
</div>

How to detect lowercase letters in Python?

To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:
    if c.islower():
         print c

Note that in Python 3 you should use print(c) instead of print c.


Possibly ending up with assigning those letters to a different variable.

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'

How to get the selected radio button’s value?

Here is an Example for Radios where no Checked="checked" attribute is used

function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {       
    if (radios[i].checked) {
        alert(radios[i].value);
        found = 0;
        break;
    }
}
   if(found == 1)
   {
     alert("Please Select Radio");
   }    
}

DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]

Source : http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html

How to wait until an element exists?

Here is a core JavaScript function to wait for the display of an element (well, its insertion into the DOM to be more accurate).

// Call the below function
waitForElementToDisplay("#div1",function(){alert("Hi");},1000,9000);

function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
  var startTimeInMs = Date.now();
  (function loopSearch() {
    if (document.querySelector(selector) != null) {
      callback();
      return;
    }
    else {
      setTimeout(function () {
        if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
          return;
        loopSearch();
      }, checkFrequencyInMs);
    }
  })();
}

This call will look for the HTML tag whose id="div1" every 1000 milliseconds. If the element is found, it will display an alert message Hi. If no element is found after 9000 milliseconds, this function stops its execution.

Parameters:

  1. selector: String : This function looks for the element ${selector}.
  2. callback: Function : This is a function that will be called if the element is found.
  3. checkFrequencyInMs: Number : This function checks whether this element exists every ${checkFrequencyInMs} milliseconds.
  4. timeoutInMs : Number : Optional. This function stops looking for the element after ${timeoutInMs} milliseconds.

NB : Selectors are explained at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

What is Cache-Control: private?

To answer your question about why caching is working, even though the web-server didn't include the headers:

  • Expires: [a date]
  • Cache-Control: max-age=[seconds]

The server kindly asked any intermediate proxies to not cache the contents (i.e. the item should only be cached in a private cache, i.e. only on your own local machine):

  • Cache-Control: private

But the server forgot to include any sort of caching hints:

  • they forgot to include Expires, so the browser knows to use the cached copy until that date
  • they forgot to include Max-Age, so the browser knows how long the cached item is good for
  • they forgot to include E-Tag, so the browser can do a conditional request

But they did include a Last-Modified date in the response:

Last-Modified: Tue, 16 Oct 2012 03:13:38 GMT

Because the browser knows the date the file was modified, it can perform a conditional request. It will ask the server for the file, but instruct the server to only send the file if it has been modified since 2012/10/16 3:13:38:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

The server receives the request, realizes that the client has the most recent version already. Rather than sending the client 200 OK, followed by the contents of the page, instead it tells you that your cached version is good:

304 Not Modified

Your browser did have to suffer the delay of sending a request to the server, and wait for a response, but it did save having to re-download the static content.

Why Max-Age? Why Expires?

Because Last-Modified sucks.

Not everything on the server has a date associated with it. If I'm building a page on the fly, there is no date associated with it - it's now. But I'm perfectly willing to let the user cache the homepage for 15 seconds:

200 OK
Cache-Control: max-age=15

If the user hammers F5, they'll keep getting the cached version for 15 seconds. If it's a corporate proxy, then all 67198 users hitting the same page in the same 15-second window will all get the same contents - all served from close cache. Performance win for everyone.

The virtue of adding Cache-Control: max-age is that the browser doesn't even have to perform a conditional request.

  • if you specified only Last-Modified, the browser has to perform a request If-Modified-Since, and watch for a 304 Not Modified response
  • if you specified max-age, the browser won't even have to suffer the network round-trip; the content will come right out of the caches

The difference between "Cache-Control: max-age" and "Expires"

Expires is a legacy equivalent of the modern (c. 1998) Cache-Control: max-age header:

  • Expires: you specify a date (yuck)
  • max-age: you specify seconds (goodness)
  • And if both are specified, then the browser uses max-age:

    200 OK
    Cache-Control: max-age=60
    Expires: 20180403T192837 
    

Any web-site written after 1998 should not use Expires anymore, and instead use max-age.

What is ETag?

ETag is similar to Last-Modified, except that it doesn't have to be a date - it just has to be a something.

If I'm pulling a list of products out of a database, the server can send the last rowversion as an ETag, rather than a date:

200 OK
ETag: "247986"

My ETag can be the SHA1 hash of a static resource (e.g. image, js, css, font), or of the cached rendered page (i.e. this is what the Mozilla MDN wiki does; they hash the final markup):

200 OK
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

And exactly like in the case of a conditional request based on Last-Modified:

GET / HTTP/1.1
If-Modified-Since: Tue, 16 Oct 2012 03:13:38 GMT

304 Not Modified

I can perform a conditional request based on the ETag:

GET / HTTP/1.1
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"

304 Not Modified

An ETag is superior to Last-Modified because it works for things besides files, or things that have a notion of date. It just is

Fixed digits after decimal with f-strings

Adding to Rob?'s answer: in case you want to print rather large numbers, using thousand separators can be a great help (note the comma).

>>> f'{a*1000:,.2f}'
'10,123.40'

How to get Toolbar from fragment?

You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();

The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

In Kotlin:

(activity as AppCompatActivity).supportActionBar?.title = "My Title"

Check if a number has a decimal place/is a whole number

parseInt(num) === num

when passed a number, parseInt() just returns the number as int:

parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3     // true

Remove part of string after "."

You could do:

sub("*\\.[0-9]", "", a)

or

library(stringr)
str_sub(a, start=1, end=-3)

Wait for page load in Selenium

If you want to wait for a specific element to load, you can use the isDisplayed() method on a RenderedWebElement :

// Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
    // Browsers which render content (such as Firefox and IE) return "RenderedWebElements"
    RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m"));

    // If results have been returned, the results are displayed in a drop down.
    if (resultsDiv.isDisplayed()) {
      break;
    }
}

(Example from The 5 Minute Getting Started Guide)

SQL Server date format yyyymmdd

SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD

What is a typedef enum in Objective-C?

A user defined type that has the possible values of kCircle, kRectangle, or kOblateSpheroid. The values inside the enum (kCircle, etc) are visible outside the enum, though. It's important to keep that in mind (int i = kCircle; is valid, for example).

Is there a way to set background-image as a base64 encoded image?

Had the same problem with base64. For anyone in the future with the same problem:

url = "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

This would work executed from console, but not from within a script:

$img.css("background-image", "url('" + url + "')");

But after playing with it a bit, I came up with this:

var img = new Image();
img.src = url;
$img.css("background-image", "url('" + img.src + "')");

No idea why it works with a proxy image, but it does. Tested on Firefox Dev 37 and Chrome 40.

Hope it helps someone.

EDIT

Investigated a little bit further. It appears that sometimes base64 encoding (at least in my case) breaks with CSS because of line breaks present in the encoded value (in my case value was generated dynamically by ActionScript).

Simply using e.g.:

$img.css("background-image", "url('" + url.replace(/(\r\n|\n|\r)/gm, "") + "')");

works too, and even seems to be faster by a few ms than using a proxy image.

Change image size with JavaScript

Once you have a reference to your image, you can set its height and width like so:

var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
    yourImg.style.height = '100px';
    yourImg.style.width = '200px';
}

In the html, it would look like this:

<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>

How to create a HTML Cancel button that redirects to a URL

Thats what i am using try it.

<a href="index.php"><button style ="position:absolute;top:450px;left:1100px;height:30px;width:200px;"> Cancel </button></a>

Transform char array into String

If you have the char array null terminated, you can assign the char array to the string:

char[] chArray = "some characters";
String String(chArray);

As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.

How to stop BackgroundWorker correctly

In my case, I had to pool database for payment confirmation to come in and then update WPF UI.

Mechanism that spins up all the processes:

public void Execute(object parameter)
        {
            try
            {
                var url = string.Format("{0}New?transactionReference={1}", Settings.Default.PaymentUrlWebsite, "transactionRef");
                Process.Start(new ProcessStartInfo(url));
                ViewModel.UpdateUiWhenDoneWithPayment = new BackgroundWorker {WorkerSupportsCancellation = true};
                ViewModel.UpdateUiWhenDoneWithPayment.DoWork += ViewModel.updateUiWhenDoneWithPayment_DoWork;
                ViewModel.UpdateUiWhenDoneWithPayment.RunWorkerCompleted += ViewModel.updateUiWhenDoneWithPayment_RunWorkerCompleted;
                ViewModel.UpdateUiWhenDoneWithPayment.RunWorkerAsync();
            }
            catch (Exception e)
            {
                ViewModel.Log.Error("Failed to navigate to payments", e);
                MessageBox.Show("Failed to navigate to payments");
            }
        }

Mechanism that does checking for completion:

 private void updateUiWhenDoneWithPayment_DoWork(object sender, DoWorkEventArgs e)
    {
        Thread.Sleep(30000);
        while (string.IsNullOrEmpty(GetAuthToken()) && !((BackgroundWorker)sender).CancellationPending)
        {
            Thread.Sleep(5000);
        }

        //Plug in pooling mechanism
        this.AuthCode = GetAuthToken();
    }

Mechanism that cancels if window gets closed:

private void PaymentView_OnUnloaded(object sender, RoutedEventArgs e)
    {
        var context = DataContext as PaymentViewModel;
        if (context.UpdateUiWhenDoneWithPayment != null && context.UpdateUiWhenDoneWithPayment.WorkerSupportsCancellation && context.UpdateUiWhenDoneWithPayment.IsBusy)
            context.UpdateUiWhenDoneWithPayment.CancelAsync();
    }

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

Getting unique items from a list

Apart from the Distinct extension method of LINQ, you could use a HashSet<T> object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode) rather than an IEqualityComparer).

In fact, if it's appropiate for your situation, I would just use a HashSet for storing the items in the first place.

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

I have this error as well after upgrading MySQL from 5.6 to 5.7

I figured out that the best solution for me was to combine some of the solutions here and make something of it that worked with the minimum of input.

I use MyPHPAdmin for the simplicity of sending the queries through the interface because then I can check the structure and all that easily. You might use ssh directly or some other interface. The method should be similar or same anyway.

...

1.

First check out the actual error when trying to repair the db:

joomla.jos_menu Note : TIME/TIMESTAMP/DATETIME columns of old format have been upgraded to the new format.

Warning : Incorrect datetime value: '0000-00-00 00:00:00' for column 'checked_out_time' at row 1

Error : Invalid default value for 'checked_out_time'

status : Operation failed

This tells me the column checked_out_time in the table jos_menu needs to have all bad dates fixed as well as the "default" changed.

...

2.

I run the SQL query based on the info in the error message:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE checked_out_time = 0

If you get an error you can use the below query instead that seems to always work:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE CAST(checked_out_time AS CHAR(20)) = '0000-00-00 00:00:00'

...

3.

Then once that is done I run the second SQL query:

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP;

Or in the case it is a date that has to be NULL

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT NULL;

...

If I run repair database now I get:

joomla.jos_menu OK

...

Works just fine :)

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Alert after page load

Add the code below in the PageLoad Event:

ScriptManager.RegisterStartupScript(Page, this.GetType(), "myScript", "alert('OK Done.');", true);

The EntityManager is closed

Symfony v4.1.6

Doctrine v2.9.0

Process inserting duplicates in a repository

  1. Get access a registry in your repo


    //begin of repo
    
    /** @var RegistryInterface */
    protected $registry;
    
    public function __construct(RegistryInterface $registry)
    {
        $this->registry = $registry;
        parent::__construct($registry, YourEntity::class);
    }

  1. Wrap risky code into transaction and reset manager in case of exception


    //in repo method
    $em = $this->getEntityManager();
    
    $em->beginTransaction();
    try {
        $em->persist($yourEntityThatCanBeDuplicate);
        $em->flush();
        $em->commit();
    
    } catch (\Throwable $e) {
        //Rollback all nested transactions
        while ($em->getConnection()->getTransactionNestingLevel() > 0) {
            $em->rollback();
        }
        
        //Reset the default em
        if (!$em->isOpen()) {
            $this->registry->resetManager();
        }
    }

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Firstly we should understand when we use $.ajax and when we use $.get/$.post

When we require low level control over the ajax request such as request header settings, caching settings, synchronous settings etc.then we should go for $.ajax.

$.get/$.post: When we do not require low level control over the ajax request.Only simple get/post the data to the server.It is shorthand of

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

and hence we can not use other features(sync,cache etc.) with $.get/$.post.

Hence for low level control(sync,cache,etc.) over ajax request,we should go for $.ajax

 $.ajax({
     type: 'GET',
      url: url,
      data: data,
      success: success,
      dataType: dataType,
      async:false
    });

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

Add line break to 'git commit -m' from the command line

Certainly, how it's done depends on your shell. In Bash, you can use single quotes around the message and can just leave the quote open, which will make Bash prompt for another line, until you close the quote. Like this:

git commit -m 'Message

goes
here'

Alternatively, you can use a "here document" (also known as heredoc):

git commit -F- <<EOF
Message

goes
here
EOF

How to rotate the background image in the container?

Very easy method, you rotate one way, and the contents the other. Requires a square though

#element{
    background : url('someImage.jpg');
}
#element:hover{
    transform: rotate(-30deg);
}
#element:hover >*{
    transform: rotate(30deg);
}

Babel 6 regeneratorRuntime is not defined

Besides polyfill, I use babel-plugin-transform-runtime. The plugin is described as:

Externalize references to helpers and builtins, automatically polyfilling your code without polluting globals. What does this actually mean though? Basically, you can use built-ins such as Promise, Set, Symbol etc as well use all the Babel features that require a polyfill seamlessly, without global pollution, making it extremely suitable for libraries.

It also includes support for async/await along with other built-ins of ES 6.

$ npm install --save-dev babel-plugin-transform-runtime

In .babelrc, add the runtime plugin

{
  "plugins": [
    ["transform-runtime", {
      "regenerator": true
    }]
  ]
}

Note If you're using babel 7, the package has been renamed to @babel/plugin-transform-runtime.

How to create JSON object using jQuery

How to get append input field value as json like

temp:[
        {
           test:'test 1',
           testData:  [ 
                       {testName: 'do',testId:''}
                         ],
           testRcd:'value'                             
        },
        {
            test:'test 2',
           testData:  [
                            {testName: 'do1',testId:''}
                         ],
           testRcd:'value'                           
        }
      ],

Put byte array to JSON and vice versa

what about simply this:

byte[] args2 = getByteArry();
String byteStr = new String(args2);

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Auto-increment primary key in SQL tables

for those who are having the issue of it still not letting you save once it is changed according to answer below, do the following:

tools -> options -> designers -> Table and Database Designers -> uncheck "prevent saving changes that require table re-creation" box -> OK

and try to save as it should work now

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

Windows Batch: How to add Host-Entries?

Well I write a script which works very well.

> @echo off TITLE Modifying your HOSTS file COLOR F0 ECHO.
> 
> :LOOP SET Choice= SET /P Choice="Do you want to modify HOSTS file ?
> (Y/N)"
> 
> IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%
> 
> ECHO. IF /I '%Choice%'=='Y' GOTO ACCEPTED IF /I '%Choice%'=='N' GOTO
> REJECTED ECHO Please type Y (for Yes) or N (for No) to proceed! ECHO.
> GOTO Loop
> 
> 
> :REJECTED ECHO Your HOSTS file was left
> unchanged>>%systemroot%\Temp\hostFileUpdate.log ECHO Finished. GOTO
> END
> 
> 
> :ACCEPTED SET NEWLINE=^& echo. ECHO Carrying out requested
> modifications to your HOSTS file FIND /C /I "www.youtube.com"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    www.youtube.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "youtube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.facebook.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "facebook.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> facebook.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1    www.4everproxy.com
> >>%WINDIR%\system32\drivers\etc\hosts FIND /C /I "4everproxy.com " %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1    4everproxy.com >>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "proxysite.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxysite.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxfree.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxfree.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "hidemyass.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemyass.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "freeyoutubeproxy.org" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> freeyoutubeproxy.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockvideos.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockvideos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxyone.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxyone.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kuvia.eu" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    kuvia.eu>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "kuvia.eu/facebook-proxy"
> %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> kuvia.eu/facebook-proxy>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "hidemytraxproxy.ca" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> hidemytraxproxy.ca>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "github.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> github.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "funproxy.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> funproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "en.wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> en.wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "wikipedia.org" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> wikipedia.org>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dronten.proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dronten.proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "proxylistpro.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> proxylistpro.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zfreez.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zfreez.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zendproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zendproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zalmos.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> zalmos.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "zacebookpk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> zacebookpk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeunblockproxy.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeunblockproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "youtubefreeproxy.net" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubefreeproxy.net>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youliaoren.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youliaoren.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "xitenow.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> xitenow.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youtubeproxy.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youtubeproxy.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "webmasterview.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> webmasterview.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "youproxytube.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> youproxytube.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.vobas.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "vobas.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    vobas.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> www.unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblockmyweb.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> unblockmyweb.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblocker.yt" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblocker.yt>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "unblock.pk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> unblock.pk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "techgyd.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> techgyd.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "snapdeal.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> snapdeal.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "site2unblock.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> site2unblock.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "shopclues.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> shopclues.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxypk.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxypk.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "proxay.co.uk" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> proxay.co.uk>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "myntra.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> myntra.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.maddw.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "maddw.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1    maddw.com>>%WINDIR%\system32\drivers\etc\hosts
> FIND /C /I "www.lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "lenskart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> lenskart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "kproxy.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> kproxy.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "jabong.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> jabong.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "flipkart.com" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ
> 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO 127.0.0.1   
> flipkart.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND
> /C /I "facebook-proxyserver.com" %WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO
> %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL% NEQ 0
> ECHO 127.0.0.1   
> facebook-proxyserver.com>>%WINDIR%\system32\drivers\etc\hosts FIND /C
> /I "www.dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts
> IF %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "dontfilter.us" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> dontfilter.us>>%WINDIR%\system32\drivers\etc\hosts FIND /C /I
> "www.dolopo.net" %WINDIR%\system32\drivers\etc\hosts IF %ERRORLEVEL%
> NEQ 0 ECHO %NEWLINE%>>%WINDIR%\system32\drivers\etc\hosts IF
> %ERRORLEVEL% NEQ 0 ECHO 127.0.0.1   
> www.dolopo.net>>%WINDIR%\system32\drivers\etc\hosts ECHO Finished GOTO
> END
> 
> 
> :END ECHO. ping -n 11 127.0.0.1 > nul EXIT

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

Please check this jsFiddle. (The code is basically the same you posted but I use an element instead of the window to bind the scroll events).

As far as I can see, there is no problem with the code you posted. The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener:

$scope.$watch('users', function(value) {
  $scope.users = [];
});

This will result on an error message:

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: ...

Make sure that your code doesn't have this kind of situations.

update:

This is your problem:

<div ng-init="user.score=user.id+1"> 

You shouldn't change objects/models during the render or otherwise, it will force a new render (and consequently a loop, which causes the 'Error: 10 $digest() iterations reached. Aborting!').

If you want to update the model, do it on the Controller or on a Directive, never on the view. angularjs documentation recommends not to use the ng-init exactly to avoid these kinds of situations:

Use ngInit directive in templates (for toy/example apps only, not recommended for real applications)

Here's a jsFiddle with a working example.

Android setOnClickListener method - How does it work?

That what manual says about setOnClickListener method is:

public void setOnClickListener (View.OnClickListener l)

Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.

Parameters

l View.OnClickListener: The callback that will run

And normally you have to use it like this

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        ...
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(this);
    }

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked
    }
    ...
}

Take a look at this lesson as well Building a Simple Calculator using Android Studio.

HashMap get/put complexity

In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.

When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.

The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).

If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.

Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.

How to delete a row from GridView?

You are deleting the row from the gridview but you are then going and calling databind again which is just refreshing the gridview to the same state that the original datasource is in.

Either remove it from the datasource and then databind, or databind and remove it from the gridview without redatabinding.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

Favicon: .ico or .png / correct tags?

I know this is an old question.

Here's another option - attending to different platform requirements - Source

<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->

This is the broadest approach I have found so far.

Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?

UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

it would be helpful to know if you use linux or windows. in linux the settings are located in ~/.smartgit/3. You could try to remove this folder. Imho this is also worth a try in Windows.

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

Why are these new categories needed? Are the WG21 gods just trying to confuse us mere mortals?

I don't feel that the other answers (good though many of them are) really capture the answer to this particular question. Yes, these categories and such exist to allow move semantics, but the complexity exists for one reason. This is the one inviolate rule of moving stuff in C++11:

Thou shalt move only when it is unquestionably safe to do so.

That is why these categories exist: to be able to talk about values where it is safe to move from them, and to talk about values where it is not.

In the earliest version of r-value references, movement happened easily. Too easily. Easily enough that there was a lot of potential for implicitly moving things when the user didn't really mean to.

Here are the circumstances under which it is safe to move something:

  1. When it's a temporary or subobject thereof. (prvalue)
  2. When the user has explicitly said to move it.

If you do this:

SomeType &&Func() { ... }

SomeType &&val = Func();
SomeType otherVal{val};

What does this do? In older versions of the spec, before the 5 values came in, this would provoke a move. Of course it does. You passed an rvalue reference to the constructor, and thus it binds to the constructor that takes an rvalue reference. That's obvious.

There's just one problem with this; you didn't ask to move it. Oh, you might say that the && should have been a clue, but that doesn't change the fact that it broke the rule. val isn't a temporary because temporaries don't have names. You may have extended the lifetime of the temporary, but that means it isn't temporary; it's just like any other stack variable.

If it's not a temporary, and you didn't ask to move it, then moving is wrong.

The obvious solution is to make val an lvalue. This means that you can't move from it. OK, fine; it's named, so its an lvalue.

Once you do that, you can no longer say that SomeType&& means the same thing everwhere. You've now made a distinction between named rvalue references and unnamed rvalue references. Well, named rvalue references are lvalues; that was our solution above. So what do we call unnamed rvalue references (the return value from Func above)?

It's not an lvalue, because you can't move from an lvalue. And we need to be able to move by returning a &&; how else could you explicitly say to move something? That is what std::move returns, after all. It's not an rvalue (old-style), because it can be on the left side of an equation (things are actually a bit more complicated, see this question and the comments below). It is neither an lvalue nor an rvalue; it's a new kind of thing.

What we have is a value that you can treat as an lvalue, except that it is implicitly moveable from. We call it an xvalue.

Note that xvalues are what makes us gain the other two categories of values:

  • A prvalue is really just the new name for the previous type of rvalue, i.e. they're the rvalues that aren't xvalues.

  • Glvalues are the union of xvalues and lvalues in one group, because they do share a lot of properties in common.

So really, it all comes down to xvalues and the need to restrict movement to exactly and only certain places. Those places are defined by the rvalue category; prvalues are the implicit moves, and xvalues are the explicit moves (std::move returns an xvalue).

How to redirect to a different domain using NGINX?

That should work via HTTPRewriteModule.

Example rewrite from www.example.com to example.com:

server {    
    server_name www.example.com;    
    rewrite ^ http://example.com$request_uri? permanent; 
}

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Select data from "show tables" MySQL query

Have you looked into querying INFORMATION_SCHEMA.Tables? As in

SELECT ic.Table_Name,
    ic.Column_Name,
    ic.data_Type,
    IFNULL(Character_Maximum_Length,'') AS `Max`,
    ic.Numeric_precision as `Precision`,
    ic.numeric_scale as Scale,
    ic.Character_Maximum_Length as VarCharSize,
    ic.is_nullable as Nulls, 
    ic.ordinal_position as OrdinalPos, 
    ic.column_default as ColDefault, 
    ku.ordinal_position as PK,
    kcu.constraint_name,
    kcu.ordinal_position,
    tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
    left outer join INFORMATION_SCHEMA.key_column_usage ku
        on ku.table_name = ic.table_name
        and ku.column_name = ic.column_name
    left outer join information_schema.key_column_usage kcu
        on kcu.column_name = ic.column_name
        and kcu.table_name = ic.table_name
    left outer join information_schema.table_constraints tc
        on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

In Windows CMD line, find out the Process ID that hold a connection on the bind port by entering following command:

C:> netstat -a -o

-a show all connections

-o show process identifier

And then Terminate the process.

Converting json results to a date

You need to extract the number from the string, and pass it into the Date constructor:

var x = [{
    "id": 1,
    "start": "\/Date(1238540400000)\/"
}, {
    "id": 2,
    "start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

Clicking URLs opens default browser

Add this 2 lines in your code -

mWebView.setWebChromeClient(new WebChromeClient()); 
mWebView.setWebViewClient(new WebViewClient());?

X-Frame-Options Allow-From multiple domains

Necromancing.
The provided answers are incomplete.

First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.

It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.

This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.

// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{

    public System.Web.HttpBrowserCapabilities Browser { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string Platform { get; set; }
    public bool IsMobileDevice { get; set; }
    public string MobileBrand { get; set; }
    public string MobileModel { get; set; }


    public BrowserInfo(System.Web.HttpRequest request)
    {
        if (request.Browser != null)
        {
            if (request.UserAgent.Contains("Edge")
                && request.Browser.Browser != "Edge")
            {
                this.Name = "Edge";
            }
            else
            {
                this.Name = request.Browser.Browser;
                this.Version = request.Browser.MajorVersion.ToString();
            }
            this.Browser = request.Browser;
            this.Platform = request.Browser.Platform;
            this.IsMobileDevice = request.Browser.IsMobileDevice;
            if (IsMobileDevice)
            {
                this.Name = request.Browser.Browser;
            }
        }
    }


}


void context_EndRequest(object sender, System.EventArgs e)
{
    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

        try
        {
            // response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
            // response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            // response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");

            // response.AppendHeader("X-Frame-Options", "DENY");
            // response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
            // response.AppendHeader("X-Frame-Options", "AllowAll");

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                // "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome 
                string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
                            + System.Web.HttpContext.Current.Request.UrlReferrer.Authority
                ;

                string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
                string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;

                // SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);

                if (IsHostAllowed(refAuth))
                {
                    BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);

                    // bi.Name = Firefox
                    // bi.Name = InternetExplorer
                    // bi.Name = Chrome

                    // Chrome wants entire path... 
                    if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
                        response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);    

                    // unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
                    // unsafe-inline: styles
                    // data: url(data:image/png:...)

                    // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
                    // https://www.ietf.org/rfc/rfc7034.txt
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

                    // https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
                    // https://content-security-policy.com/
                    // http://rehansaeed.com/content-security-policy-for-asp-net-mvc/

                    // This is for Chrome:
                    // response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);


                    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
                    ls.Add("default-src");
                    ls.Add("'self'");
                    ls.Add("'unsafe-inline'");
                    ls.Add("'unsafe-eval'");
                    ls.Add("data:");

                    // http://az416426.vo.msecnd.net/scripts/a/ai.0.js

                    // ls.Add("*.msecnd.net");
                    // ls.Add("vortex.data.microsoft.com");

                    ls.Add(selfAuth);
                    ls.Add(refAuth);

                    string contentSecurityPolicy = string.Join(" ", ls.ToArray());
                    response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
                }
                else
                {
                    response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
                }

            }
            else
                response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
        }
        catch (System.Exception ex)
        {
            // WTF ? 
            System.Console.WriteLine(ex.Message); // Suppress warning
        }

    } // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)

} // End Using context_EndRequest


private static string[] s_allowedHosts = new string[] 
{
     "localhost:49533"
    ,"localhost:52257"
    ,"vmcompany1"
    ,"vmcompany2"
    ,"vmpostalservices"
    ,"example.com"
};


public static bool IsHostAllowed(string host)
{
    return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed 


public static bool Contains(string[] allowed, string current)
{
    for (int i = 0; i < allowed.Length; ++i)
    {
        if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
            return true;
    } // Next i 

    return false;
} // End Function Contains 

You need to register the context_EndRequest function in the HTTP-module Init function.

public class RequestLanguageChanger : System.Web.IHttpModule
{


    void System.Web.IHttpModule.Dispose()
    {
        // throw new NotImplementedException();
    }


    void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
    {
        // https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
        context.EndRequest += new System.EventHandler(context_EndRequest);
    }

    // context_EndRequest Code from above comes here


}

Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:

namespace ChangeRequestLanguage
{


    public class Global : System.Web.HttpApplication
    {

        System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();

        public override void Init()
        {
            mod.Init(this);
            base.Init();
        }



        protected void Application_Start(object sender, System.EventArgs e)
        {

        }

        protected void Session_Start(object sender, System.EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_Error(object sender, System.EventArgs e)
        {

        }

        protected void Session_End(object sender, System.EventArgs e)
        {

        }

        protected void Application_End(object sender, System.EventArgs e)
        {

        }


    }


}

or you can add entries to Web.config if you don't own the application source-code:

      <httpModules>
        <add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
      </httpModules>
    </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

    <modules runAllManagedModulesForAllRequests="true">
      <add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
    </modules>
  </system.webServer>
</configuration>

The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.

The string in type is in the format "Namespace.Class, Assembly". Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like

"[DefaultNameSpace.Namespace].Class, Assembly"

If you want to avoid this problem, write the DLL in C#.

Client to send SOAP request and receive response

I wrote a more general helper class which accepts a string-based dictionary of custom parameters, so that they can be set by the caller without having to hard-code them. It goes without saying that you should only use such method when you want (or need) to manually issue a SOAP-based web service: in most common scenarios the recommended approach would be using the Web Service WSDL together with the Add Service Reference Visual Studio feature instead.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;

namespace Ryadel.Web.SOAP
{
    /// <summary>
    /// Helper class to send custom SOAP requests.
    /// </summary>
    public static class SOAPHelper
    {
        /// <summary>
        /// Sends a custom sync SOAP request to given URL and receive a request
        /// </summary>
        /// <param name="url">The WebService endpoint URL</param>
        /// <param name="action">The WebService action name</param>
        /// <param name="parameters">A dictionary containing the parameters in a key-value fashion</param>
        /// <param name="soapAction">The SOAPAction value, as specified in the Web Service's WSDL (or NULL to use the url parameter)</param>
        /// <param name="useSOAP12">Set this to TRUE to use the SOAP v1.2 protocol, FALSE to use the SOAP v1.1 (default)</param>
        /// <returns>A string containing the raw Web Service response</returns>
        public static string SendSOAPRequest(string url, string action, Dictionary<string, string> parameters, string soapAction = null, bool useSOAP12 = false)
        {
            // Create the SOAP envelope
            XmlDocument soapEnvelopeXml = new XmlDocument();
            var xmlStr = (useSOAP12)
                ? @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
                      xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                      xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
                      <soap12:Body>
                        <{0} xmlns=""{1}"">{2}</{0}>
                      </soap12:Body>
                    </soap12:Envelope>"
                : @"<?xml version=""1.0"" encoding=""utf-8""?>
                    <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                        xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                        xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                        <soap:Body>
                           <{0} xmlns=""{1}"">{2}</{0}>
                        </soap:Body>
                    </soap:Envelope>";
            string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
            var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
            soapEnvelopeXml.LoadXml(s);

            // Create the web request
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", soapAction ?? url);
            webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
            webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
            webRequest.Method = "POST";

            // Insert SOAP envelope
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }

            // Send request and retrieve result
            string result;
            using (WebResponse response = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    result = rd.ReadToEnd();
                }
            }
            return result;
        }
    }
}

For additional info & details regarding this class you can also read this post on my blog.

Pure CSS to make font-size responsive based on dynamic amount of characters

If doing from scratch in Bootstrap 4

  1. Go to https://bootstrap.build/app
  2. Click Search Mode
  3. Search for $enable-responsive-font-sizes and turn it on.
  4. Click Export Theme to save your custom bootstrap CSS file.

How to send post request to the below post method using postman rest client

I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.

How do I use HTML as the view engine in Express?

In your apps.js just add

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

Now you can use ejs view engine while keeping your view files as .html

source: http://www.makebetterthings.com/node-js/how-to-use-html-with-express-node-js/

You need to install this two packages:

`npm install ejs --save`
`npm install path --save`

And then import needed packages:

`var path = require('path');`


This way you can save your views as .html instead of .ejs.
Pretty helpful while working with IDEs that support html but dont recognize ejs.

How could I put a border on my grid control in WPF?

<Grid x:Name="outerGrid">
    <Grid x:Name="innerGrid">
        <Border BorderBrush="#FF179AC8" BorderThickness="2" />
        <other stuff></other stuff>
        <other stuff></other stuff>
    </Grid>
</Grid>

This code Wrap a border inside the "innerGrid"

PHP - Copy image to my server direct from URL

$url = "http://www.example/images/image.gif";
$save_name = "image.gif";
$save_directory = "/var/www/example/downloads/";

if(is_writable($save_directory)) {
    file_put_contents($save_directory . $save_name, file_get_contents($url));
} else {
    exit("Failed to write to directory "{$save_directory}");
}

How do I protect javascript files?

I think the only way is to put required data on the server and allow only logged-in user to access the data as required (you can also make some calculations server side). This wont protect your javascript code but make it unoperatable without the server side code

How can I add new array elements at the beginning of an array in Javascript?

Without Mutate

Actually, all unshift/push and shift/pop mutate the origin array.

The unshift/push add an item to the existed array from begin/end and shift/pop remove an item from the beginning/end of an array.

But there are few ways to add items to an array without a mutation. the result is a new array, to add to the end of array use below code:

const originArray = ['one', 'two', 'three'];
const newItem = 4;

const newArray = originArray.concat(newItem); // ES5
const newArray2 = [...originArray, newItem]; // ES6+

To add to begin of original array use below code:

const originArray = ['one', 'two', 'three'];
const newItem = 0;

const newArray = (originArray.slice().reverse().concat(newItem)).reverse(); // ES5
const newArray2 = [newItem, ...originArray]; // ES6+

With the above way, you add to the beginning/end of an array without a mutation.

How can I change or remove HTML5 form validation default error messages?

I found a bug on Mahoor13 answer, it's not working in loop so I've fixed it with this correction:

HTML:

<input type="email" id="eid" name="email_field" oninput="check(this)">

Javascript:

function check(input) {  
    if(input.validity.typeMismatch){  
        input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");  
    }  
    else {  
        input.setCustomValidity("");  
    }                 
}  

It will perfectly running in loop.

How to check string length with JavaScript

 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io package name hints, the mentioned class is part of the http://commons.apache.org/io project.

And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar in the /WEB-INF/lib as well.

See also:

Can I have multiple background images using CSS?

Current version of FF and IE and some other browsers support multiple background images in a single CSS2 declaration. Look here http://dense13.com/blog/2008/08/31/multiple-background-images-with-css2/ and here http://www.quirksmode.org/css/multiple_backgrounds.html and here http://nicolasgallagher.com/multiple-backgrounds-and-borders-with-css2/

For IE, you might consider adding a behavior. Look here: http://css3pie.com/

Regular Expression to match only alphabetic characters

If you need to include non-ASCII alphabetic characters, and if your regex flavor supports Unicode, then

\A\pL+\z

would be the correct regex.

Some regex engines don't support this Unicode syntax but allow the \w alphanumeric shorthand to also match non-ASCII characters. In that case, you can get all alphabetics by subtracting digits and underscores from \w like this:

\A[^\W\d_]+\z

\A matches at the start of the string, \z at the end of the string (^ and $ also match at the start/end of lines in some languages like Ruby, or if certain regex options are set).

how I can show the sum of in a datagridview column?

If your grid is bound to a DataTable, I believe you can just do:

// Should probably add a DBNull check for safety; but you get the idea.
long sum = (long)table.Compute("Sum(count)", "True");

If it isn't bound to a table, you could easily make it so:

var table = new DataTable();
table.Columns.Add("type", typeof(string));
table.Columns.Add("count", typeof(int));

// This will automatically create the DataGridView's columns.
dataGridView.DataSource = table;

height style property doesn't work in div elements

You're loosing your height attribute because you're changing the block element to inline (it's now going to act like a <p>). You're probably picking up that 14px height because of the text height inside your in-line div.

Inline-block may work for your needs, but you may have to implement a work around or two for cross-browser support.

IE supports inline-block, but only for elements that are natively inline.

Using reCAPTCHA on localhost

It's so easy:

  1. Go to your google reCaptcha admin panel
  2. Add localhost & 127.0.0.1 to domains of a new site like the following image.

enter image description here


Update:

If your question is how to set reCaptcha in Google site for using it in localhost, then i has been wrote it above but if you are curious that how you can using reCAPTCHA on both localhost and website host by minimal codes in your controller and prevent some codes like ConfigurationManager.AppSettings["ReCaptcha:SiteKey"] in it then I help you with this extra description and codes in my answer.

Do you like the following GET and POST actions?

It support reCaptcha and doesn't need any other codes for handling reCaptcha.

[HttpGet]
[Recaptcha]
public ActionResult Register()
{
    // Your codes in GET action
}

[HttpPost]
[Recaptcha]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model, string reCaptcha_SecretKey){
   // Your codes in POST action
   if (!ModelState.IsValid || !ReCaptcha.Validate(reCaptcha_SecretKey))
   {
       // Your codes
   }
   // Your codes
}

In View: (reference)

@ReCaptcha.GetHtml(@ViewBag.publicKey)

@if (ViewBag.RecaptchaLastErrors != null)
{
    <div>Oops! Invalid reCAPTCHA =(</div>
}

To use it

A) Add the following ActionFilter to your Web project:

public class RecaptchaAttribute : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
        filterContext.ActionParameters["ReCaptcha_SecretKey"] = ConfigurationManager.AppSettings[$"{setting_Key}:SecretKey"];
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
        filterContext.Controller.ViewBag.Recaptcha = ReCaptcha.GetHtml(publicKey: ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"]);
        filterContext.Controller.ViewBag.publicKey = ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"];
    }
}

B) Add the reCaptcha settings keys for both localhost & website like it in your webconfig file:

<appSettings>

    <!-- RECAPTCHA SETTING KEYS FOR LOCALHOST -->
    <add key="ReCaptcha_Local:SiteKey" value="[Localhost SiteKey]" />
    <add key="ReCaptcha_Local:SecretKey" value="[Localhost SecretKey]" />
    <!-- RECAPTCHA SETTING KEYS FOR WEBSITE -->
    <!--<add key="ReCaptcha:SiteKey" value="[Webite SiteKey]" />
    <add key="ReCaptcha:SecretKey" value="[Webite SecretKey]" />-->

    <!-- OTHER SETTING KEYS OF YOUR PROJECT -->

</appSettings>

Note: By this way you did not need set reCaptcha_SecretKey parameter in the post action or any ViewBag for reCaptcha manually in your Actions and Views, all of them will be filled automatically at runtime with appropriate values depending on you have run the project on the localhost or website.

How to find minimum value from vector?

template <class ForwardIterator>
ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
    ForwardIterator lowest = first;
    if (first == last) return last;
    while (++first != last)
    if (*first < *lowest) 
        lowest = first;
    return lowest;
}

How to find length of digits in an integer?

Here is a bulky but fast version :

def nbdigit ( x ):
    if x >= 10000000000000000 : # 17 -
        return len( str( x ))
    if x < 100000000 : # 1 - 8
        if x < 10000 : # 1 - 4
            if x < 100             : return (x >= 10)+1 
            else                   : return (x >= 1000)+3
        else: # 5 - 8                                                 
            if x < 1000000         : return (x >= 100000)+5 
            else                   : return (x >= 10000000)+7
    else: # 9 - 16 
        if x < 1000000000000 : # 9 - 12
            if x < 10000000000     : return (x >= 1000000000)+9 
            else                   : return (x >= 100000000000)+11
        else: # 13 - 16
            if x < 100000000000000 : return (x >= 10000000000000)+13 
            else                   : return (x >= 1000000000000000)+15

Only 5 comparisons for not too big numbers. On my computer it is about 30% faster than the math.log10 version and 5% faster than the len( str()) one. Ok... no so attractive if you don't use it furiously.

And here is the set of numbers I used to test/measure my function:

n = [ int( (i+1)**( 17/7. )) for i in xrange( 1000000 )] + [0,10**16-1,10**16,10**16+1]

NB: it does not manage negative numbers, but the adaptation is easy...

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

Can I delete a git commit but keep the changes?

Yes, you can delete your commit without deleting the changes:

git reset @~

How can I parse a string with a comma thousand separator to a number?

If you have a small set of locales to support you'd probably be better off by just hardcoding a couple of simple rules:

function parseNumber(str, locale) {
  let radix = ',';
  if (locale.match(/(en|th)([-_].+)?/)) {
    radix = '.';
  }
  return Number(str
    .replace(new RegExp('[^\\d\\' + radix + ']', 'g'), '')
    .replace(radix, '.'));
}

Android on-screen keyboard auto popping up

In that version of Android, when a view is inflated, the focus will be set to the first focusable control by default - and if there's no physical keyboard, the on-screen keyboard will pop up.

To fix this, explicitly set focus somewhere else. If focus is set to anything other than an EditText, the on-screen keyboard will not appear.

Have you tried testing this by running Android 1.5 in the emulator?

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

Script based on Joe answer (detach, copy files, attach both).

  1. Run Managment Studio as Administrator account.

It's not necessary, but maybe access denied error on executing.

  1. Configure sql server for execute xp_cmdshel
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
  1. Run script, but type your db names in @dbName and @copyDBName variables before.
USE master;
GO 

DECLARE @dbName NVARCHAR(255) = 'Products'
DECLARE @copyDBName NVARCHAR(255) = 'Products_branch'

-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
    INSERT INTO ##DBFileNames([FileName])
    SELECT [filename] FROM ' + @dbName + '.sys.sysfiles')

-- drop connections
EXEC('ALTER DATABASE ' + @dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')

EXEC('ALTER DATABASE ' + @dbName + ' SET SINGLE_USER')

-- detach
EXEC('EXEC sp_detach_db @dbname = ''' + @dbName + '''')

-- copy files
DECLARE @filename NVARCHAR(255), @path NVARCHAR(255), @ext NVARCHAR(255), @copyFileName NVARCHAR(255), @command NVARCHAR(MAX) = ''
DECLARE 
    @oldAttachCommand NVARCHAR(MAX) = 
        'CREATE DATABASE ' + @dbName + ' ON ', 
    @newAttachCommand NVARCHAR(MAX) = 
        'CREATE DATABASE ' + @copyDBName + ' ON '

DECLARE curs CURSOR FOR 
SELECT [filename] FROM ##DBFileNames
OPEN curs  
FETCH NEXT FROM curs INTO @filename
WHILE @@FETCH_STATUS = 0  
BEGIN
    SET @path = REVERSE(RIGHT(REVERSE(@filename),(LEN(@filename)-CHARINDEX('\', REVERSE(@filename),1))+1))
    SET @ext = RIGHT(@filename,4)
    SET @copyFileName = @path + @copyDBName + @ext

    SET @command = 'EXEC master..xp_cmdshell ''COPY "' + @filename + '" "' + @copyFileName + '"'''
    PRINT @command
    EXEC(@command);

    SET @oldAttachCommand = @oldAttachCommand + '(FILENAME = "' + @filename + '"),'
    SET @newAttachCommand = @newAttachCommand + '(FILENAME = "' + @copyFileName + '"),'

    FETCH NEXT FROM curs INTO @filename
END
CLOSE curs 
DEALLOCATE curs

-- attach
SET @oldAttachCommand = LEFT(@oldAttachCommand, LEN(@oldAttachCommand) - 1) + ' FOR ATTACH'
SET @newAttachCommand = LEFT(@newAttachCommand, LEN(@newAttachCommand) - 1) + ' FOR ATTACH'

-- attach old db
PRINT @oldAttachCommand
EXEC(@oldAttachCommand)

-- attach copy db
PRINT @newAttachCommand
EXEC(@newAttachCommand)

DROP TABLE ##DBFileNames

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Logging in Scala

Logging in 2020

I was really surprised that Scribe logging framework that I use at work isn't even mentioned here. What is more, it doesn't even appear on the first page in Google after searching "scala logging". But this page appears when googling it! So let me leave that here.

Main advantages of Scribe:

String concatenation of two pandas columns

I have encountered a specific case from my side with 10^11 rows in my dataframe, and in this case none of the proposed solution is appropriate. I have used categories, and this should work fine in all cases when the number of unique string is not too large. This is easily done in the R software with XxY with factors but I could not find any other way to do it in python (I'm new to python). If anyone knows a place where this is implemented I'd be glad to know.

def Create_Interaction_var(df,Varnames):
    '''
    :df data frame
    :list of 2 column names, say "X" and "Y". 
    The two columns should be strings or categories
    convert strings columns to categories
    Add a column with the "interaction of X and Y" : X x Y, with name 
    "Interaction-X_Y"
    '''
    df.loc[:, Varnames[0]] = df.loc[:, Varnames[0]].astype("category")
    df.loc[:, Varnames[1]] = df.loc[:, Varnames[1]].astype("category")
    CatVar = "Interaction-" + "-".join(Varnames)
    Var0Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[0]].cat.categories)).rename(columns={0 : "code0",1 : "name0"})
    Var1Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[1]].cat.categories)).rename(columns={0 : "code1",1 : "name1"})
    NbLevels=len(Var0Levels)

    names = pd.DataFrame(list(itertools.product(dict(enumerate(df.loc[:,Varnames[0]].cat.categories)),
                                                dict(enumerate(df.loc[:,Varnames[1]].cat.categories)))),
                         columns=['code0', 'code1']).merge(Var0Levels,on="code0").merge(Var1Levels,on="code1")
    names=names.assign(Interaction=[str(x) + '_' + y for x, y in zip(names["name0"], names["name1"])])
    names["code01"]=names["code0"] + NbLevels*names["code1"]
    df.loc[:,CatVar]=df.loc[:,Varnames[0]].cat.codes+NbLevels*df.loc[:,Varnames[1]].cat.codes
    df.loc[:, CatVar]=  df[[CatVar]].replace(names.set_index("code01")[["Interaction"]].to_dict()['Interaction'])[CatVar]
    df.loc[:, CatVar] = df.loc[:, CatVar].astype("category")
    return df

MySQL JOIN with LIMIT 1 on joined table

The With clause would do the trick. Something like this:

WITH SELECTION AS (SELECT id FROM products LIMIT 1)
SELECT a.id, c.id, c.title FROM selection a JOIN categories c ON (c.id = a.id);

JavaScript ES6 promise for loop

Based on the excellent answer by trincot, I wrote a reusable function that accepts a handler to run over each item in an array. The function itself returns a promise that allows you to wait until the loop has finished and the handler function that you pass may also return a promise.

loop(items, handler) : Promise

It took me some time to get it right, but I believe the following code will be usable in a lot of promise-looping situations.

Copy-paste ready code:

// SEE https://stackoverflow.com/a/46295049/286685
const loop = (arr, fn, busy, err, i=0) => {
  const body = (ok,er) => {
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}
    catch(e) {er(e)}
  }
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()
  return busy ? run(busy,err) : new Promise(run)
}

Usage

To use it, call it with the array to loop over as the first argument and the handler function as the second. Do not pass parameters for the third, fourth and fifth arguments, they are used internally.

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const items = ['one', 'two', 'three']_x000D_
_x000D_
loop(items, item => {_x000D_
  console.info(item)_x000D_
})_x000D_
.then(() => console.info('Done!'))
_x000D_
_x000D_
_x000D_

Advanced use cases

Let's look at the handler function, nested loops and error handling.

handler(current, index, all)

The handler gets passed 3 arguments. The current item, the index of the current item and the complete array being looped over. If the handler function needs to do async work, it can return a promise and the loop function will wait for the promise to resolve before starting the next iteration. You can nest loop invocations and all works as expected.

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
  [],_x000D_
  ['one', 'two'],_x000D_
  ['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
  console.info('Performing test ' + idx)_x000D_
  return loop(test, (testCase) => {_x000D_
    console.info(testCase)_x000D_
  })_x000D_
  .then(testNext)_x000D_
  .catch(testFailed)_x000D_
}))_x000D_
.then(() => console.info('All tests done'))
_x000D_
_x000D_
_x000D_

Error handling

Many promise-looping examples I looked at break down when an exception occurs. Getting this function to do the right thing was pretty tricky, but as far as I can tell it is working now. Make sure to add a catch handler to any inner loops and invoke the rejection function when it happens. E.g.:

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
  [],_x000D_
  ['one', 'two'],_x000D_
  ['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
  console.info('Performing test ' + idx)_x000D_
  loop(test, (testCase) => {_x000D_
    if (idx == 2) throw new Error()_x000D_
    console.info(testCase)_x000D_
  })_x000D_
  .then(testNext)_x000D_
  .catch(testFailed)  //  <--- DON'T FORGET!!_x000D_
}))_x000D_
.then(() => console.error('Oops, test should have failed'))_x000D_
.catch(e => console.info('Succesfully caught error: ', e))_x000D_
.then(() => console.info('All tests done'))
_x000D_
_x000D_
_x000D_

UPDATE: NPM package

Since writing this answer, I turned the above code in an NPM package.

for-async

Install

npm install --save for-async

Import

var forAsync = require('for-async');  // Common JS, or
import forAsync from 'for-async';

Usage (async)

var arr = ['some', 'cool', 'array'];
forAsync(arr, function(item, idx){
  return new Promise(function(resolve){
    setTimeout(function(){
      console.info(item, idx);
      // Logs 3 lines: `some 0`, `cool 1`, `array 2`
      resolve(); // <-- signals that this iteration is complete
    }, 25); // delay 25 ms to make async
  })
})

See the package readme for more details.

Python-Requests close http connection

this works for me:

res = requests.get(<url>, timeout=10).content
requests.session().close()

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

What is &amp used for

if you're doing a string of characters. make:

let linkGoogle = 'https://www.google.com/maps/dir/?api=1'; 
let origin = '&origin=' + locations[0][1] + ',' + locations[0][2];


aNav.href = linkGoogle + origin;

CSS: styled a checkbox to look like a button, is there a hover?

Do what Kelly said...

BUT. Instead of having the input positioned absolute and top -20px (just hiding it off the page), make the input box hidden.

example:

<input type="checkbox" hidden> 

Works better and can put it anywhere on the page.

Is there a download function in jsFiddle?

Ctrl + S, saves the entire fiddle, inside the files folder there is the clean page you are looking for

How should I choose an authentication library for CodeIgniter?

Maybe you'd find Redux suiting your needs. It's no overkill and comes packed solely with bare features most of us would require. The dev and contributors were very strict on what code was contributed.

This is the official page

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

It might be that you are forgetting to specify the settings which was the case with me.

Try:

mvn clean install -s settings_file.xml

How to use ScrollView in Android?

As said above you can put it inside a ScrollView... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView... and if you want your component (or layout) to support both put inside both of them like this:

  <HorizontalScrollView>
        <ScrollView>
            <!-- SOME THING -->
        </ScrollView>
    </HorizontalScrollView>

and with setting the layout_width and layout_height ofcourse.

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

django MultiValueDictKeyError error, how do I deal with it

Choose what is best for you:

1

is_private = request.POST.get('is_private', False);

If is_private key is present in request.POST the is_private variable will be equal to it, if not, then it will be equal to False.

2

if 'is_private' in request.POST:
    is_private = request.POST['is_private']
else:
    is_private = False

3

from django.utils.datastructures import MultiValueDictKeyError
try:
    is_private = request.POST['is_private']
except MultiValueDictKeyError:
    is_private = False

Project Links do not work on Wamp Server

You can follow all steps by @RiggsFolly thats is really good answer, If you do not want to create virtual host and want to use like previous localhost/example/ or something like that you can use answer by @Arunu

But if you still face problem please use this method,

  1. Locate your wamp folder (Eg. c:/Wamp/) where you have installed
  2. Goto Wamp/www/
  3. Open index.php file
  4. find this code $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://' : '').$file.'">'.$file.'</a></li>';
  5. modify it add localhost after http:// $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://localhost' : '').$file.'">'.$file.'</a></li>';
  6. Restart wamp server
  7. open localhost see the updated links

Hope you got your url like previous version of wamp server.

How to force a checkbox and text on the same line?

Another way to do this solely with css:

input[type='checkbox'] {
  float: left;
  width: 20px;
}
input[type='checkbox'] + label {
  display: block;
  width: 30px;
}

Note that this forces each checkbox and its label onto a separate line, rather than only doing so only when there's overflow.

What does this format means T00:00:00.000Z?

As one person may have already suggested,

I passed the ISO 8601 date string directly to moment like so...

`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`

or

`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`

either of these solutions will give you the same result.

`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`

Get Country of IP Address with PHP

If you need to have a good and updated database, for having more performance and not requesting external services from your website, here there is a good place to download updated and accurate databases.

I'm recommending this because in my experience it was working excellent even including city and country location for my IP which most of other databases/apis failed to include/report my location except this service which directed me to this database.
(My ip location was from "Rasht" City in "Iran" when I was testing and the ip was: 2.187.21.235 equal to 45815275)

Therefore I recommend to use these services if you're unsure about which service is more accurate:

Database: http://lite.ip2location.com/databases

API Service: http://ipinfodb.com/ip_location_api.php

Where is Developer Command Prompt for VS2013?

I don't know if this changed recently -- the answer given by Samuel did not apply to me even though that link seemed authoritative.

A couple of things

1) For some reason, the folder in the start menu is called Visual Studio 2013, and not Microsoft Visual Studio 2013. Using the win8 apps interface you might see the 2010 entry Microsoft Visual Studio 2010, and since you don't see the new 2013 folder Microsoft Visual Studio 2013 next to it, you assume it isn't there. But it is.. Just a few page scrolls away..

2) It seems the Windows 8 (or 8.1 at least) cannot display sub-folders. I tried creating a folder underneath the Visual Studio 2013 folder with shortcuts, and the entire folder just didn't show.

3) Which is why what is installed is a shortcut. Not sure what the windows 7 behavior is with a shortcut in the start menu, but the apps menu just displays it like a folder. When you click on it, it brings you to the so-called missing shortcuts in explorer.

Final solution: under C:\ProgramData\Microsoft\Windows\Start Menu\Programs, create a new folder called Microsoft Visual Studio 2013. Copy the shortcuts from C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts to that new folder. Then you'll have your icons using the windows 8 app interface under the heading which is the new folder name.

You'll also be able to just start typing from the start screen VS2013, and the icons will now show up.

How do I specify local .gem files in my Gemfile?

This isn't strictly an answer to your question about installing .gem packages, but you can specify all kinds of locations on a gem-by-gem basis by editing your Gemfile.

Specifying a :path attribute will install the gem from that path on your local machine.

gem "foreman", path: "/Users/pje/my_foreman_fork"

Alternately, specifying a :git attribute will install the gem from a remote git repository.

gem "foreman", git: "git://github.com/pje/foreman.git"

# ...or at a specific SHA-1 ref
gem "foreman", git: "git://github.com/pje/foreman.git", ref: "bf648a070c"

# ...or branch
gem "foreman", git: "git://github.com/pje/foreman.git", branch: "jruby"

# ...or tag
gem "foreman", git: "git://github.com/pje/foreman.git", tag: "v0.45.0"

(As @JHurrah mentioned in his comment.)

How to convert an array to object in PHP?

Depending on where you need that and how to access the object there are different ways to do it.

For example: just typecast it

$object =  (object) $yourArray;

However, the most compatible one is using a utility method (not yet part of PHP) that implements standard PHP casting based on a string that specifies the type (or by ignoring it just de-referencing the value):

/**
 * dereference a value and optionally setting its type
 *
 * @param mixed $mixed
 * @param null  $type (optional)
 *
 * @return mixed $mixed set as $type
 */
function rettype($mixed, $type = NULL) {
    $type === NULL || settype($mixed, $type);
    return $mixed;
}

The usage example in your case (Online Demo):

$yourArray = Array('status' => 'Figure A. ...');

echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

How to fix Python Numpy/Pandas installation?

I had the same problem and, in my case, the problem was that python was looking for packages in some ordered locations, first of all the default computer one where default old packages are.

To check what your python is looking for you can do:

>>> import sys
>>> print '\n'.join(sys.path)

This was outputting the directory '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python' before pip or brew or port folders.

The simple solution is:

export PYTHONPATH="/Library/Python/2.7/site-packages:$PYTHONPATH"

This worked well for me, I advise you to add this line to your home bash_profile file for the next time. Remember that sys.path is built using the current working directory, followed by the directories in the PYTHONPATH environment variable. Then there are the installation-dependent default dirs.

How to check if a string contains a substring in Bash

Try oobash.

It is an OO-style string library for Bash 4. It has support for German umlauts. It is written in Bash.

Many functions are available: -base64Decode, -base64Encode, -capitalize, -center, -charAt, -concat, -contains, -count, -endsWith, -equals, -equalsIgnoreCase, -reverse, -hashCode, -indexOf, -isAlnum, -isAlpha, -isAscii, -isDigit, -isEmpty, -isHexDigit, -isLowerCase, -isSpace, -isPrintable, -isUpperCase, -isVisible, -lastIndexOf, -length, -matches, -replaceAll, -replaceFirst, -startsWith, -substring, -swapCase, -toLowerCase, -toString, -toUpperCase, -trim, and -zfill.

Look at the contains example:

[Desktop]$ String a testXccc
[Desktop]$ a.contains tX
true
[Desktop]$ a.contains XtX
false

oobash is available at Sourceforge.net.

Virtualhost For Wildcard Subdomain and Static Subdomain

This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com

SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"

VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"

DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>

Detect if value is number in MySQL

I have found that this works quite well

if(col1/col1= 1,'number',col1) AS myInfo

Bash command line and input limit

Ok, Denizens. So I have accepted the command line length limits as gospel for quite some time. So, what to do with one's assumptions? Naturally- check them.

I have a Fedora 22 machine at my disposal (meaning: Linux with bash4). I have created a directory with 500,000 inodes (files) in it each of 18 characters long. The command line length is 9,500,000 characters. Created thus:

seq 1 500000 | while read digit; do
    touch $(printf "abigfilename%06d\n" $digit);
done

And we note:

$ getconf ARG_MAX
2097152

Note however I can do this:

$ echo * > /dev/null

But this fails:

$ /bin/echo * > /dev/null
bash: /bin/echo: Argument list too long

I can run a for loop:

$ for f in *; do :; done

which is another shell builtin.

Careful reading of the documentation for ARG_MAX states, Maximum length of argument to the exec functions. This means: Without calling exec, there is no ARG_MAX limitation. So it would explain why shell builtins are not restricted by ARG_MAX.

And indeed, I can ls my directory if my argument list is 109948 files long, or about 2,089,000 characters (give or take). Once I add one more 18-character filename file, though, then I get an Argument list too long error. So ARG_MAX is working as advertised: the exec is failing with more than ARG_MAX characters on the argument list- including, it should be noted, the environment data.

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

How can I upload files asynchronously?

This is my solution.

<form enctype="multipart/form-data">    

    <div class="form-group">
        <label class="control-label col-md-2" for="apta_Description">Description</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
        </div>
    </div>

    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

and the js

<script>

    $(':button').click(function () {
        var formData = new FormData($('form')[0]);
        $.ajax({
            url: '@Url.Action("Save", "Home")',  
            type: 'POST',                
            success: completeHandler,
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
    });    

    function completeHandler() {
        alert(":)");
    }    
</script>

Controller

[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
    [...]
}

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).

var prevdef=true;
var dosubmit=function(){
    if(prevdef==true){
        //here we can do something else first//
        prevdef=false;
        dosubmit();
    }
    else{
        $(this).submit();//which was the default action
    }
};

$('input#somebutton').click(function(){dosubmit()});

Uncaught TypeError: undefined is not a function while using jQuery UI

The issue because of not loading jquery ui library.

https://code.jquery.com/ui/1.11.4/jquery-ui.js - CDN source file

Call above path in your file.

Seeing the underlying SQL in the Spring JdbcTemplate?

This worked for me with log4j2 and xml parameters:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
    <Properties>
        <Property name="log-path">/some_path/logs/</Property>
        <Property name="app-id">my_app</Property>
    </Properties>

    <Appenders>
        <RollingFile name="file-log" fileName="${log-path}/${app-id}.log"
            filePattern="${log-path}/${app-id}-%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
                </pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>

        <Logger name="org.springframework.jdbc.core" level="trace" additivity="false">
            <appender-ref ref="file-log" />
            <appender-ref ref="console" />
        </Logger>

        <Root level="info" additivity="false">
            <appender-ref ref="file-log" />
            <appender-ref ref="console" />
        </Root>
    </Loggers>

</Configuration>

Result console and file log was:

JdbcTemplate - Executing prepared SQL query
JdbcTemplate - Executing prepared SQL statement [select a, b from c where id = ? ]
StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [my_id], value class [java.lang.String], SQL type unknown

Just copy/past

HTH

How to center cards in bootstrap 4?

You can also use Bootstrap 4 flex classes

Like: .align-item-center and .justify-content-center

We can use these classes identically for all device view.

Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center

.text-center class is used to align text in center.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

SQL Server copy all rows from one table into another i.e duplicate table

try this single command to both delete and insert the data:

DELETE MyTable
    OUTPUT DELETED.Col1, DELETED.COl2,...
        INTO MyBackupTable

working sample:

--set up the tables
DECLARE @MyTable table (col1 int, col2 varchar(5))
DECLARE @MyBackupTable table (col1 int, col2 varchar(5))
INSERT INTO @MyTable VALUES (1,'A')
INSERT INTO @MyTable VALUES (2,'B')
INSERT INTO @MyTable VALUES (3,'C')
INSERT INTO @MyTable VALUES (4,'D')

--single command that does the delete and inserts
DELETE @MyTable
    OUTPUT DELETED.Col1, DELETED.COl2
        INTO @MyBackupTable

--show both tables final values
select * from @MyTable
select * from @MyBackupTable

OUTPUT:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(4 row(s) affected)
col1        col2
----------- -----

(0 row(s) affected)

col1        col2
----------- -----
1           A
2           B
3           C
4           D

(4 row(s) affected)

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Change the database.php file from

$db['default']['dbdriver'] = 'mysql';

to

$db['default']['dbdriver'] = 'mysqli';

No process is on the other end of the pipe (SQL Server 2012)

The server was set to Windows Authentication only by default. There isn't any notification, that the origin of the errors is that, so it's hard to figure it out. The SQL Management studio dont alert, even if you create a user with SQL Authentication only.

So the answer is: Switch from Windows to SQL Authentication:

  1. Right click on the server name and select properties;
  2. Select security tab;
  3. Enable the SQL Server and Windows Authentication mode;
  4. Restart the SQL Server service.

You can now connect with your login/password.

jQuery Selector: Id Ends With?

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(where element is the type of element you're trying to find - eg div, input etc.

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

Signing a Windows EXE file

Another option, if you need to sign the executable on a Linux box is to use signcode from the Mono project tools. It is supported on Ubuntu.

convert float into varchar in SQL server without scientific notation

You will have to test your data VERY well. This can get messy. Here is an example of results simply by multiplying the value by 10. Run this to see what happens. On my SQL Server 2017 box, at the 3rd query I get a bunch of *********. If you CAST as BIGINT it should work every time. But if you don't and don't test enough data you could run into problems later on, so don't get sucked into thinking it will work on all of your data unless you test the maximum expected value.

 Declare @Floater AS FLOAT =100000003.141592653
    SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ), 
            CONVERT(VARCHAR(100),ROUND(@Floater,0)), 
            STR(@Floater)

    SET  @Floater =@Floater *10
    SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ), 
            CONVERT(VARCHAR(100),ROUND(@Floater,0)), 
            STR(@Floater)

    SET  @Floater =@Floater *100
    SELECT CAST(ROUND(@Floater,0) AS VARCHAR(30) ), 
            CONVERT(VARCHAR(100),ROUND(@Floater,0)), 
            STR(@Floater)

Why use prefixes on member variables in C++ classes

As others have already said, the importance is to be colloquial (adapt naming styles and conventions to the code base in which you're writing) and to be consistent.

For years I have worked on a large code base that uses both the "this->" convention as well as using a postfix underscore notation for member variables. Throughout the years I've also worked on smaller projects, some of which did not have any sort of convention for naming member variables, and other which had differing conventions for naming member variables. Of those smaller projects, I've consistently found those which lacked any convention to be the most difficult to jump into quickly and understand.

I'm very anal-retentive about naming. I will agonize over the name to be ascribed to a class or variable to the point that, if I cannot come up with something that I feel is "good", I will choose to name it something nonsensical and provide a comment describing what it really is. That way, at least the name means exactly what I intend it to mean--nothing more and nothing less. And often, after using it for a little while, I discover what the name should really be and can go back and modify or refactor appropriately.

One last point on the topic of an IDE doing the work--that's all nice and good, but IDEs are often not available in environments where I have perform the most urgent work. Sometimes the only thing available at that point is a copy of 'vi'. Also, I've seen many cases where IDE code completion has propagated stupidity such as incorrect spelling in names. Thus, I prefer to not have to rely on an IDE crutch.

Best way to compare 2 XML documents in Java

I required the same functionality as requested in the main question. As I was not allowed to use any 3rd party libraries, I have created my own solution basing on @Archimedes Trajano solution.

Following is my solution.

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Assert;
import org.w3c.dom.Document;

/**
 * Asserts for asserting XML strings.
 */
public final class AssertXml {

    private AssertXml() {
    }

    private static Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(ns\\d+)=\"(.*?)\"");

    /**
     * Asserts that two XML are of identical content (namespace aliases are ignored).
     * 
     * @param expectedXml expected XML
     * @param actualXml actual XML
     * @throws Exception thrown if XML parsing fails
     */
    public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {
        // Find all namespace mappings
        Map<String, String> fullnamespace2newAlias = new HashMap<String, String>();
        generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);
        generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);

        for (Entry<String, String> entry : fullnamespace2newAlias.entrySet()) {
            String newAlias = entry.getValue();
            String namespace = entry.getKey();
            Pattern nsReplacePattern = Pattern.compile("xmlns:(ns\\d+)=\"" + namespace + "\"");
            expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);
            actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);
        }

        // nomralize namespaces accoring to given mapping

        DocumentBuilder db = initDocumentParserFactory();

        Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName("UTF-8"))));
        expectedDocuemnt.normalizeDocument();

        Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName("UTF-8"))));
        actualDocument.normalizeDocument();

        if (!expectedDocuemnt.isEqualNode(actualDocument)) {
            Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse
        }
    }


    private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        dbf.setCoalescing(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db;
    }

    private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {
        Matcher nsMatcherExp = namespacePattern.matcher(xml);
        if (nsMatcherExp.find()) {
            xml = xml.replaceAll(nsMatcherExp.group(1) + "[:]", newAlias + ":");
            xml = xml.replaceAll(nsMatcherExp.group(1) + "=", newAlias + "=");
        }
        return xml;
    }

    private static void generateNewAliasesForNamespacesFromXml(String xml, Map<String, String> fullnamespace2newAlias) {
        Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);
        while (nsMatcher.find()) {
            if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {
                fullnamespace2newAlias.put(nsMatcher.group(2), "nsTr" + (fullnamespace2newAlias.size() + 1));
            }
        }
    }

}

It compares two XML strings and takes care of any mismatching namespace mappings by translating them to unique values in both input strings.

Can be fine tuned i.e. in case of translation of namespaces. But for my requirements just does the job.

Is there any method to get the URL without query string?

location.toString().replace(location.search, "")

AngularJS: Basic example to use authentication in Single Page Application

In angularjs you can create the UI part, service, Directives and all the part of angularjs which represent the UI. It is nice technology to work on.

As any one who new into this technology and want to authenticate the "User" then i suggest to do it with the power of c# web api. for that you can use the OAuth specification which will help you to built a strong security mechanism to authenticate the user. once you build the WebApi with OAuth you need to call that api for token:

_x000D_
_x000D_
var _login = function (loginData) {_x000D_
 _x000D_
        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
 _x000D_
        var deferred = $q.defer();_x000D_
 _x000D_
        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
 _x000D_
            localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
 _x000D_
            _authentication.isAuth = true;_x000D_
            _authentication.userName = loginData.userName;_x000D_
 _x000D_
            deferred.resolve(response);_x000D_
 _x000D_
        }).error(function (err, status) {_x000D_
            _logOut();_x000D_
            deferred.reject(err);_x000D_
        });_x000D_
 _x000D_
        return deferred.promise;_x000D_
 _x000D_
    };_x000D_
 
_x000D_
_x000D_
_x000D_

and once you get the token then you request the resources from angularjs with the help of Token and access the resource which kept secure in web Api with OAuth specification.

Please have a look into the below article for more help:-

http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/

Import SQL dump into PostgreSQL database

make sure the database you want to import to is created, then you can import the dump with

sudo -u postgres -i psql testdatabase < db-structure.sql

If you want to overwrite the whole database, first drop the database

# be sure you drop the right database !!!
#sudo -u postgres -i psql -c "drop database testdatabase;"

and then recreate it with

sudo -u postgres -i psql -c "create database testdatabase;"

Downloading an entire S3 bucket?

Here is some stuff to download all buckets, list them, list their contents.

    //connection string
    private static void dBConnection() {
    app.setAwsCredentials(CONST.getAccessKey(), CONST.getSecretKey());
    conn = new AmazonS3Client(app.getAwsCredentials());
    app.setListOfBuckets(conn.listBuckets());
    System.out.println(CONST.getConnectionSuccessfullMessage());
    }

    private static void downloadBucket() {

    do {
        for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
            app.setBucketKey(objectSummary.getKey());
            app.setBucketName(objectSummary.getBucketName());
            if(objectSummary.getKey().contains(CONST.getDesiredKey())){
                //DOWNLOAD
                try 
                {
                    s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
                    s3Client.getObject(
                            new GetObjectRequest(app.getBucketName(),app.getBucketKey()),
                            new File(app.getDownloadedBucket())
                            );
                } catch (IOException e) {
                    e.printStackTrace();
                }

                do
                {
                     if(app.getBackUpExist() == true){
                        System.out.println("Converting back up file");
                        app.setCurrentPacsId(objectSummary.getKey());
                        passIn = app.getDataBaseFile();
                        CONVERT= new DataConversion(passIn);
                        System.out.println(CONST.getFileDownloadedMessage());
                    }
                }
                while(app.getObjectExist()==true);

                if(app.getObjectExist()== false)
                {
                    app.setNoObjectFound(true);
                }
            }
        }
        app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
    } 
    while (app.getS3Object().isTruncated());
}

/----------------------------Extension Methods-------------------------------------/

//Unzip bucket after download 
public static void unzipBucket() throws IOException {
    unzip = new UnZipBuckets();
    unzip.unZipIt(app.getDownloadedBucket());
    System.out.println(CONST.getFileUnzippedMessage());
}

//list all S3 buckets
public static void listAllBuckets(){
    for (Bucket bucket : app.getListOfBuckets()) {
        String bucketName = bucket.getName();
        System.out.println(bucketName + "\t" + StringUtils.fromDate(bucket.getCreationDate()));
    }
}

//Get the contents from the auto back up bucket
public static void listAllBucketContents(){     
    do {
        for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
            if(objectSummary.getKey().contains(CONST.getDesiredKey())){
                System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
                app.setBackUpCount(app.getBackUpCount() + 1);   
            }
        }
        app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
    } 
    while (app.getS3Object().isTruncated());
    System.out.println("There are a total of : " + app.getBackUpCount() + " buckets.");
}

}

How do you remove an invalid remote branch reference from Git?

I had a similar problem. None of the answers helped. In my case, I had two removed remote repositories showing up permanently.

My last idea was to remove all references to it by hand.

Let's say the repository is called “Repo”. I did:

find .git -name Repo 

So, I deleted the corresponding files and directories from the .git folder (this folder could be found in your Rails app or on your computer https://stackoverflow.com/a/19538763/6638513).

Then I did:

grep Repo -r .git

This found some text files in which I removed the corresponding lines. Now, everything seems to be fine.

Usually, you should leave this job to git.

Javascript / Chrome - How to copy an object from the webkit inspector as code

Right click on data which you want to store

  • Firstly, Right click on data which you want to store -> select "Store as global variable" And the new temp variable appear like bellow: (temp3 variable): New temp variable appear in console
  • Second use command copy(temp_variable_name) like picture: enter image description here After that, you can paste data to anywhere you want. hope useful/

Defining a variable with or without export

Others have answered that export makes the variable available to subshells, and that is correct but merely a side effect. When you export a variable, it puts that variable in the environment of the current shell (ie the shell calls putenv(3) or setenv(3)).
The environment of a process is inherited across exec, making the variable visible in subshells.

Edit (with 5 year's perspective): this is a silly answer. The purpose of 'export' is to make variables "be in the environment of subsequently executed commands", whether those commands be subshells or subprocesses. A naive implementation would be to simply put the variable in the environment of the shell, but this would make it impossible to implement export -p.

CMD what does /im (taskkill)?

it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe

Missing Push Notification Entitlement

In XCode 8 you need to enable push in the Capabilities tab on your target, on top of enabling everything on the provisions and certificates: Xcode 8 "the aps-environment entitlement is missing from the app's signature" on submit

My blog post about this here.

How do you tell if a checkbox is selected in Selenium for Java?

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

How to get cell value from DataGridView in VB.Net?

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

Using LINQ to concatenate strings

You can combine LINQ and string.join() quite effectively. Here I am removing an item from a string. There are better ways of doing this too but here it is:

filterset = String.Join(",",
                        filterset.Split(',')
                                 .Where(f => mycomplicatedMatch(f,paramToMatch))
                       );

How to get featured image of a product in woocommerce

I had the same problem and solved it by using the default woocommerce hook to display the product image.

while ( $loop->have_posts() ) : $loop->the_post();
   echo woocommerce_get_product_thumbnail('woocommerce_full_size');
endwhile;

Available parameters:

  • woocommerce_thumbnail
  • woocommerce_full_size

Computing cross-correlation function?

To cross-correlate 1d arrays use numpy.correlate.

For 2d arrays, use scipy.signal.correlate2d.

There is also scipy.stsci.convolve.correlate2d.

There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.

See this post on the SciPy mailing list for some links to different implementations.

Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.

How to iterate over a column vector in Matlab?

In Matlab, you can iterate over the elements in the list directly. This can be useful if you don't need to know which element you're currently working on.

Thus you can write

for elm = list
%# do something with the element
end

Note that Matlab iterates through the columns of list, so if list is a nx1 vector, you may want to transpose it.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

In NHibernate (with NHibernate.Linq) you could do it as follows:

return session.Query<T>()
              .Single(a => a.Filter == filter &&
                           a.Id == session.Query<T>()
                                          .Where(a2 => a2.Filter == filter)
                                          .Max(a2 => a2.Id));

Which will generate SQL like follows:

select *
from TableName foo
where foo.Filter = 'Filter On String'
and foo.Id = (select cast(max(bar.RowVersion) as INT)
              from TableName bar
              where bar.Name = 'Filter On String')

Which seems pretty efficient to me.

How to detect the OS from a Bash script?

Try using "uname". For example, in Linux: "uname -a".

According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.

BTW: $OSTYPE is also set to linux-gnu here :)

Playing a MP3 file in a WinForm application

You can do it using old DirectShow functionality.

This answer teaches you how to create QuartzTypeLib.dll:

  1. Run tlbimp tool (in your case path will be different):

  2. Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll

Alternatively, this project contains the library interop.QuartzTypeLib.dll, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:

  1. Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")

  2. In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).

  3. In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266

  4. Use this class to play your favorite MP3 file:

    using QuartzTypeLib;
    
    public sealed class DirectShowPlayer
    {
        private FilgraphManager FilterGraph;
    
        public void Play(string path)
        {
            FilgraphManager = new FilgraphManager();
            FilterGraph.RenderFile(path);
            FilterGraph.Run();
        }
    
        public void Stop()
        {
            FilterGraph?.Stop();
        }
    }
    

PS: TlbImp.exe can be found here: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin", or in "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"

How to implement a read only property

You can do this:

public int Property { get { ... } private set { ... } }

How do I get user IP address in django?

Alexander's answer is great, but lacks the handling of proxies that sometimes return multiple IP's in the HTTP_X_FORWARDED_FOR header.

The real IP is usually at the end of the list, as explained here: http://en.wikipedia.org/wiki/X-Forwarded-For

The solution is a simple modification of Alexander's code:

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[-1].strip()
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

java.util.Date vs java.sql.Date

I had the same issue, the easiest way i found to insert the current date into a prepared statement is this one:

preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));

calculating the difference in months between two dates

If you want the exact number, you can't from just the Timespan, since you need to know which months you're dealing, and whether you're dealing with a leap year, like you said.

Either go for an approximate number, or do some fidgetting with the original DateTimes

What's the difference between struct and class in .NET?

+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
|                        |                                                Struct                                                |                                               Class                                               |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
| Type                   | Value-type                                                                                           | Reference-type                                                                                    |
| Where                  | On stack / Inline in containing type                                                                 | On Heap                                                                                           |
| Deallocation           | Stack unwinds / containing type gets deallocated                                                     | Garbage Collected                                                                                 |
| Arrays                 | Inline, elements are the actual instances of the value type                                          | Out of line, elements are just references to instances of the reference type residing on the heap |
| Aldel Cost             | Cheap allocation-deallocation                                                                        | Expensive allocation-deallocation                                                                 |
| Memory usage           | Boxed when cast to a reference type or one of the interfaces they implement,                         | No boxing-unboxing                                                                                |
|                        | Unboxed when cast back to value type                                                                 |                                                                                                   |
|                        | (Negative impact because boxes are objects that are allocated on the heap and are garbage-collected) |                                                                                                   |
| Assignments            | Copy entire data                                                                                     | Copy the reference                                                                                |
| Change to an instance  | Does not affect any of its copies                                                                    | Affect all references pointing to the instance                                                    |
| Mutability             | Should be immutable                                                                                  | Mutable                                                                                           |
| Population             | In some situations                                                                                   | Majority of types in a framework should be classes                                                |
| Lifetime               | Short-lived                                                                                          | Long-lived                                                                                        |
| Destructor             | Cannot have                                                                                          | Can have                                                                                          |
| Inheritance            | Only from an interface                                                                               | Full support                                                                                      |
| Polymorphism           | No                                                                                                   | Yes                                                                                               |
| Sealed                 | Yes                                                                                                  | When have sealed keyword                                                                          |
| Constructor            | Can not have explicit parameterless constructors                                                     | Any constructor                                                                                   |
| Null-assignments       | When marked with nullable question mark                                                              | Yes (+ When marked with nullable question mark in C# 8+)                                          |
| Abstract               | No                                                                                                   | When have abstract keyword                                                                        |
| Member Access Modifiers| public, private, internal                                                                            | public, protected, internal, protected internal, private protected                                |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+

Facebook Graph API : get larger pictures in one request

From v2.7, /<picture-id>?fields=images will give you a list with different size of the images, the first element being the full size image.

I don't know of any solution for multiple images at once.

Animate background image change with jQuery

Have a look at this jQuery plugin from OvalPixels.

It may do the trick.

ImportError: No module named PytQt5

pip install pyqt5 for python3 for ubuntu

How to get a Static property with Reflection

The below seems to work for me.

using System;
using System.Reflection;

public class ReflectStatic
{
    private static int SomeNumber {get; set;}
    public static object SomeReference {get; set;}
    static ReflectStatic()
    {
        SomeReference = new object();
        Console.WriteLine(SomeReference.GetHashCode());
    }
}

public class Program
{
    public static void Main()
    {
        var rs = new ReflectStatic();
        var pi = rs.GetType().GetProperty("SomeReference",  BindingFlags.Static | BindingFlags.Public);
        if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
        Console.WriteLine(pi.GetValue(rs, null).GetHashCode());


    }
}

Changing password with Oracle SQL Developer

you can find the user in DBA_USERS table like

SELECT profile
FROM dba_users
WHERE username = 'MacsP'

Now go to the sys/system (administrator) and use query

ALTER USER PRATEEK
IDENTIFIED BY "new_password"
REPLACE "old_password"

To verify the account status just go through

SELECT * FROM DBA_USERS.

and you can see status of your user.

When would you use the Builder Pattern?

I always disliked the Builder pattern as something unwieldy, obtrusive and very often abused by less experienced programmers. Its a pattern which only makes sense if you need to assemble the object from some data which requires a post-initialisation step (i.e. once all the data is collected - do something with it). Instead, in 99% of the time builders are simply used to initialise the class members.

In such cases it is far better to simply declare withXyz(...) type setters inside the class and make them return a reference to itself.

Consider this:

public class Complex {

    private String first;
    private String second;
    private String third;

    public String getFirst(){
       return first; 
    }

    public void setFirst(String first){
       this.first=first; 
    }

    ... 

    public Complex withFirst(String first){
       this.first=first;
       return this; 
    }

    public Complex withSecond(String second){
       this.second=second;
       return this; 
    }

    public Complex withThird(String third){
       this.third=third;
       return this; 
    }

}


Complex complex = new Complex()
     .withFirst("first value")
     .withSecond("second value")
     .withThird("third value");

Now we have a neat single class that manages its own initialization and does pretty much the same job as the builder, except that its far more elegant.

Get difference between two lists

In case you want the difference recursively, I have written a package for python: https://github.com/seperman/deepdiff

Installation

Install from PyPi:

pip install deepdiff

Example usage

Importing

>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2

Same object returns empty

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}

Type of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
                                 'newvalue': '2',
                                 'oldtype': <class 'int'>,
                                 'oldvalue': 2}}}

Value of an item has changed

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

Item added and/or removed

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
 'dic_item_removed': ['root[4]'],
 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

String difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
                      "root[4]['b']": { 'newvalue': 'world!',
                                        'oldvalue': 'world'}}}

String difference 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
                                                '+++ \n'
                                                '@@ -1,5 +1,4 @@\n'
                                                '-world!\n'
                                                '-Goodbye!\n'
                                                '+world\n'
                                                ' 1\n'
                                                ' 2\n'
                                                ' End',
                                        'newvalue': 'world\n1\n2\nEnd',
                                        'oldvalue': 'world!\n'
                                                    'Goodbye!\n'
                                                    '1\n'
                                                    '2\n'
                                                    'End'}}}

>>> 
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
--- 
+++ 
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
 1
 2
 End

Type change

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
                                      'newvalue': 'world\n\n\nEnd',
                                      'oldtype': <class 'list'>,
                                      'oldvalue': [1, 2, 3]}}}

List difference

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}

List difference 2:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
  'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
                      "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}

List difference ignoring order or duplicates: (with the same dictionaries as above)

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}

List that contains dictionary:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
  'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}

Sets:

>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}

Named Tuples:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}

Custom objects:

>>> class ClassA(object):
...     a = 1
...     def __init__(self, b):
...         self.b = b
... 
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>> 
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

Object attribute added:

>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

Regular expression to extract URL from an HTML link

If you're only looking for one:

import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
    print(match.group(1))

If you have a long string, and want every instance of the pattern in it:

import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print(', '.join(urls))

Where s is the string that you're looking for matches in.

Quick explanation of the regexp bits:

r'...' is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\ especially -- in a raw string a \ is just a \. In a regular string you'd have to do \\ every time, and that gets old in regexps.)

"href=[\'"]?" says to match "href=", possibly followed by a ' or ". "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.

Enclosing the next bit in "()" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in."

"[^\'" >]+" says to match any characters that aren't ', ", >, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.

The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.

It's pretty easy to do:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
    print(tag['href'])

Once you've installed BeautifulSoup, anyway.

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

How to detect if a stored procedure already exists

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[xxx]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
CREATE PROCEDURE dbo.xxx

where xxx is the proc name

CentOS 7 and Puppet unable to install nc

You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:

root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}

#we capture release hash
$curr_os = $os['release']

case $curr_os['major'] {
  '7': { .... something }
  *: {something}
}

That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.

The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.

How to Install Sublime Text 3 using Homebrew

I originally used this page to solve the same problem in the past - however it would appear as if the sublime-text cask has been updated to now be the most recent release of Sublime Text 3. No workarounds are necessary anymore.

Installation is as simple as brew cask install sublime-text.

The changelog for Sublime Text 3 downloaded from the <code>sublime-text</code> cask.

Executing an EXE file using a PowerShell script

It looks like you're specifying both the EXE and its first argument in a single string e.g; '"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode'. This won't work. In general you invoke a native command that has a space in its path like so:

& "c:\some path with spaces\foo.exe" <arguments go here>

That is & expects to be followed by a string that identifies a command: cmdlet, function, native exe relative or absolute path.

Once you get just this working:

& "c:\some path with spaces\foo.exe"

Start working on quoting of the arguments as necessary. Although it looks like your arguments should be just fine (no spaces, no other special characters interpreted by PowerShell).

What is The difference between ListBox and ListView

Listview derives from listbox control. One most important difference is listview uses the extended selection mode by default . listview also adds a property called view which enables you to customize the view in a richer way than a custom itemspanel. One real life example of listview with gridview is file explorer's details view. Listview with grid view is a less powerful data grid. After the introduction of datagrid control listview lost its importance.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

How to iterate using ngFor loop Map containing key as string and values as map iteration

Angular’s keyvalue pipe can be used, but unfortunately it sorts by key. Maps already have an order and it would be great to be able to keep it!

We can define out own pipe mapkeyvalue which preserves the order of items in the map:

import { Pipe, PipeTransform } from '@angular/core';

// Holds a weak reference to its key (here a map), so if it is no longer referenced its value can be garbage collected.
const cache = new WeakMap<ReadonlyMap<any, any>, Array<{ key: any; value: any }>>();

@Pipe({ name: 'mapkeyvalue', pure: true })
export class MapKeyValuePipe implements PipeTransform {
  transform<K, V>(input: ReadonlyMap<K, V>): Iterable<{ key: K; value: V }> {
    const existing = cache.get(input);
    if (existing !== undefined) {
      return existing;
    }

    const iterable = Array.from(input, ([key, value]) => ({ key, value }));
    cache.set(input, iterable);
    return iterable;
  }
}

It can be used like so:

<mat-select>
  <mat-option *ngFor="let choice of choicesMap | mapkeyvalue" [value]="choice.key">
    {{ choice.value }}
  </mat-option>
</mat-select>

How can I make XSLT work in chrome?

After 8 years the situation is changed a bit.

I'm unable to open a new session of Google Chrome without other parameters and allow 'file:' schema.

On macOS I do:

open -n -a "Google Chrome" --args \
    --disable-web-security \               # This disable all CORS and other security checks
    --user-data-dir=$HOME/fakeChromeDir    # This let you to force open a new Google Chrome session

Without this arguments I'm unable to test the XSL stylesheet in local.

how to enable sqlite3 for php?

one thing I want to add , before you try to install

apt-get install php5-sqlite

or

apt-get install php5-sqlite3 

search the given package is available or not :-

 # apt-cache search 'php5'

After that you get :-

php5-rrd - rrd module for PHP 5

php5-sasl - Cyrus SASL extension for PHP 5

php5-snmp - SNMP module for php5

**php5-sqlite - SQLite module for php5**

php5-svn - PHP Bindings for the Subversion Revision control system

php5-sybase - Sybase / MS SQL Server module for php5

Here you get an idea about whether your version support or not .. in my system I get php5-sqlite - SQLite module for php5 so I prefer to install

**apt-get install php5-sqlite**

Maximum value for long integer

Python long can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf'), since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf').

Could not load file or assembly 'System.Web.Mvc'

If your NOT using a hosting provider, and you have access to the server to install ... Then install the MVC 3 update tools, do that... it will save you hours of problems on a windows 2003 server / IIS6 machine. , I commented on this page here Nuget.Core.dll version number mismatch

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

How do you list the primary key of a SQL Server table?

SELECT Col.Column_Name from 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE 
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY'
    AND Col.Table_Name = '<your table name>'

SELECTING with multiple WHERE conditions on same column

SELECT contactid, Count(*) 
FROM <YOUR_TABLE> WHERE flag in ('Volunteer','Uploaded')  
GROUP BY contactid 
HAVING count(*)>1;

How to add a classname/id to React-Bootstrap Component?

If you look at the code for the component you can see that it uses the className prop passed to it to combine with the row class to get the resulting set of classes (<Row className="aaa bbb"... works).Also, if you provide the id prop like <Row id="444" ... it will actually set the id attribute for the element.

Android Fragment handle back button press

If you want to handle hardware Back key event than you have to do following code in your onActivityCreated() method of Fragment.

You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.

Also, If your rootview(getView()) will not contain focus then it will not work. If you have clicked on any control then again you need to give focus to rootview using getView().requestFocus(); After this only onKeydown() will call.

getView().setFocusableInTouchMode(true);
getView().requestFocus();

getView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        Toast.makeText(getActivity(), "Back Pressed", Toast.LENGTH_SHORT).show();
                    return true;
                    }
                }
                return false;
            }
        });

Working very well for me.

css ellipsis on second line

I found a solution however you need to know a rough character length that will fit in to your text area, then join a ... to the preceeding space.

The way I did this is to:

  1. assume a rough character length (in this case 200) and pass to a function along with your text
  2. split the spaces so you have one long string
  3. use jQuery to get slice the first " " space after your character length
  4. join the remaining ...

code :

truncate = function(description){
        return description.split('').slice(0, description.lastIndexOf(" ",200)).join('') + "...";           
}

here is a fiddle - http://jsfiddle.net/GYsW6/1/

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

None of these worked for me.

My class libraries were definitely all referencing both System.Core and Microsoft.CSharp. Web Application was 4.0 and couldn't upgrade to 4.5 due to support issues.

I was encountering the error compiling a razor template using the Razor Engine, and only encountering it intermittently, like after web application has been restarted.

The solution that worked for me was manually loading the assembly then reattempting the same operation...

        bool retry = true;
        while (retry)
        {
            try
            {
                string textTemplate = File.ReadAllText(templatePath);
                Razor.CompileWithAnonymous(textTemplate, templateFileName);
                retry = false;
            }
            catch (TemplateCompilationException ex)
            {
                LogTemplateException(templatePath, ex);
                retry = false;

                if (ex.Errors.Any(e  => e.ErrorNumber == "CS1969"))
                {
                    try
                    {
                        _logger.InfoFormat("Attempting to manually load the Microsoft.CSharp.RuntimeBinder.Binder");
                        Assembly csharp = Assembly.Load("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        Type type = csharp.GetType("Microsoft.CSharp.RuntimeBinder.Binder");
                        retry = true;
                    }
                    catch(Exception exLoad)
                    {
                        _logger.Error("Failed to manually load runtime binder", exLoad);
                    }
                }

                if (!retry)
                    throw;
            }
        }

Hopefully this might help someone else out there.

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Constructor overloading in Java - best practice

Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.

The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.

For further details about java constructor, please visit https://tecloger.com/constructor-in-java/

Refresh Excel VBA Function Results

To switch to Automatic:

Application.Calculation = xlCalculationAutomatic    

To switch to Manual:

Application.Calculation = xlCalculationManual    

JMS Topic vs Queues

TOPIC:: topic is one to many communication... (multipoint or publish/subscribe) EX:-imagine a publisher publishes the movie in the youtub then all its subscribers will gets notification.... QUEVE::queve is one-to-one communication ... Ex:-When publish a request for recharge it will go to only one qreciever ... always remember if request goto all qreceivers then multiple recharge happened so while developing analyze which is fit for a application

How to pass variables from one php page to another without form?

You can pass via GET. So if you want to pass the value foobar from PageA.php to PageB.php, call it as PageB.php?value=foobar.

In PageB.php, you can access it this way:

$value = $_GET['value'];

How to get row count in sqlite using Android?

Change your getTaskCount Method to this:

public int getTaskCount(long tasklist_id){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
    cursor.moveToFirst();
    int count= cursor.getInt(0);
    cursor.close();
    return count;
}

Then, update the click handler accordingly:

public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
    db = new TodoTask_Database(getApplicationContext());

    // Get task list id
    int tasklistid = adapter.getItem(position).getTaskListId();

    if(db.getTaskCount(tasklistid) > 0) {    
        System.out.println(c);
        Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
        taskListID.putExtra("TaskList_ID", tasklistid);
        startActivity(taskListID);
    } else {
        Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
        startActivity(addTask);
    }
}

Difference between const reference and normal parameter

There are three methods you can pass values in the function

  1. Pass by value

    void f(int n){
        n = n + 10;
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: 3. Disadvantage: When parameter x pass through f function then compiler creates a copy in memory in of x. So wastage of memory.

  2. Pass by reference

    void f(int& n){
        n = n + 10;
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference

  3. Constant reference

    void f(const int& n){
        n = n + 10; // Error: assignment of read-only reference  ‘n’
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: Throw error at n = n + 10 because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.

How do I use Maven through a proxy?

Those are caused most likely by 2 issues:

  1. You need to add proxy configuration to your settings.xml. Here's a trick in your username field. Make sure it looks like domain\username. Setting domain there and putting this exact slash is important '\'. You might want to use <![CDATA[]]> tag if your password contains non xml-friendly characters.
  2. I've noticed maven 2.2.0 does not work sometimes through a proxy at all, where 2.2.1 works perfectly fine.

If some of those are omitted - maven could fail with random error messages.

Just hope I've saved somebody from googling around this issue for 6 hours, like I did.

How to check if array is not empty?

I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:

if l:
    print "list has items"

elif not l:
    print "list is empty"

the error will be:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()