Programs & Examples On #Openlayers

OpenLayers is an open source Javascript web mapping library for creating web map applications.

Access to Image from origin 'null' has been blocked by CORS policy

A solution to this is to serve your code, and make it run on a server, you could use web server for chrome to easily serve your pages.

Attaching click event to a JQuery object not yet added to the DOM

On event

$('#my-button').on('click', function () {
    console.log("yeahhhh!!! but this doesn't work for me :(");
});

Or add the event after append

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

How do I display images from Google Drive on a website?

A couple interesting alternatives to publicly hosting an image on Drive (deprecated):

1. Google Photos

If you upload an image to Google Photos instead of Drive it gets a public web link.

This behavior is a little surprising to me, but the link is very long and random, so they are apparently practicing "privacy by obscurity."

2. Google Drawing

If you create an image using the "Google Drawing" program (built into Drive) you can press File > Publish to Web to get a public link.

enter image description here

Note: This could be a solution if you're trying to share an existing image-- paste the image into the editor and crop the canvas to your image (file > Page Setup)-- but it's a little cumbersome. If you need to do some basic image editing, though, or if you're trying create a simple icon/graphic, I think this is nifty.

Improving bulk insert performance in Entity framework

 Use : db.Set<tale>.AddRange(list); 
Ref :
TESTEntities db = new TESTEntities();
List<Person> persons = new List<Person> { 
new  Person{Name="p1",Place="palce"},
new  Person{Name="p2",Place="palce"},
new  Person{Name="p3",Place="palce"},
new  Person{Name="p4",Place="palce"},
new  Person{Name="p5",Place="palce"}
};
db.Set<Person>().AddRange(persons);
db.SaveChanges();

How can I use SUM() OVER()

Query would be like this:

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 

       FROM #Empl ORDER BY AccountID

Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

so result would appear like attached snapshot.

When is a language considered a scripting language?

Scripting languages were originally thought of as a control mechanisms for applications written in a hard programming language. The compiled programs could not be modified at runtime, so scripting gave people flexibility.

Most notably, shell script was automating processes in the OS kernel (traditionally, AppleScript on Macs); a role which more and more passed into Perl's hands, and then out of it into Python lately. I've seen Scheme (particularly in its Guile implementation) used to declare raytracing scenes; and recently, Lua is very popular as the programming language to script games - to the point that the only hard-coded thing in many new games is the graphics/physics engine, while the whole game logic is encoded in Lua. In the same way, JavaScript was thought to script the behaviour of a web browser.

The languages emancipated; no-one now thinks about the OS as an application (or thinks about it much at all), and many formerly scripting languages began to be used to write full applications of their own. The name itself became meaningless, and spread to many interpreted languages in use today, regardless of whether they are designed to be interpreted from within another system or not.

However, "scripting languages" is most definitely not synonymous with "interpreted languages" - for instance, BASIC was interpreted for most of its life (i.e. before it lost its acronimicity and became Visual Basic), yet no-one really thinks of it as scripting.

UPDATE: Reading material as usual available at Wikipedia.

Bulk Record Update with SQL

Or you can simply update without using join like this:

Update t1 set  t1.Description = t2.Description from @tbl2 t2,tbl1 t1
where t1.ID= t2.ID

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

PadLeft function in T-SQL

Try this:

SELECT RIGHT(REPLICATE('0',4)+CAST(Id AS VARCHAR(4)),4) FROM [Table A]

Change the selected value of a drop-down list with jQuery

<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
     <asp:ListItem Value="1" Text="aaa"></asp:ListItem>
     <asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>

ClientIDMode="Static"

$('#DropUserType').val('1');

How to use jQuery to show/hide divs based on radio button selection?

I wrote a simple code to unterstand you to how to make a show and hide radio buttons in jquery its very simple

<div id="myRadioGroup">

    Value Based<input type="radio" name="cars" checked="checked" value="2"  />

    Percent Based<input type="radio" name="cars" value="3" />
    <br>
    <div id="Cars2" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Value</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        <br>
        <label for="txtPassportNumber">Commission Percent</label>
       <input type="text" id="txtPassportNumber" class="form-control" />
    </div>
</div>
</div>

Jquery code

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

give me comments

Chrome desktop notification example

In modern browsers, there are two types of notifications:

  • Desktop notifications - simple to trigger, work as long as the page is open, and may disappear automatically after a few seconds
  • Service Worker notifications - a bit more complicated, but they can work in the background (even after the page is closed), are persistent, and support action buttons

The API call takes the same parameters (except for actions - not available on desktop notifications), which are well-documented on MDN and for service workers, on Google's Web Fundamentals site.


Below is a working example of desktop notifications for Chrome, Firefox, Opera and Safari. Note that for security reasons, starting with Chrome 62, permission for the Notification API may no longer be requested from a cross-origin iframe, so we can't demo this using StackOverflow's code snippets. You'll need to save this example in an HTML file on your site/application, and make sure to use localhost:// or HTTPS.

_x000D_
_x000D_
// request permission on page load_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
 if (!Notification) {_x000D_
  alert('Desktop notifications not available in your browser. Try Chromium.');_x000D_
  return;_x000D_
 }_x000D_
_x000D_
 if (Notification.permission !== 'granted')_x000D_
  Notification.requestPermission();_x000D_
});_x000D_
_x000D_
_x000D_
function notifyMe() {_x000D_
 if (Notification.permission !== 'granted')_x000D_
  Notification.requestPermission();_x000D_
 else {_x000D_
  var notification = new Notification('Notification title', {_x000D_
   icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',_x000D_
   body: 'Hey there! You\'ve been notified!',_x000D_
  });_x000D_
  notification.onclick = function() {_x000D_
   window.open('http://stackoverflow.com/a/13328397/1269037');_x000D_
  };_x000D_
 }_x000D_
}
_x000D_
 <button onclick="notifyMe()">Notify me!</button>
_x000D_
_x000D_
_x000D_

We're using the W3C Notifications API. Do not confuse this with the Chrome extensions notifications API, which is different. Chrome extension notifications obviously only work in Chrome extensions, and don't require any special permission from the user.

W3C notifications work in many browsers (see support on caniuse), and require user permission. As a best practice, don't ask for this permission right off the bat. Explain to the user first why they would want notifications and see other push notifications patterns.

Note that Chrome doesn't honor the notification icon on Linux, due to this bug.

Final words

Notification support has been in continuous flux, with various APIs being deprecated over the last years. If you're curious, check the previous edits of this answer to see what used to work in Chrome, and to learn the story of rich HTML notifications.

Now the latest standard is at https://notifications.spec.whatwg.org/.

As to why there are two different calls to the same effect, depending on whether you're in a service worker or not - see this ticket I filed while I worked at Google.

See also notify.js for a helper library.

How to sort a list of strings numerically?

scores = ['91','89','87','86','85']
scores.sort()
print (scores)

This worked for me using python version 3, though it didn't in version 2.

Is JavaScript a pass-by-reference or pass-by-value language?

Semantics!! Setting concrete definitions will necessarily make some answers and comments incompatible since they are not describing the same thing even when using the same words and phrases, but it is critical to get past the confusion (especially for new programmers).

First of all, there are multiple levels of abstraction that not everyone seems to grasp. Newer programmers who have learned on 4th or 5th generation languages may have difficulty wrapping their mind around concepts familiar to assembly or C programmers not phased by pointers to pointers to pointers. Pass-by-reference does not simply mean the ability to change a referenced object using a function parameter variable.

Variable: Combined concept of a symbol which references a value at a particular location in memory. This term is usually too loaded to be used alone in discussing details.

Symbol: Text string used to refer to variable (i.e. variable's name).

Value: Particular bits stored in memory and referenced using variable's symbol.

Memory location: Where a variable's value is stored. (The location itself is represented by a number separate from the value stored at the location.)

Function parameter: Variable declared in a function definition, used for referencing variables passed to the function.

Function argument: Variable outside the function which is passed to the function by the caller.

Object variable: Variable whose basic underlying value is not the "object" itself, rather its value is a pointer (memory location value) to another location in memory where the object's actual data is stored. In most higher-generation languages, the "pointer" aspect is effectively hidden by automatic de-referencing in various contexts.

Primitive variable: Variable whose value IS the actual value. Even this concept can be complicated by auto-boxing and object-like contexts of various languages, but the general ideas is that the variable's value IS the actual value represented by the variable's symbol rather than a pointer to another memory location.

Function arguments and parameters are not the same thing. Also, a variable's value is not the variable's object (as already pointed out by various people, but apparently ignored). These distinctions are critical to proper understanding.

Pass-by-value or Call-by-sharing (for objects): The function argument's value is COPIED to another memory location which is referenced by the function's parameter symbol (regardless of whether it's on the stack or heap). In other words, the function parameter received a copy of the passed argument's value... AND (critical) the argument's value IS NEVER UPDATED / ALTERED / CHANGED by the calling function. Remember, an object variable's value is NOT the object itself, rather it is the pointer to the object, so passing an object variable by value copies the pointer to the function parameter variable. The function parameter's value points to the exact same object in memory. The object data itself can be altered directly via the function parameter, BUT the function argument's value IS NEVER UPDATED, so it will continue to point to the same object throughout and even after the function call (even if its object's data was altered or if the function parameter is assigned a different object altogether). It is incorrect to conclude that the function argument was passed by reference just because the referenced object is updatable via the function parameter variable.

Call / Pass-by-reference: The function argument's value can/will be updated directly by the corresponding function parameter. If it helps, the function parameter becomes an effective "alias" for the argument--they effectively refer to the same value at the same memory location. If a function argument is an object variable, the ability to change the object's data is no different than the pass-by-value case since the function parameter will still point to the same object as the argument. But in the object variable case, if the function parameter is set to a completely different object, then the argument will likewise also point to the different object--this does not happen in the pass-by-value case.

JavaScript does not pass by reference. If you read closely, you will realize that all contrary opinions misunderstand what is meant by pass-by-value and they falsely conclude that the ability to update an object's data via the function parameter is synonymous to "pass-by-value".

Object clone/copy: A new object is created and the original object's data is copied. This can be a deep copy or shallow copy, but the point is that a new object is created. Creating a copy of an object is a separate concept from pass-by-value. Some languages distinguish between class object and structs (or the like), and may have different behavior for passing variables of the different types. But JavaScript does not do anything like this automatically when passing object variables. But the absence of automatic object cloning does not translate to pass-by-reference.

How do I "un-revert" a reverted Git commit?

If you haven't pushed that change yet, git reset --hard HEAD^

Otherwise, reverting the revert is perfectly fine.

Another way is to git checkout HEAD^^ -- . and then git add -A && git commit.

Java: Clear the console

By combining all the given answers, this method should work on all environments:

public static void clearConsole() {
    try {
        if (System.getProperty("os.name").contains("Windows")) {
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        }
        else {
            System.out.print("\033\143");
        }
    } catch (IOException | InterruptedException ex) {}
}

Get position/offset of element relative to a parent container?

I did it like this in Internet Explorer.

function getWindowRelativeOffset(parentWindow, elem) {
    var offset = {
        left : 0,
        top : 0
    };
    // relative to the target field's document
    offset.left = elem.getBoundingClientRect().left;
    offset.top = elem.getBoundingClientRect().top;
    // now we will calculate according to the current document, this current
    // document might be same as the document of target field or it may be
    // parent of the document of the target field
    var childWindow = elem.document.frames.window;
    while (childWindow != parentWindow) {
        offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
        offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
        childWindow = childWindow.parent;
    }

    return offset;
};

=================== you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus on IE only as per my focus but similar things can be done for other browsers.

Difference between java.exe and javaw.exe

java.exe is the command where it waits for application to complete untill it takes the next command. javaw.exe is the command which will not wait for the application to complete. you can go ahead with another commands.

jQuery click event on radio button doesn't get fired

Personally, for me, the best solution for a similar issue was:

HTML

<input type="radio" name="selectAll" value="true" />
<input type="radio" name="selectAll" value="false" />

JQuery

var $selectAll = $( "input:radio[name=selectAll]" );
    $selectAll.on( "change", function() {
         console.log( "selectAll: " + $(this).val() );
         // or
         alert( "selectAll: " + $(this).val() );
    });

*The event "click" can work in place of "change" as well.

Hope this helps!

Intellij JAVA_HOME variable

So far, nobody has answered the actual question.

Someone can figure what is happening ?

The problem here is that while the value of your $JAVA_HOME is correct, you defined it in the wrong place.

  • When you open a terminal and launch a Bash session, it will read the ~/.bash_profile file. Thus, when you enter echo $JAVA_HOME, it will return the value that has been set there.
  • When you launch IntelliJ directly, it will not read ~/.bash_profile … why should it? So to IntelliJ, this variable is not set.

There are two possible solutions to this:

  • Launch IntelliJ from a Bash session: open a terminal and run "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea". The idea process will inherit any environment variables of Bash that have been exported. (Since you did export JAVA_HOME=…, it works!), or, the sophisticated way:
  • Set global environment variables that apply to all programs, not only Bash sessions. This is more complicated than you might think, and is explained here and here, for example. What you should do is run

    /bin/launchctl setenv JAVA_HOME $(/usr/libexec/java_home)
    

    However, this gets reset after a reboot. To make sure this gets run on every boot, execute

    cat << EOF > ~/Library/LaunchAgents/setenv.JAVA_HOME.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>setenv.JAVA_HOME</string>
        <key>ProgramArguments</key>
        <array>
          <string>/bin/launchctl</string>
          <string>setenv</string>
          <string>JAVA_HOME</string>
          <string>$(/usr/libexec/java_home)</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
      </dict>
    </plist>
    EOF
    

    Note that this also affects the Terminal process, so there is no need to put anything in your ~/.bash_profile.

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

How to find files modified in last x minutes (find -mmin does not work as expected)

I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60 returns nothing. The command find . -mmin -60 |xargs ls -l, however, returns every file in the directory which is consistent with what happens when ls -l is run without an argument.

To make sure that ls -l is only run when a file is found, try:

find . -mmin -60 -type f -exec ls -l {} +

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

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.Text = sum.ToString();

Maximum number of threads per process in Linux?

To retrieve it:

cat /proc/sys/kernel/threads-max

To set it:

echo 123456789 | sudo tee -a /proc/sys/kernel/threads-max

123456789 = # of threads

add commas to a number in jQuery

Using toLocaleString ref at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

_x000D_
_x000D_
function formatComma(value, sep = 0) {_x000D_
      return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });_x000D_
    }_x000D_
console.log(formatComma(123456789, 2)); // ?123,456,789.00_x000D_
console.log(formatComma(123456789, 0)); // ?123,456,789_x000D_
console.log(formatComma(1234, 0)); // ?1,234
_x000D_
_x000D_
_x000D_

How to find the array index with a value?

Use indexOf

imageList.indexOf(200)

Keep CMD open after BAT file executes

If you are starting the script within the command line, then add exit /b to keep CMD opened

C# Listbox Item Double Click Event

WinForms

Add an event handler for the Control.DoubleClick event for your ListBox, and in that event handler open up a MessageBox displaying the selected item.

E.g.:

 private void ListBox1_DoubleClick(object sender, EventArgs e)
 {
     if (ListBox1.SelectedItem != null)
     {
         MessageBox.Show(ListBox1.SelectedItem.ToString());
     }
 }

Where ListBox1 is the name of your ListBox.

Note that you would assign the event handler like this:

ListBox1.DoubleClick += new EventHandler(ListBox1_DoubleClick);

WPF
Pretty much the same as above, but you'd use the MouseDoubleClick event instead:

ListBox1.MouseDoubleClick += new RoutedEventHandler(ListBox1_MouseDoubleClick);

And the event handler:

 private void ListBox1_MouseDoubleClick(object sender, RoutedEventArgs e)
 {
     if (ListBox1.SelectedItem != null)
     {
         MessageBox.Show(ListBox1.SelectedItem.ToString());
     }
 }

Edit: Sisya's answer checks to see if the double-click occurred over an item, which would need to be incorporated into this code to fix the issue mentioned in the comments (MessageBox shown if ListBox is double-clicked while an item is selected, but not clicked over an item).

Hope this helps!

UITableView Cell selected Color?

Swift 4.x

To Change the selection background Colour to anyColour use Swift Extension

Create UITableView Cell extension as below

extension UITableViewCell{

    func removeCellSelectionColour(){
        let clearView = UIView()
        clearView.backgroundColor = UIColor.clear
        UITableViewCell.appearance().selectedBackgroundView = clearView
    } 

}

Then call removeCellSelectionColour() with cell instance.

Twitter Bootstrap Modal Form Submit

Updated 2018

Do you want to close the modal after submit? Whether the form in inside the modal or external to it you should be able to use jQuery ajax to submit the form.

Here is an example with the form inside the modal:

<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <form id="myForm" method="post">
          <input type="hidden" value="hello" id="myField">
            <button id="myFormSubmit" type="submit">Submit</button>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

And the jQuery ajax to get the form fields and submit it..

$('#myFormSubmit').click(function(e){
      e.preventDefault();
      alert($('#myField').val());
      /*
      $.post('http://path/to/post', 
         $('#myForm').serialize(), 
         function(data, status, xhr){
           // do something here with response;
         });
      */
});

Bootstrap 3 example


Bootstrap 4 example

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

pypsrp - Python PowerShell Remoting Protocol Client library

At a basic level, you can use this library to;

Execute a cmd command
Run another executable
Execute PowerShell scripts
Copy a file from the localhost to the remote Windows host
Fetch a file from the remote Windows host to the localhost
Create a Runspace Pool that contains one or multiple PowerShell pipelines and execute them asynchronously
Support for a reference host base implementation of PSRP for interactive scripts

REF: https://github.com/jborean93/pypsrp

How to delete a row from GridView?

Please try this code.....

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
   GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();

C# Public Enums in Classes

Currently, your enum is nested inside of your Card class. All you have to do is move the definition of the enum out of the class:

// A better name which follows conventions instead of card_suits is
public enum CardSuit
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
}

To Specify:

The name change from card_suits to CardSuit was suggested because Microsoft guidelines suggest Pascal Case for Enumerations and the singular form is more descriptive in this case (as a plural would suggest that you're storing multiple enumeration values by ORing them together).

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

This error occurs when there are some non ASCII characters in our string and we are performing any operations on that string without proper decoding. This helped me solve my problem. I am reading a CSV file with columns ID,Text and decoding characters in it as below:

train_df = pd.read_csv("Example.csv")
train_data = train_df.values
for i in train_data:
    print("ID :" + i[0])
    text = i[1].decode("utf-8",errors="ignore").strip().lower()
    print("Text: " + text)

WAMP/XAMPP is responding very slow over localhost

I'm not yet able to comment under @Honesta answer, so I'll write here the way I manage to solve it.

My environment (I don't know if this is relevant for the answer)

  • XAMPP (version 5.6.3)
  • Windows 8.1 Pro (64 bit)

How to

I just opened my.ini file and uncommented the line where it says

bind-address="127.0.0.1"

This file is located, for XAMPP users, in C:\xampp\mysql\bin\my.ini.

Credits

This article helped me to solve the problem, although I didn't needed everything in it because some setup in XAMPP were not requested.

How to call Android contacts list?

public void onActivityResult(int requestCode, int resultCode, Intent intent) 
{
  if (requestCode == PICK_CONTACT && intent != null) //here check whether intent is null R not
  {  
  }
}

because without selecting any contact it will give an exception. so better to check this condition.

Accessing the web page's HTTP Headers in JavaScript

You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like "http referer javascript".

I know this should be obvious, but I kept searching for stuff like "http headers javascript" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

How can I select all elements without a given class in jQuery?

You could use this to pick all li elements without class:

$('ul#list li:not([class])')

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

INNER JOIN ON vs WHERE clause

They have a different human-readable meaning.

However, depending on the query optimizer, they may have the same meaning to the machine.

You should always code to be readable.

That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.

Session state can only be used when enableSessionState is set to true either in a configuration

Session State may be broken if you have the following in Web.Config:

<httpModules>
  <clear/>
</httpModules>

If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.

Django Cookies, how can I set them?

You could manually set the cookie, but depending on your use case (and if you might want to add more types of persistent/session data in future) it might make more sense to use Django's sessions feature. This will let you get and set variables tied internally to the user's session cookie. Cool thing about this is that if you want to store a lot of data tied to a user's session, storing it all in cookies will add a lot of weight to HTTP requests and responses. With sessions the session cookie is all that is sent back and forth (though there is the overhead on Django's end of storing the session data to keep in mind).

are there dictionaries in javascript like python?

There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:

let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');

Without support for ES6 you can try using objects:

var x = new Object();
x["Key"] = "Value";

However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Changing password with Oracle SQL Developer

I realise that there are many answers, but I found a solution that may be helpful to some. I ran into the same problem, I am running oracle sql develop on my local computer and I have a bunch of users. I happen to remember the password for one of my users and I used it to reset the password of other users.

Steps:

  1. connect to a database using a valid user and password, in my case all my users expired except "system" and I remember that password

  2. find the "Other_users" node within the tree as the image below displays

enter image description here

3.within the "Other_users" tree find your users that you would like to reset password of and right click the note and select "Edit Users"

enter image description here

4.fill out the new password in edit user dialog and click "Apply". Make sure that you have unchecked "Password expired (user must change next login)".

enter image description here

And that worked for me, It is not as good as other solution because you need to be able to login to at least one account but it does work.

C# : Passing a Generic Object

You cannot access var with the generic.

Try something like

Console.WriteLine("Generic : {0}", test);

And override ToString method [1]

[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

How to add items into a numpy array

Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

That said, It's often unavoidable and the functions that do this are:

for 2-D arrays:

for 3-D arrays (the above plus):

for N-D arrays:

Reading DataSet

TL;DR: - grab the datatable from the dataset and read from the rows property.

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn("Id", typeof(int));
            dt.Columns.Add(col);
            dt.Rows.Add(new object[] { 1 });
            ds.Tables.Add(dt);

            var row = ds.Tables[0].Rows[0];
            //access the ID column.  
            var id = (int) row.ItemArray[0];

A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.

Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.

If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.

If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.

You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.

After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.

When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:

MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset 
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
   trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
    //do some other work

The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!

How can I get the console logs from the iOS Simulator?

There's an option in the Simulator to open the console

Debug > Open System Log

or use the

keyboard shortcut: ?/

Simulator menu screenshot

How do I print a list of "Build Settings" in Xcode project?

Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.

As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:

Target's Build Phases section w/ added Log Build Settings script phase

To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash and the command to export.  You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources.  Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.

The result is this incredibly helpful listing of current environment variables used for building:

Build Log output w/ export command's results

Django. Override save for model

Query the database for an existing record with the same PK. Compare the file sizes and checksums of the new and existing images to see if they're the same.

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

Regular expression search replace in Sublime Text 2

Important: Use the ( ) parentheses in your search string

While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( ) parentheses, otherwise these matched segments won't be accessible to defined variables such as $1, $2 or \1, \2 etc.

For example we want to replace 'em' with 'px' but preserve the digit values:

    margin: 10em;  /* Expected: margin: 10px */
    margin: 2em;   /* Expected: margin: 2px */
  • Replacement string: margin: $1px or margin: \1px
  • Search string (CORRECT): margin: ([0-9]*)em // with parentheses
  • Search string (INCORRECT): margin: [0-9]*em

CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em search string (with parentheses). Enclose the desired matched segment (e.g. $1 or \1) by ( ) parentheses as following:

  • Find: margin: ([0-9]*)em (with parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: 10px;
    margin: 2px;

INCORRECT CASE EXAMPLE: Using margin: [0-9]*em search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1 or \1:

  • Find: margin: [0-9]*em (without parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: px; /* `$1` is undefined */
    margin: px; /* `$1` is undefined */

How to get File Created Date and Modified Date

File.GetLastWriteTime Method

Returns the date and time the specified file or directory was last written to.

string path = @"c:\Temp\MyTest.txt";
DateTime dt = File.GetLastWriteTime(path);

For create time File.GetCreationTime Method

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Console.WriteLine("file created: " + fileCreatedDate);

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

Run a shell script with an html button

PHP is likely the easiest.

Just make a file script.php that contains <?php shell_exec("yourscript.sh"); ?> and send anybody who clicks the button to that destination. You can return the user to the original page with header:

<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>

Reference: http://php.net/manual/en/function.shell-exec.php

how to count the spaces in a java string?

Here's a different way of looking at it, and it's a simple one-liner:

int spaces = s.replaceAll("[^ ]", "").length();

This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).

You might want to add a null check:

int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();

Java 8 update

You can use a stream too:

int spaces = s.chars().filter(c -> c == (int)' ').count();

Regex in JavaScript for validating decimal numbers

The schema for passing the value in as a string. The regex will validate a string of at least one digit, possibly followed by a period and exactly two digits:

{
    "type": "string",
    "pattern": "^[0-9]+(\\.[0-9]{2})?$"
}

The schema below is equivalent, except that it also allows empty strings:

{
    "type": "string",
    "pattern": "^$|^[0-9]+(\\.[0-9]{2})?$"
}

Android Debug Bridge (adb) device - no permissions

  1. Close running adb, could be closing running android-studio.

  2. list devices,

/usr/local/android-studio/sdk/platform-tools/adb devices

How do I run a terminal inside of Vim?

I know that I'm not directly answering the question, but I think it's a good approach. Nobody has mentioned tmux (or at least not as a standalone answer). Tmux is a terminal multiplexor like screen. Most stuff can be made in both multiplexors, but afaik tmux it's more easily to configure. Also tmux right now is being more actively developed than screen and there's quite a big ecosystem around it, like tools that help the configuration, ecc.

Also for vim, there's another plugin: ViMUX, that helps a lot in the interaction between both tools. You can call commands with:

:call VimuxRunCommand("ls")

That command creates a small horizontal split below the current pane vim is in.

It can also let you run from a prompt in case you don't want to run the whole command:

<Leader>vp :VimuxPromptCommand<CR>

As it weren't enought, there are at least 6 'platform specific plugins':

Here is a nice "use case": Tests on demand using Vimux and Turbux with Spork and Guard

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

Getting the parent div of element

Knowing the parent of an element is useful when you are trying to position them out the "real-flow" of elements.

Below given code will output the id of parent of element whose id is provided. Can be used for misalignment diagnosis.

<!-- Patch of code to find parent -->
<p id="demo">Click the button </p>
<button onclick="parentFinder()">Find Parent</button>
<script>
function parentFinder()
{
    var x=document.getElementById("demo"); 
    var y=document.getElementById("*id of Element you want to know parent of*");
    x.innerHTML=y.parentNode.id;
}
</script>
<!-- Patch ends -->

Why is it OK to return a 'vector' from a function?

This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.

The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.

On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.

So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.

How to implement an STL-style iterator and avoid common pitfalls?

http://www.cplusplus.com/reference/std/iterator/ has a handy chart that details the specs of § 24.2.2 of the C++11 standard. Basically, the iterators have tags that describe the valid operations, and the tags have a hierarchy. Below is purely symbolic, these classes don't actually exist as such.

iterator {
    iterator(const iterator&);
    ~iterator();
    iterator& operator=(const iterator&);
    iterator& operator++(); //prefix increment
    reference operator*() const;
    friend void swap(iterator& lhs, iterator& rhs); //C++11 I think
};

input_iterator : public virtual iterator {
    iterator operator++(int); //postfix increment
    value_type operator*() const;
    pointer operator->() const;
    friend bool operator==(const iterator&, const iterator&);
    friend bool operator!=(const iterator&, const iterator&); 
};
//once an input iterator has been dereferenced, it is 
//undefined to dereference one before that.

output_iterator : public virtual iterator {
    reference operator*() const;
    iterator operator++(int); //postfix increment
};
//dereferences may only be on the left side of an assignment
//once an output iterator has been dereferenced, it is 
//undefined to dereference one before that.

forward_iterator : input_iterator, output_iterator {
    forward_iterator();
};
//multiple passes allowed

bidirectional_iterator : forward_iterator {
    iterator& operator--(); //prefix decrement
    iterator operator--(int); //postfix decrement
};

random_access_iterator : bidirectional_iterator {
    friend bool operator<(const iterator&, const iterator&);
    friend bool operator>(const iterator&, const iterator&);
    friend bool operator<=(const iterator&, const iterator&);
    friend bool operator>=(const iterator&, const iterator&);

    iterator& operator+=(size_type);
    friend iterator operator+(const iterator&, size_type);
    friend iterator operator+(size_type, const iterator&);
    iterator& operator-=(size_type);  
    friend iterator operator-(const iterator&, size_type);
    friend difference_type operator-(iterator, iterator);

    reference operator[](size_type) const;
};

contiguous_iterator : random_access_iterator { //C++17
}; //elements are stored contiguously in memory.

You can either specialize std::iterator_traits<youriterator>, or put the same typedefs in the iterator itself, or inherit from std::iterator (which has these typedefs). I prefer the second option, to avoid changing things in the std namespace, and for readability, but most people inherit from std::iterator.

struct std::iterator_traits<youriterator> {        
    typedef ???? difference_type; //almost always ptrdiff_t
    typedef ???? value_type; //almost always T
    typedef ???? reference; //almost always T& or const T&
    typedef ???? pointer; //almost always T* or const T*
    typedef ???? iterator_category;  //usually std::forward_iterator_tag or similar
};

Note the iterator_category should be one of std::input_iterator_tag, std::output_iterator_tag, std::forward_iterator_tag, std::bidirectional_iterator_tag, or std::random_access_iterator_tag, depending on which requirements your iterator satisfies. Depending on your iterator, you may choose to specialize std::next, std::prev, std::advance, and std::distance as well, but this is rarely needed. In extremely rare cases you may wish to specialize std::begin and std::end.

Your container should probably also have a const_iterator, which is a (possibly mutable) iterator to constant data that is similar to your iterator except it should be implicitly constructable from a iterator and users should be unable to modify the data. It is common for its internal pointer to be a pointer to non-constant data, and have iterator inherit from const_iterator so as to minimize code duplication.

My post at Writing your own STL Container has a more complete container/iterator prototype.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I will throw one more solution into the mix. I downloaded a sample app and it was crimping only on this taglib. Turns out it didn't care for the single quotes around the attributes.

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>

Once I changed those and made sure jstl.jar was in the web app, i was good to go.

Is it possible to opt-out of dark mode on iOS 13?

Xcode 12 and iOS 14 update. I have try the previous options to opt-out dark mode and this sentence in the info.plist file is not working for me:

<key>UIUserInterfaceStyle</key>
<string>Light</string>

Now it is renamed to:

<key>Appearance</key>
<string>Light</string>

This setting will block all dark mode in the full app.

EDITED:

Fixed typo thank you to @sarah

Get list of all tables in Oracle?

To get all the table names, we can use:

Select  owner, table_name  from all_tables;

if you have dba permission, you can use:

Select owner, table_name from dba_tables;

How to play a sound using Swift?

import AVFoundation
var player:AVAudioPlayer!

func Play(){
    guard let path = Bundle.main.path(forResource: "KurdishSong", ofType: "mp3")else{return}
    let soundURl = URL(fileURLWithPath: path)
    player = try? AVAudioPlayer(contentsOf: soundURl)
    player.prepareToPlay()
    player.play()
    //player.pause()
    //player.stop()
}

Location of my.cnf file on macOS

macOS High Sierra version 10.13.6

mysql Ver 14.14 Distrib 5.7.22, for osx10.13 (x86_64) using EditLine wrapper Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved

Default options are read from the following files in the given order:

/etc/my.cnf 
/etc/mysql/my.cnf 
/usr/local/etc/my.cnf 
~/.my.cnf

I want to multiply two columns in a pandas DataFrame and add the result into a new column

I think an elegant solution is to use the where method (also see the API docs):

In [37]: values = df.Prices * df.Amount

In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)

In [39]: df
Out[39]: 
   Prices  Amount Action  Values
0       3      57   Sell     171
1      89      42   Sell    3738
2      45      70    Buy   -3150
3       6      43   Sell     258
4      60      47   Sell    2820
5      19      16    Buy    -304
6      56      89   Sell    4984
7       3      28    Buy     -84
8      56      69   Sell    3864
9      90      49    Buy   -4410

Further more this should be the fastest solution.

SOAP Action WSDL

When soapAction is missing in the SOAP 1.2 request (and many clients do not set it, even when it is specified in WSDL), some app servers (eg. jboss) infer the "actual" soapAction from {xsd:import namespace}+{wsdl:operation name}. So, to make the inferred "actual" soapAction match the expected soapAction, you can set the expected soapAction to {xsd:import namespace}+{wsdl:operation name} in your WS definition (@WebMethod(action=...) for Java EE)

Eg. for a typical Java EE case, this helps (not the Stewart's case, National Rail WS has 'soapAction' set):

@WebMethod(action = "http://packagename.of.your.webservice.class.com/methodName")

If you cannot change the server, you will have to force client to fill soapAction.

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

where does MySQL store database files?

WAMP stores the db data under WAMP\bin\mysql\mysql(version)\data. Where the WAMP folder itself is depends on where you installed it to (on xp, I believe it is directly in the main drive, for example c:\WAMP\...

If you deleted that folder, or if the uninstall deleted that folder, if you did not do a DB backup before the uninstall, you may be out of luck.

If you did do a backup though phpmyadmin, then login, and click the import tab, and browse to the backup file.

python: SyntaxError: EOL while scanning string literal

Most previous answers are correct and my answer is very similar to aaronasterling, you could also do 3 single quotations s1='''some very long string............'''

Comparing strings in Java

Try to use .trim() first, before .equals(), or create a new String var that has these things.

position fixed header in html

set #container div top to zero

#container{ 


 top: 0;



}

Display more Text in fullcalendar

This code can help you :

$(document).ready(function() { 
    $('#calendar').fullCalendar({ 
        events: 
            [ 
                { 
                    id: 1, 
                    title: 'First Event', 
                    start: ..., 
                    end: ..., 
                    description: 'first description' 
                }, 
                { 
                    id: 2, 
                    title: 'Second Event', 
                    start: ..., 
                    end: ..., 
                    description: 'second description'
                }
            ], 
        eventRender: function(event, element) { 
            element.find('.fc-title').append("<br/>" + event.description); 
        } 
    });
}   

How to config Tomcat to serve images from an external folder outside webapps?

You could have a redirect servlet. In you web.xml you'd have:

<servlet>
    <servlet-name>images</servlet-name>
    <servlet-class>com.example.images.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>images</servlet-name>
    <url-pattern>/images/*</url-pattern>
</servlet-mapping>

All your images would be in "/images", which would be intercepted by the servlet. It would then read in the relevant file in whatever folder and serve it right back out. For example, say you have a gif in your images folder, c:\Server_Images\smilie.gif. In the web page would be <img src="http:/example.com/app/images/smilie.gif".... In the servlet, HttpServletRequest.getPathInfo() would yield "/smilie.gif". Which the servlet would find in the folder.

Append String in Swift

let string2 = " there"
var instruction = "look over"

choice 1 :

 instruction += string2;

  println(instruction)

choice 2:

 var Str = instruction + string2;

 println(Str)

ref this

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

Unrecognized SSL message, plaintext connection? Exception

If you're running the Java process from the command line on Java 6 or earlier, adding this switch solved the issue above for me:

-Dhttps.protocols="TLSv1"

Spring Boot access static resources missing scr/main/resources

To get the files in the classpath :

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();

To read the file onStartup use @PostConstruct:

@Configuration
public class ReadFileOnStartUp {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {

        //Gets the XML file under src/main/resources folder
        Resource resource = new ClassPathResource("countries.xml");
        File file = resource.getFile();
        //Logic to read File.
    }
}

Here is a Small example for reading an XML File on Spring Boot App startup.

TextFX menu is missing in Notepad++

For Notepad++ 64-bit:

There is an unreleased 64-bit version of this plugin. You can download the DLL from here, drop it under Notepad++/plugins/NppTextFX directory and restart Notepad++. You will need to create the NppTextFX directory first though.

As per this GitHub issue, there might be some bugs lurking around. If you run into any, feel free to raise a GitHub ticket for each, as the author (HQJaTu) is recommending. As per the author, the code behind this binary is found on this branch.

enter image description here

Tested on Notepad++ v7.5.8 (64-bit, Build time: Jul 23 2018)

How to get the innerHTML of selectable jquery element?

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').html(); 
                console.log($variable);
            }
        });
    });

or

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').text(); 
                console.log($variable);
            }
        });
    });

or

$(function() {
        $("#select-image").selectable({
            selected: function( event, ui ) { 
                var $variable = $('.ui-selected').val(); 
                console.log($variable);
            }
        });
    });

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

If JDK installed but still not working.

In Eclipse follow below steps:- Window --> Preference --> Installed JREs -->Change path of JRE to JDK(add).

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

How to change credentials for SVN repository in Eclipse?

There are several places on Windows where SVN will place cached credentials depending on system configuration. Read SVNBook | Client Credentials.

  • The main credential store is located in %APPDATA%\Subversion\auth and you can run svn auth command to view and manage its contents.

  • You can also run cmdkey to view the credentials stored in Windows Credential Manager.

  • If your SVN server is integrated with Active Directory and supports Integrated Windows Authentication such as VisualSVN Server, your Windows logon credentials are used for authentication, but they are not cached. You can run whoami to find out your user account name.

Is it possible to use pip to install a package from a private GitHub repository?

The syntax for the requirements file is given here:

https://pip.pypa.io/en/latest/reference/pip_install.html#requirements-file-format

So for example, use:

-e git+http://github.com/rwillmer/django-behave#egg=django-behave

if you want the source to stick around after installation.

Or just

git+http://github.com/rwillmer/django-behave#egg=django-behave

if you just want it to be installed.

difference between new String[]{} and new String[] in java

{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings

String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};

while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings

String[] array = new String[10];

...But...

String array = new String[10]{};  //The line you mentioned above

Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.

Additionally

The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.

Convert base64 string to ArrayBuffer

Javascript is a fine development environment so it seems odd than it doesn't provide a solution to this small problem. The solutions offered elsewhere on this page are potentially slow. Here is my solution. It employs the inbuilt functionality that decodes base64 image and sound data urls.

var req = new XMLHttpRequest;
req.open('GET', "data:application/octet;base64," + base64Data);
req.responseType = 'arraybuffer';
req.onload = function fileLoaded(e)
{
   var byteArray = new Uint8Array(e.target.response);
   // var shortArray = new Int16Array(e.target.response);
   // var unsignedShortArray = new Int16Array(e.target.response);
   // etc.
}
req.send();

The send request fails if the base 64 string is badly formed.

The mime type (application/octet) is probably unnecessary.

Tested in chrome. Should work in other browsers.

Modifying location.hash without page scrolling

if you use hashchange event with hash parser, you can prevent default action on links and change location.hash adding one character to have difference with id property of an element

$('a[href^=#]').on('click', function(e){
    e.preventDefault();
    location.hash = $(this).attr('href')+'/';
});

$(window).on('hashchange', function(){
    var a = /^#?chapter(\d+)-section(\d+)\/?$/i.exec(location.hash);
});

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

How to change the default message of the required field in the popover of form-control in bootstrap?

You can use setCustomValidity function when oninvalid event occurs.

Like below:-

<input class="form-control" type="email" required="" 
    placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>

Update:-

To clear the message once you start entering use oninput="setCustomValidity('') attribute to clear the message.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

How to jquery alert confirm box "yes" & "no"

I won't write your code but what you looking for is something like a jquery dialog

take a look here

jQuery modal-confirmation

$(function() {
    $( "#dialog-confirm" ).dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $( this ).dialog( "close" );
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });
  });

<div id="dialog-confirm" title="Empty the recycle bin?">
  <p>
    <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
    These items will be permanently deleted and cannot be recovered. Are you sure?
  </p>
</div>

Import module from subfolder

Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).

Also you can manually add your current directory (src in your case) to pythonpath:

import os
import sys
sys.path.insert(0, os.getcwd())

C string append

You could use asprintf to concatenate both into a new string:

char *new_str;
asprintf(&new_str,"%s%s",str1,str2);

Use grep to report back only line numbers

All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:

sed -n '/pattern/=' filename

Confirm deletion using Bootstrap 3 modal box

enter image description here Following solution is better than bootbox.js, because

  • It can do everything bootbox.js can do;
  • The use syntax is simpler
  • It allows you to elegantly control the color of your message using "error", "warning" or "info"
  • Bootbox is 986 lines long, mine only 110 lines long

digimango.messagebox.js:

_x000D_
_x000D_
const dialogTemplate = '\_x000D_
    <div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
        <div class ="modal-dialog">\_x000D_
            <div class ="modal-content">\_x000D_
                <div class ="modal-body">\_x000D_
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
                </div>\_x000D_
                <div class ="modal-footer">\_x000D_
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
                </div>\_x000D_
            </div>\_x000D_
        </div>\_x000D_
    </div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
    if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
        var iDiv = document.createElement('div');_x000D_
        iDiv.id = 'digimango_MessageBoxContainer';_x000D_
        document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
        $("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
    }_x000D_
_x000D_
    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
    if (options == null) {_x000D_
        okButtonName = 'OK';_x000D_
        cancelButtonName = null;_x000D_
        showTextBox = null;_x000D_
        textBoxDefaultText = null;_x000D_
    } else {_x000D_
        okButtonName = options.okButtonName;_x000D_
        cancelButtonName = options.cancelButtonName;_x000D_
        showTextBox = options.showTextBox;_x000D_
        textBoxDefaultText = options.textBoxDefaultText;_x000D_
    }_x000D_
_x000D_
    if (showTextBox == true) {_x000D_
        if (textBoxDefaultText == null)_x000D_
            $('#digimango_messageBoxTextArea').val('');_x000D_
        else_x000D_
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
        $('#digimango_messageBoxTextArea').show();_x000D_
    }_x000D_
    else_x000D_
        $('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
    if (okButtonName != null)_x000D_
        $('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
    else_x000D_
        $('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
    if (cancelButtonName == null)_x000D_
        $('#digimango_messageBoxCancelButton').hide();_x000D_
    else {_x000D_
        $('#digimango_messageBoxCancelButton').show();_x000D_
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
    }_x000D_
_x000D_
    $('#digimango_messageBoxOkButton').unbind('click');_x000D_
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
    $('#digimango_messageBoxCancelButton').unbind('click');_x000D_
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
    var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
    if (significance == 'error')_x000D_
        content.attr('class', 'text-danger');_x000D_
    else if (significance == 'warning')_x000D_
        content.attr('class', 'text-warning');_x000D_
    else_x000D_
        content.attr('class', 'text-success');_x000D_
_x000D_
    content.html(msg);_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $("#digimango_messageBox").modal();_x000D_
_x000D_
    digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
    // JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
    // thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
    // not execute the last line in this function._x000D_
    if (typeof (event.data.callback) != 'undefined')_x000D_
        event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
_x000D_
_x000D_

To use digimango.messagebox.js:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title>A useful generic message box</title>_x000D_
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    <script type="text/javascript">_x000D_
        function testAlert() {_x000D_
            messageBox('Something went wrong!', 'error');_x000D_
        }_x000D_
_x000D_
        function testAlertWithCallback() {_x000D_
            messageBox('Something went wrong!', 'error', null, function () {_x000D_
                messageBox('OK clicked.');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testConfirm() {_x000D_
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPrompt() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPromptWithDefault() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
    </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
    <a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the best way to repeatedly execute a function every x seconds?

You might want to consider Twisted which is a Python networking library that implements the Reactor Pattern.

from twisted.internet import task, reactor

timeout = 60.0 # Sixty seconds

def doWork():
    #do work here
    pass

l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds

reactor.run()

While "while True: sleep(60)" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution

Read file As String

this is working for me

i use this path

String FILENAME_PATH =  "/mnt/sdcard/Download/Version";

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();        
    return ret;

}

An invalid form control with name='' is not focusable

There are things that still surprises me... I have a form with dynamic behaviour for two different entities. One entity requires some fields that the other don't. So, my JS code, depending on the entity, does something like: $('#periodo').removeAttr('required'); $("#periodo-container").hide();

and when the user selects the other entity: $("#periodo-container").show(); $('#periodo').prop('required', true);

But sometimes, when the form is submitted, the issue apppears: "An invalid form control with name=periodo'' is not focusable (i am using the same value for the id and name).

To fix this problem, you have to ensurance that the input where you are setting or removing 'required' is always visible.

So, what I did is:

$("#periodo-container").show(); //for making sure it is visible
$('#periodo').removeAttr('required'); 
$("#periodo-container").hide(); //then hide

Thats solved my problem... unbelievable.

Disabled href tag

You need to remove the <a> tag to get rid of this.

or try using :-

  <a href="/" onclick="return false;">123n</a>

recyclerview No adapter attached; skipping layout

In my case, I was setting the adapter inside onLocationChanged() callback AND debugging in the emulator. Since it didn't detected a location change it never fired. When I set them manually in the Extended controls of the emulator it worked as expected.

Adding a new value to an existing ENUM Type

A possible solution is the following; precondition is, that there are not conflicts in the used enum values. (e.g. when removing an enum value, be sure that this value is not used anymore.)

-- rename the old enum
alter type my_enum rename to my_enum__;
-- create the new enum
create type my_enum as enum ('value1', 'value2', 'value3');

-- alter all you enum columns
alter table my_table
  alter column my_column type my_enum using my_column::text::my_enum;

-- drop the old enum
drop type my_enum__;

Also in this way the column order will not be changed.

How to define a relative path in java

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);

Dockerfile if else condition with external arguments

Exactly as others told, shell script would help.

Just an additional case, IMHO it's worth mentioning (for someone else who stumble upon here, looking for an easier case), that is Environment replacement.

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

The ${variable_name} syntax also supports a few of the standard bash modifiers as specified below:

  • ${variable:-word} indicates that if variable is set then the result will be that value. If variable is not set then word will be the result.

  • ${variable:+word} indicates that if variable is set then word will be the result, otherwise the result is the empty string.

How to "test" NoneType in python?

I hope this example will be helpful for you)

print(type(None))  # NoneType

So, you can check type of the variable name

# Example
name = 12  # name = None

if type(name) is type(None):
    print("Can't find name")
else:
    print(name)

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

Accessing certain pixel RGB value in openCV

const double pi = boost::math::constants::pi<double>();

cv::Mat distance2ellipse(cv::Mat image, cv::RotatedRect ellipse){
    float distance = 2.0f;
    float angle = ellipse.angle;
    cv::Point ellipse_center = ellipse.center;
    float major_axis = ellipse.size.width/2;
    float minor_axis = ellipse.size.height/2;
    cv::Point pixel;
    float a,b,c,d;

    for(int x = 0; x < image.cols; x++)
    {
        for(int y = 0; y < image.rows; y++) 
        {
        auto u =  cos(angle*pi/180)*(x-ellipse_center.x) + sin(angle*pi/180)*(y-ellipse_center.y);
        auto v = -sin(angle*pi/180)*(x-ellipse_center.x) + cos(angle*pi/180)*(y-ellipse_center.y);

        distance = (u/major_axis)*(u/major_axis) + (v/minor_axis)*(v/minor_axis);  

        if(distance<=1)
        {
            image.at<cv::Vec3b>(y,x)[1] = 255;
        }
      }
  }
  return image;  
}

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

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

For me the problem was copying .resx files and associated .cs files from one project to another. Both projects had the same namespace so that wasn't the problem.

Finally solved it when I noticed in Solution Explorer that in the original project the .resx files were dependent on the .cs files:

MyResource.cs
|_ MyResource.resx

While in the copied project the .cs files was dependent on the .resx files:

MyResource.resx
|_ MyResource.cs

It turned out that in the second project somehow the .resx files had been set to auto-generate the .cs files. The auto-generated .cs files were overwriting the .cs files copied from the original project.

To fix the problem edit the properties of each .resx file in the copied project. The Custom Tool property will be set to something like ResXFileCodeGenerator. Clear the Custom Tool property of the .resx file. You will need to re-copy the .cs file from the original project as it will have been overwritten by the auto-generated file.

Error during SSL Handshake with remote server

The comment by MK pointed me in the right direction.

In the case of Apache 2.4 and up, there are different defaults and a new directive.

I am running Apache 2.4.6, and I had to add the following directives to get it working:

SSLProxyEngine on
SSLProxyVerify none 
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off

How can I simulate mobile devices and debug in Firefox Browser?

You can use the already mentioned built in Responsive Design Mode (via dev tools) for setting customised screen sizes together with the Random Agent Spoofer Plugin to modify your headers to simulate you are using Mobile, Tablet etc. Many websites specify their content according to these identified headers.

As dev tools you can use the built in Developer Tools (Ctrl + Shift + I or Cmd + Shift + I for Mac) which have become quite similar to Chrome dev tools by now.

MVC 4 client side validation not working

My problem was in web.config: UnobtrusiveJavaScriptEnabled was turned off

<appSettings>

<add key="ClientValidationEnabled" value="true" />

<add key="UnobtrusiveJavaScriptEnabled" value="false" />

</appSettings>

I changed to and now works:

`<add key="UnobtrusiveJavaScriptEnabled" value="true" />`

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

How to update a value, given a key in a hashmap?

hashmap.put(key, hashmap.get(key) + 1);

The method put will replace the value of an existing key and will create it if doesn't exist.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

How to get a Docker container's IP address from the host

Execute:

docker ps -a

This will display active docker images:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS               NAMES
3b733ae18c1c        parzee/database     "/usr/lib/postgresql/"   6 minutes ago       Up 6 minutes                 5432/tcp            serene_babbage

Use the CONTAINER ID value:

docker inspect <CONTAINER ID> | grep -w "IPAddress" | awk '{ print $2 }' | head -n 1 | cut -d "," -f1

"172.17.0.2"

Warn user before leaving web page with unsaved changes

via jquery

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

How to remove all numbers from string?

Use some regex like [0-9] or \d:

$words = preg_replace('/\d+/', '', $words );

You might want to read the preg_replace() documentation as this is directly shown there.

How do I filter date range in DataTables?

Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)

http://www.daterangepicker.com/#ex1

Multiple WHERE Clauses with LINQ extension methods

results = context.Orders.Where(o => o.OrderDate <= today && today <= o.OrderDate)

The select is uneeded as you are already working with an order.

Retrieve list of tasks in a queue in Celery

To retrieve tasks from backend, use this

from amqplib import client_0_8 as amqp
conn = amqp.Connection(host="localhost:5672 ", userid="guest",
                       password="guest", virtual_host="/", insist=False)
chan = conn.channel()
name, jobs, consumers = chan.queue_declare(queue="queue_name", passive=True)

How to delete file from public folder in laravel 5.1

Two ways to delete the image from public folder without changing laravel filesystems config file or messing with pure php unlink function:

  1. Using the default local storage you need to specify public subfolder:
Storage::delete('public/'.$image_path);
  1. Use public storage directly:
Storage::disk('public')->delete($image_path);

I would suggest second way as the best one.

Hope this help other people.

Assembly - JG/JNLE/JL/JNGE after CMP

The command JG simply means: Jump if Greater. The result of the preceding instructions is stored in certain processor flags (in this it would test if ZF=0 and SF=OF) and jump instruction act according to their state.

How to sort a list of lists by a specific index of the inner list?

Itemgetter lets you to sort by multiple criteria / columns:

sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

How to read first N lines of a file?

The two most intuitive ways of doing this would be:

  1. Iterate on the file line-by-line, and break after N lines.

  2. Iterate on the file line-by-line using the next() method N times. (This is essentially just a different syntax for what the top answer does.)

Here is the code:

# Method 1:
with open("fileName", "r") as f:
    counter = 0
    for line in f:
        print line
        counter += 1
        if counter == N: break

# Method 2:
with open("fileName", "r") as f:
    for i in xrange(N):
        line = f.next()
        print line

The bottom line is, as long as you don't use readlines() or enumerateing the whole file into memory, you have plenty of options.

Difference between hamiltonian path and euler path

An Euler path is a path that uses every edge of a graph exactly once.and it must have exactly two odd vertices.the path starts and ends at different vertex. A Hamiltonian cycle is a cycle that contains every vertex of the graph hence you may not use all the edges of the graph.

What is the difference between a static method and a non-static method?

A static method belongs to the class and a non-static method belongs to an object of a class. That is, a non-static method can only be called on an object of a class that it belongs to. A static method can however be called both on the class as well as an object of the class. A static method can access only static members. A non-static method can access both static and non-static members because at the time when the static method is called, the class might not be instantiated (if it is called on the class itself). In the other case, a non-static method can only be called when the class has already been instantiated. A static method is shared by all instances of the class. These are some of the basic differences. I would also like to point out an often ignored difference in this context. Whenever a method is called in C++/Java/C#, an implicit argument (the 'this' reference) is passed along with/without the other parameters. In case of a static method call, the 'this' reference is not passed as static methods belong to a class and hence do not have the 'this' reference.

Reference:Static Vs Non-Static methods

Fastest way(s) to move the cursor on a terminal command line?

Incremental history searching

in terminal enter:

gedit  ~/.inputrc

then copy paste and save

"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char

all you need to do to find a previous command is to enter say the first 2 or 3 letters and upward arrow will take you there quickly say i want:

for f in *.mid ; do timidity "$f"; done

all i need to do is enter

fo

and hit upward arrow command will soon appear

EF Migrations: Rollback last applied migration?

I realised there aren't any good solutions utilizing the CLI dotnet command so here's one:

dotnet ef migrations list
dotnet ef database update NameOfYourMigration

In the place of NameOfYourMigration enter the name of the migration you want to revert to.

Exception thrown in catch and finally clause

Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:

When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.

Note that applicable catch or finally blocks includes:

When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.

Now retrace the execution remembering that, whenever you hit throw, you should abort tracing the current exception and start tracing the new exception.

Convert pandas data frame to series

You can retrieve the series through slicing your dataframe using one of these two methods:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html

import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randn(1,8))

series1=df.iloc[0,:]
type(series1)
pandas.core.series.Series

How can I use console logging in Internet Explorer?

Since version 8, Internet Explorer has its own console, like other browsers. However, if the console is not enabled, the console object does not exist and a call to console.log will throw an error.

Another option is to use log4javascript (full disclosure: written by me), which has its own logging console that works in all mainstream browsers, including IE >= 5, plus a wrapper for the browser's own console that avoids the issue of an undefined console.

H2 database error: Database may be already in use: "Locked by another process"

For InteliJ: right lick on your database in the database view and choose "Disconnect".

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

How do I get the last character of a string?

String aString = "This will return the letter t";
System.out.println(aString.charAt(aString.length() - 1));

Output should be:

t

Happy coding!

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

We had a similar situation and we tried out given at the top of the answers ini_set('memory_limit', '-1'); and everything worked fine, compressed images files greater than 1MB to KBs.

What is the difference between an Instance and an Object?

Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.

how to get all child list from Firebase android

 private FirebaseDatabase firebaseDatabase=  FirebaseDatabase.getInstance();
    private DatabaseReference databaseReference=  firebaseDatabase.getReference();
    private DatabaseReference mChildReference= databaseReference.child("data");

  mChildReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    User commandObject = ds.getValue(User.class);
                    Log.d("TAG", commandObject.getMsg());
                }
                Toast.makeText(MainActivity.this,dataSnapshot.toString(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

This will help you, you just have to create a model class containing String msg.

Room persistance library. Delete all

If want to delete an entry from the the table in Room simply call this function,

@Dao
public interface myDao{
    @Delete
    void delete(MyModel model);
}

Update: And if you want to delete complete table, call below function,

  @Query("DELETE FROM MyModel")
  void delete();

Note: Here MyModel is a Table Name.

Error in Swift class: Property not initialized at super.init call

Swift will not allow you to initialise super class with out initialising the properties, reverse of Obj C. So you have to initialise all properties before calling "super.init".

Please go to http://blog.scottlogic.com/2014/11/20/swift-initialisation.html. It gives a nice explanation to your problem.

How to construct a std::string from a std::vector<char>?

Well, the best way is to use the following constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

which would lead to something like:

std::vector<char> v;
std::string str(v.begin(), v.end());

Thread Safe C# Singleton Pattern

You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance()
    {
        return instance;
    }
}

AngularJS - ng-if check string empty value

If by "empty" you mean undefined, it is the way ng-expressions are interpreted. Then, you could use :

<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>

What's the best way to get the current URL in Spring MVC?

If you need the URL till hostname and not the path use Apache's Common Lib StringUtil, and from URL extract the substring till third indexOf /.

public static String getURL(HttpServletRequest request){
   String fullURL = request.getRequestURL().toString();
   return fullURL.substring(0,StringUtils.ordinalIndexOf(fullURL, "/", 3)); 
}

Example: If fullURL is https://example.com/path/after/url/ then Output will be https://example.com

Altering a column: null to not null

this worked for me:

ALTER TABLE [Table] 
Alter COLUMN [Column] VARCHAR(50) not null;

What are the differences between ArrayList and Vector?

Basically both ArrayList and Vector both uses internal Object Array.

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.

Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.

Some other differences are: enter image description here

How to Store Historical Data

You can use MSSQL Server Auditing feature. From version SQL Server 2012 you will find this feature in all editions:

http://technet.microsoft.com/en-us/library/cc280386.aspx

Can HTML be embedded inside PHP "if" statement?

<?php if($condition) : ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>

By request, here's elseif and else (which you can also find in the docs)

<?php if($condition) : ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
    more html
<?php else : ?>
    even more html
<?php endif; ?>

It's that simple.

The HTML will only be displayed if the condition is satisfied.

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

How to use graphics.h in codeblocks?

  • Open the file graphics.h using either of Sublime Text Editor or Notepad++,from the include folder where you have installed Codeblocks.
  • Goto line no 302
  • Delete the line and paste int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX, in that line.
  • Save the file and start Coding.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Is there any simple way to convert .xls file to .csv file? (Excel)

Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber parameter. You can overload the method if you need to support earlier versions.

static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
   if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
   if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

   // connection string
   var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
   var cnn = new OleDbConnection(cnnStr);

   // get schema, then data
   var dt = new DataTable();
   try {
      cnn.Open();
      var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
      if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
      string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
      string sql = String.Format("select * from [{0}]", worksheet);
      var da = new OleDbDataAdapter(sql, cnn);
      da.Fill(dt);
   }
   catch (Exception e) {
      // ???
      throw e;
   }
   finally {
      // free resources
      cnn.Close();
   }

   // write out CSV data
   using (var wtr = new StreamWriter(csvOutputFile)) {
      foreach (DataRow row in dt.Rows) {
         bool firstLine = true;
         foreach (DataColumn col in dt.Columns) {
            if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
            var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
            wtr.Write(String.Format("\"{0}\"", data));
         }
         wtr.WriteLine();
      }
   }
}

How to ping multiple servers and return IP address and Hostnames using batch script?

Parsing pingtest.txt for each HOST name and result with batch is difficult because the name and result are on different lines.

It is much easier to test the result (the returned error code) of each PING command directly instead of redirecting to a file. It is also more efficient to enclose the entire construct in parens and redirect the final output just once.

>result.txt (
  for /f %%i in (testservers.txt) do ping -n 1 %%i >nul && echo %%i UP||echo %%i DOWN
)

Converting from longitude\latitude to Cartesian coordinates

In python3.x it can be done using :

# Converting lat/long to cartesian
import numpy as np

def get_cartesian(lat=None,lon=None):
    lat, lon = np.deg2rad(lat), np.deg2rad(lon)
    R = 6371 # radius of the earth
    x = R * np.cos(lat) * np.cos(lon)
    y = R * np.cos(lat) * np.sin(lon)
    z = R *np.sin(lat)
    return x,y,z

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

here is another solution I started using after being fed up with the copy and paste issue:

  1. Download MRemote (for pc). this is an alternative to remote desktop manager. You can use remote desktop manager if you like.
  2. Change the VMNet settings to NAT or add another VMNet and set it to NAT.
  3. Configure the vm ip address with an ip in the same network as you host machine. if you want to keep networks separated use a second vmnet and set it's ip address in the same network as the host. that's what I use.
  4. Enable RDP connections on the guest (I only use windows guests)
  5. Create a batch file with this command. add your guest machines:

vmrun start D:\VM\MySuperVM1\vm1.vmx nogui vmrun start D:\VM\MySuperVM2\vm2.vmx nogui

save the file to startmyvms.cmd

create another batch file and add your vms

vmrun stop D:\VM\MySuperVM1\vm1.vmx nogui vmrun stop D:\VM\MySuperVM2\vm2.vmx nogui

save the file to stopmyvms.cmd

  1. Open Mremote go to tools => External tools Add external tool => filename will be the startmyvms.cmd file Add external tool => filename will be the stopmyvms.cmd file So to start working with your vms:

  2. Create you connections to your VMs in mremote

Now to work with your vm 1. You open mremote 2. You go to tools => external tools 3. You click the startmyvms tool when you're done 1. You go to tools => external tools 2. You click the stopmyvms external tool

you could add the vmrun start on the connection setting => external tool before connection and add the vmrun stop in the connection settings => external tool after

Voilà !

How to add action listener that listens to multiple buttons

First, exend JFrame properly with a super() and a constructor then add actionlisteners to the frame and add the buttons.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;


public class Calc extends JFrame implements ActionListener {
    JButton button1 = new JButton("1");
    JButton button2 = new JButton("2");

    public Calc()
    {
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setSize(100, 100);
         button1.addActionListener(this);
         button2.addActionListener(this);
         calcFrame.add(button1);
         calcFrame.add(button2);
    }
    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();
        if(source == button1)
        {
            \\button1 code here
        } else if(source == button2)
        {
            \\button2 code here
        }
    } 
    public static void main(String[] args)
    {

        JFrame calcFrame = new JFrame();
        calcFrame.setVisible(true);
    }
}

Google Spreadsheet, Count IF contains a string

It will likely have been solved by now, but I ran accross this and figured to give my input

=COUNTIF(a2:a51;"*iPad*")

The important thing is that separating parameters in google docs is using a ; and not a ,

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Best timing method in C?

gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.

kubectl apply vs kubectl create?

The explanation below from the official documentation helped me understand kubectl apply.

This command will compare the version of the configuration that you’re pushing with the previous version and apply the changes you’ve made, without overwriting any automated changes to properties you haven’t specified.

kubectl create on the other hand will create (should be non-existing) resources.

Array of char* should end at '\0' or "\0"?

Well, technically '\0' is a character while "\0" is a string, so if you're checking for the null termination character the former is correct. However, as Chris Lutz points out in his answer, your comparison won't work in it's current form.

Reset/remove CSS styles for element only

For those of you trying to figure out how to actually remove the styling from the element only, without removing the css from the files, this solution works with jquery:

$('.selector').removeAttr('style');

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

Complementing @lasse-v-karlsen answer. To unblock all files recursively, run from powershell as administrator inside the folder you want:

gci -recurse | Unblock-File

source link: How to Unblock Files Downloaded from Internet? - Winhelponline
https://www.winhelponline.com/blog/bulk-unblock-files-downloaded-internet/

How to access Winform textbox control from another class?

Define a property of the form like, then use this in other places it would be available with the form instance

public string SetText
{
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

XAMPP - Apache could not start - Attempting to start Apache service

I had a hard-coded IP in httpd.conf and my local IP had changed which was causing my issue, changed IP over and all worked again

Getting an "ambiguous redirect" error

if you are using a variable name in the shell command, you must concatenate it with + sign.

for example :

if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y

then ('shell command within quotes' + x > + y)

it will work this way especially if you are using this inside a python program with os.system command probably

How to measure height, width and distance of object using camera?

You can't.. You would have to know:

  • How far is the object (you can know your location from GPS.. but the object's location?)
  • What is the focal length of the camera

Maybe, just maybe if the object was optically tagged with for example a QR code, and you have a code-to-loc map...

phpinfo() - is there an easy way for seeing it?

Use the command line.

touch /var/www/project1/html/phpinfo.php && echo '<?php phpinfo(); ?>' >> /var/www/project1/html/phpinfo.php && firefox --url localhost/project1/phpinfo.php

Something like that? Idk!

jQuery: Selecting by class and input type

Try this:

$("input:checkbox").hasClass("myClass");

No submodule mapping found in .gitmodule for a path that's not a submodule

in the file .gitmodules, I replaced string

"path = thirdsrc\boost" 

with

"path = thirdsrc/boost", 

and it solved! - -

Undefined symbols for architecture i386

Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project

QuartzCore.framework

For the bug

Undefined symbols for architecture i386:

HTML5 Canvas and Anti-aliasing

If you need pixel level control over canvas you can do using createImageData and putImageData.

HTML:

<canvas id="qrCode" width="200", height="200">
  QR Code
</canvas>

And JavaScript:

function setPixel(imageData, pixelData) {
  var index = (pixelData.x + pixelData.y * imageData.width) * 4;
    imageData.data[index+0] = pixelData.r;
    imageData.data[index+1] = pixelData.g;
    imageData.data[index+2] = pixelData.b;
    imageData.data[index+3] = pixelData.a;
}

element = document.getElementById("qrCode");
c = element.getContext("2d");

pixcelSize = 4;
width = element.width;
height = element.height;


imageData = c.createImageData(width, height);

for (i = 0; i < 1000; i++) {
  x = Math.random() * width / pixcelSize | 0; // |0 to Int32
  y = Math.random() * height / pixcelSize| 0;

  for(j=0;j < pixcelSize; j++){
    for(k=0;k < pixcelSize; k++){
     setPixel( imageData, {
         x: x * pixcelSize + j,  
         y: y * pixcelSize + k,
         r: 0 | 0,
         g: 0 | 0,
         b: 0 * 256 | 0,
         a: 255 // 255 opaque
       });
      }
  }
}

c.putImageData(imageData, 0, 0);

Working sample here

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

Assign keyboard shortcut to run procedure

You can add some ALT+Letter shortcuts to the VBA editor environment. I added ALT+C to Comment selected text lines and A+X to Uncomment selected text lines:

  1. In the VBE, right-click on a toolbar and select Customize
  2. Optionally create a new toolbar
  3. Select the Command Tab and 'Edit' in the Categories listbox. Find 'Comment Block' in the Commands listbox. Click and drag it to the target toolbar. Left-click on it to open the context popup menu and select 'Image and Text'. Replace the name with &C.
  4. Repeat step 3 for the Uncomment Block command and replace the name with &X.
  5. Close the Customize popup window.

There are built-in Alt+Letter commands that cannot be used for new shortcuts using letters: A,D,E,D,H,I,O,Q,R,T,V,W.

JavaScript Promises - reject vs. throw

TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise

Your particular example obfuscates some important distinctions between them:

Because you are error handling inside a promise chain, thrown exceptions get automatically converted to rejected promises. This may explain why they seem to be interchangeable - they are not.

Consider the situation below:

checkCredentials = () => {
    let idToken = localStorage.getItem('some token');
    if ( idToken ) {
      return fetch(`https://someValidateEndpoint`, {
        headers: {
          Authorization: `Bearer ${idToken}`
        }
      })
    } else {
      throw new Error('No Token Found In Local Storage')
    }
  }

This would be an anti-pattern because you would then need to support both async and sync error cases. It might look something like:

try {
  function onFulfilled() { ... do the rest of your logic }
  function onRejected() { // handle async failure - like network timeout }
  checkCredentials(x).then(onFulfilled, onRejected);
} catch (e) {
  // Error('No Token Found In Local Storage')
  // handle synchronous failure
} 

Not good and here is exactly where Promise.reject ( available in the global scope ) comes to the rescue and effectively differentiates itself from throw. The refactor now becomes:

checkCredentials = () => {
  let idToken = localStorage.getItem('some_token');
  if (!idToken) {
    return Promise.reject('No Token Found In Local Storage')
  }
  return fetch(`https://someValidateEndpoint`, {
    headers: {
      Authorization: `Bearer ${idToken}`
    }
  })
}

This now lets you use just one catch() for network failures and the synchronous error check for lack of tokens:

checkCredentials()
      .catch((error) => if ( error == 'No Token' ) {
      // do no token modal
      } else if ( error === 400 ) {
      // do not authorized modal. etc.
      }

How to select multiple rows filled with constants?

select (level - 1) * row_dif + 1 as a, (level - 1) * row_dif + 2 as b, (level - 1) * row_dif + 3 as c
    from dual 
    connect by level <= number_of_rows;

something like that

select (level - 1) * 3 + 1 as a, (level - 1) * 3 + 2 as b, (level - 1) * 3 + 3 as c
    from dual 
    connect by level <= 3;

Running interactive commands in Paramiko

You can use this method to send whatever confirmation message you want like "OK" or the password. This is my solution with an example:

def SpecialConfirmation(command, message, reply):
    net_connect.config_mode()    # To enter config mode
    net_connect.remote_conn.sendall(str(command)+'\n' )
    time.sleep(3)
    output = net_connect.remote_conn.recv(65535).decode('utf-8')
    ReplyAppend=''
    if str(message) in output:
        for i in range(0,(len(reply))):
            ReplyAppend+=str(reply[i])+'\n'
        net_connect.remote_conn.sendall(ReplyAppend)
        output = net_connect.remote_conn.recv(65535).decode('utf-8') 
    print (output)
    return output

CryptoPkiEnroll=['','','no','no','yes']

output=SpecialConfirmation ('crypto pki enroll TCA','Password' , CryptoPkiEnroll )
print (output)

Launch custom android application from android browser

Felix's approach to handling deep links is the typical approach to handling deep links. I would also suggest checking out this library to handle the routing and parsing of your deep links:

https://github.com/airbnb/DeepLinkDispatch

You can use annotations to register your Activity for a particular deep link URI, and it will extract out the parameters for you without having to do the usual rigmarole of getting the path segments, matching it, etc. You could simply annotate and activity like this:

@DeepLink("somePath/{someParameter1}/{someParameter2}")
public class MainActivity extends Activity {
   ...
}

How to get just one file from another branch

Review the file on github and pull it from there

This is a pragmatic approach which doesn't directly answer the OP, but some have found useful:

If the branch in question is on GitHub, then you can navigate to the desired branch and file using any of the many tools that GitHub offers, then click 'Raw' to view the plain text, and (optionally) copy and paste the text as desired.

I like this approach because it lets you look at the remote file in its entirety before pulling it to your local machine.

Check a radio button with javascript

Easiest way would probably be with jQuery, as follows:

$(document).ready(function(){
  $("#_1234").attr("checked","checked");
})

This adds a new attribute "checked" (which in HTML does not need a value). Just remember to include the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

How to copy part of an array to another array in C#?

int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • a = source array
  • 1 = start index in source array
  • b = destination array
  • 0 = start index in destination array
  • 3 = elements to copy

Can an ASP.NET MVC controller return an Image?

You can write directly to the response but then it isn't testable. It is preferred to return an ActionResult that has deferred execution. Here is my resusable StreamResult:

public class StreamResult : ViewResult
{
    public Stream Stream { get; set; }
    public string ContentType { get; set; }
    public string ETag { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = ContentType;
        if (ETag != null) context.HttpContext.Response.AddHeader("ETag", ETag);
        const int size = 4096;
        byte[] bytes = new byte[size];
        int numBytes;
        while ((numBytes = Stream.Read(bytes, 0, size)) > 0)
            context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);
    }
}

Concatenate chars to form String in java

You can use StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.append('a');
    sb.append('b');
    sb.append('c');
    String str = sb.toString()

Or if you already have the characters, you can pass a character array to the String constructor:

String str = new String(new char[]{'a', 'b', 'c'});

How to check if a "lateinit" variable has been initialized?

To check if a lateinit var were initialised or not use a .isInitialized on the reference to that property:

if (foo::bar.isInitialized) {
    println(foo.bar)
}

This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.

How to find and restore a deleted file in a Git repository

In many cases, it can be useful to use coreutils (grep, sed, etc.) in conjunction with Git. I already know these tools quite well, but Git less so. If I wanted to do a search for a deleted file, I would do the following:

git log --raw | grep -B 30 $'D\t.*deleted_file.c'

When I find the revision/commit:

git checkout <rev>^ -- path/to/refound/deleted_file.c

Just like others have stated before me.

The file will now be restored to the state it had before removal. Remember to re-commit it to the working tree if you want to keep it around.

How can I use a custom font in Java?

Here is how I did it!

//create the font

try {
    //create the font to use. Specify the size!
    Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //register the font
    ge.registerFont(customFont);
} catch (IOException e) {
    e.printStackTrace();
} catch(FontFormatException e) {
    e.printStackTrace();
}

//use the font
yourSwingComponent.setFont(customFont);

@Autowired - No qualifying bean of type found for dependency

I had this happen because my tests were not in the same package as my components. (I had renamed my component package, but not my test package.) And I was using @ComponentScan in my test @Configuration class, so my tests weren't finding the components on which they relied.

So, double check that if you get this error.

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

AngularJS - Binding radio buttons to models with boolean values

 <label class="rate-hit">
     <input type="radio" ng-model="st.result" ng-value="true" ng-checked="st.result">
     Hit
 </label>
 &nbsp;&nbsp;
 <label class="rate-miss">
     <input type="radio" ng-model="st.result" ng-value="false" ng-checked="!st.result">
     Miss
 </label>