Programs & Examples On #Xbap

XBAP (XAML Browser Application) are Windows Presentation Foundation (WPF) applications that run in a sandboxed environment in a user's browser

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

How do I create a WPF Rounded Corner container?

You don't need a custom control, just put your container in a border element:

<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
   <Grid/>
</Border>

You can replace the <Grid/> with any of the layout containers...

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

Connect to SQL Server Database from PowerShell

Assuming you can use integrated security, you can remove the user id and pass:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

If you know the sessionID then you can use the following:

SELECT * FROM sys.dm_exec_requests WHERE session_id = 62

Or if you want to narrow it down:

SELECT command, percent_complete, start_time FROM sys.dm_exec_requests WHERE session_id = 62

Installed Java 7 on Mac OS X but Terminal is still using version 6

Hard-coding the JAVA_HOME path might not be the best idea. The /usr/libexec/java_home utility sill works for me on Mac OSX Lion 10.7.5 and JDK 1.7.0_13. According to its man page, it is meant to be used with Apple's old Java Preferences pane, but it appears to be working with the replacement provided by Oracle (Java Control Panel). For example running /usr/libexec/java_home -V lists all installed JDKs (both 1.6.* and 1.7.*) on my machine.

So, as discussed in other threads (e.g. What should I set JAVA_HOME to on OSX), I would still recommend adding the following line to your .bash_profile:

export JAVA_HOME=$(/usr/libexec/java_home)

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

Permutations in JavaScript?

This is an interesting task and and here is my contribution. It's very simple and fast. If interested please bear with me and read on.

If you would like to this job fast, you definitely have to get yourself into dynamical programming. Which means you should forget about recursive approaches. That's for sure...

OK le_m's code which uses the Heap's method seems to be the fastest so far. Well i haven't got a name for my algorithm, i don't know if it's already been implemented or not but it's very simple and fast. As with all dynamical programming approaches we will start with the simplest problem and go for the final result.

Assuming that we have an array of a = [1,2,3] we will start with

r = [[1]]; // result
t = [];    // interim result

Then follow these three steps;

  1. For each item of our r (result) array we will add the next item of the input array.
  2. We will rotate each item it's length many times and will store each instance at the interim result array t. (well except for the first one not to waste time with 0 rotation)
  3. Once we finish with all items of r the interim array t should hold the next level of results so we make r = t; t = []; and carry on up until the length of the input array a.

So the following are our steps;

r array   | push next item to |  get length many rotations
          |  each sub array   |       of each subarray
-----------------------------------------------------------
[[1]]     |     [[1,2]]       |     [[1,2],[2,1]]
----------|-------------------|----------------------------
[[1,2],   |     [[1,2,3],     |     [[1,2,3],[2,3,1],[3,1,2],
 [2,1]]   |      [2,1,3]]     |      [2,1,3],[1,3,2],[3,2,1]]
----------|-------------------|----------------------------
previous t|                   |
-----------------------------------------------------------

So here is the code

_x000D_
_x000D_
function perm(a){_x000D_
  var r = [[a[0]]],_x000D_
      t = [],_x000D_
      s = [];_x000D_
  if (a.length <= 1) return a;_x000D_
  for (var i = 1, la = a.length; i < la; i++){_x000D_
    for (var j = 0, lr = r.length; j < lr; j++){_x000D_
      r[j].push(a[i]);_x000D_
      t.push(r[j]);_x000D_
      for(var k = 1, lrj = r[j].length; k < lrj; k++){_x000D_
        for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];_x000D_
        t[t.length] = s;_x000D_
        s = [];_x000D_
      }_x000D_
    }_x000D_
    r = t;_x000D_
    t = [];_x000D_
  }_x000D_
  return r;_x000D_
}_x000D_
_x000D_
var arr = [0,1,2,4,5];_x000D_
console.log("The length of the permutation is:",perm(arr).length);_x000D_
console.time("Permutation test");_x000D_
for (var z = 0; z < 2000; z++) perm(arr);_x000D_
console.timeEnd("Permutation test");
_x000D_
_x000D_
_x000D_

In multiple test i have seen it resolving the 120 permutations of [0,1,2,3,4] for 2000 times in 25~35ms.

How to write a foreach in SQL Server?

I came up with a very effective, (I think) readable way to do this.

    1. create a temp table and put the records you want to iterate in there
    2. use WHILE @@ROWCOUNT <> 0 to do the iterating
    3. to get one row at a time do, SELECT TOP 1 <fieldnames>
        b. save the unique ID for that row in a variable
    4. Do Stuff, then delete the row from the temp table based on the ID saved at step 3b.

Here's the code. Sorry, its using my variable names instead of the ones in the question.

            declare @tempPFRunStops TABLE (ProformaRunStopsID int,ProformaRunMasterID int, CompanyLocationID int, StopSequence int );    

        INSERT @tempPFRunStops (ProformaRunStopsID,ProformaRunMasterID, CompanyLocationID, StopSequence) 
        SELECT ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence from ProformaRunStops 
        WHERE ProformaRunMasterID IN ( SELECT ProformaRunMasterID FROM ProformaRunMaster WHERE ProformaId = 15 )

    -- SELECT * FROM @tempPFRunStops

    WHILE @@ROWCOUNT <> 0  -- << I dont know how this works
        BEGIN
            SELECT TOP 1 * FROM @tempPFRunStops
            -- I could have put the unique ID into a variable here
            SELECT 'Ha'  -- Do Stuff
            DELETE @tempPFRunStops WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
        END

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Had this problem when setting up a new slave server. Found it was the slave server IP address was missing from the master server /etc/hosts.allow file. Added the IP address and it let me connect to the master server.

Note that I use hosts.allow and hosts.deny to control access.

ng is not recognized as an internal or external command

I faced same issue when i tried to install angular cli locally with command

npm install @angular/cli@latest

After that i got same issue C:\Users\vi1kumar\Desktop\tus\ANGULAR\AngularForms>ng -v 'ng' is not recognized as an internal or external command, operable program or batch file

Than i tried to install it globally

npm install -g @angular/cli@latest

In this case case it worked i was wondering that is it not possible to install cli globally ?

After doing some research i found this article very helpful hope it will help someone facing similar issue

Working with multiple versions of Angular CLI

CSS Box Shadow - Top and Bottom Only

So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.

HTML

<div class="shadow-block">
    <div class="shadow"></div>
    <div class="overlay">
        <div class="overlay-inner">
            content here
        </div>
    </div>
</div>

CSS

.overlay {
    background: #f7f7f4;
    height: 185px;
    overflow: hidden;
    position: relative;
    width: 100%; 
}

.overlay:before {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
    content: " ";
    display: block;
    margin: 0 auto;
    width: 80%;
}

.overlay:after {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
    content: "-";
    display: block;
    margin: 0 auto;
    position: absolute;
    bottom: -65px;
    left: -50%;
    right: -50%;
    width: 80%;
}

.shadow {
    position: relative;
    width:100%;
    height:8px;
    margin: 0 0 -22px 0;
    -webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    border-radius: 50%;
}

How can I set a proxy server for gem?

You can try export http_proxy=http://your_proxy:your_port

Generate SHA hash in C++ using OpenSSL library

From the command line, it's simply:

printf "compute sha1" | openssl sha1

You can invoke the library like this:

#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>

int main()
{
    unsigned char ibuf[] = "compute sha1";
    unsigned char obuf[20];

    SHA1(ibuf, strlen(ibuf), obuf);

    int i;
    for (i = 0; i < 20; i++) {
        printf("%02x ", obuf[i]);
    }
    printf("\n");

    return 0;
}

How do I add a border to an image in HTML?

The answers above are very good I'm sure. But for dim-wits, like me, I recommend Snagit 10. You can give an image a border in any width, style, and color before inserting it into your webpage. They do a full working program on 30 day trial.

SQL Current month/ year question

This should work in MySql

SELECT * FROM 'my_table' WHERE 'month' = MONTH(CURRENT_TIMESTAMP) AND 'year' = YEAR(CURRENT_TIMESTAMP);

How to break out of while loop in Python?

What I would do is run the loop until the ans is Q

ans=(R)
while not ans=='Q':
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore

Google Maps API v3: How to remove all markers?

This is the method Google themselves use in at least one sample:

var markers = [];

// Clear out the old markers.
markers.forEach(function(marker) {
  marker.setMap(null);
});
markers = [];

Check Google sample for complete code example:

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

How should I escape commas and speech marks in CSV files so they work in Excel?

Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.

  1. If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.

  2. Any double quote characters in the value should be escaped with another double quote.

  3. If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.

How to simulate browsing from various locations?

This is a bit of self promotion, but I built a tool to do just this that you might find useful, called GeoPeeker.

It remotely accesses a site from servers spread around the world, renders the page with webkit and sends back an image. It will also report the IP address and DNS information of the site as it appears from that location.

There are no ads, and it's very stream-lined to serve this one purpose. It's still in development, and feedback is welcome. Here's hoping somebody besides myself finds it useful!

How can I display an RTSP video stream in a web page?

I have published project on Github that help you to stream ip/network camera on to web browser real time without plugin require, which I contributed to open source project under MIT License that might be matched to your need, here you go:

Streaming IP/Network Camera on web browser using NodeJS

There is no full package of framework yet, but it is a kickstart that might give you a way to proceed further.
As a student, I hope this helpful and please contribute to this project.

Sublime Text 2 - View whitespace characters

http://sublimetexttips.com/show-whitespace-sublime-text/

  1. open

Ctrl+Shift+P

  1. search

Preferences: Settings –> User

  1. just paste below codes

_x000D_
_x000D_
{_x000D_
    "draw_white_space": "all",_x000D_
    "translate_tabs_to_spaces": true_x000D_
}
_x000D_
_x000D_
_x000D_

How to delete node from XML file using C#

You can use Linq to XML to do this:

XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
        let attr = node.Attribute("name")
        where attr != null && attr.Value == "File1"
        select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

.htaccess rewrite to redirect root URL to subdirectory

This will try the subdir if the file doesn't exist in the root. Needed this as I moved a basic .html website that expects to be ran at the root level and pushed it to a subdir. Only works if all files are flat (no .htaccess trickery in the subdir possible). Useful for linked things like css and js files.

# Internal Redirect to subdir if file is found there.
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-s
RewriteCond %{DOCUMENT_ROOT}/subdir/%{REQUEST_URI} -s
RewriteRule ^(.*)$ /subdir/$1 [L]

Change default date time format on a single database in SQL Server

Use:

select * from mytest
EXEC sp_rename 'mytest.eid', 'id', 'COLUMN'
alter table mytest add id int not null identity(1,1)
update mytset set eid=id
ALTER TABLE mytest DROP COLUMN eid

ALTER TABLE [dbo].[yourtablename] ADD DEFAULT (getdate()) FOR [yourfieldname]

It's working 100%.

Selecting default item from Combobox C#

private void comboBox_Loaded(object sender, RoutedEventArgs e)
{
 Combobox.selectedIndex= your index;
}

OR if you want to display some value after comparing into combobox

 foreach (var item in comboBox.Items)
            {
                if (item.ToString().ToLower().Equals("your item in lower"))
                {
                    comboBox.SelectedValue = item;
                }
            }

I hope it will help, it works for me.

What is the symbol for whitespace in C?

No special escape sequence is required: you can just type the space directly:

if (char_i_want_to_test == ' ') { 
    // Do something because it is space
}

In ASCII, space is code 32, so you could specify space by '\x20' or even 32, but you really shouldn't do that.

Aside: the word "whitespace" is a catch all for space, tab, newline, and all of that. When you're referring specifically to the ordinary space character, you shouldn't use the term.

CSS way to horizontally align table

Although it might be heresy in today's world - in the past you would do the following non-css code. This works in everything up to and including today's browsers but - as I have said - it is heresy in today's world:

<center>
<table>
   ...
</table>
</center>

What you need is some way to tell that you want to center a table and the person is using an older browser. Then insert the "<center>" commands around the table. Otherwise - use css.

Surprisingly - if you want to center everything in the BODY area - you just can use the standard

text-align: center;

css command and in IE8 (at least) it will center everything on the page including tables.

Remove an item from a dictionary when its key is unknown

The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'

Example:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

The problem is that dataTable is not defined at the point you are calling this method.

Ensure that you are loading the .js files in the correct order:

<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>

Cross-Domain Cookies

As far as I know, cookies are limited by the "same origin" policy. However, with CORS you can receive and use the "Server B" cookies to establish a persistent session from "Server A" on "Server B".

Although, this requires some headers on "Server B":

Access-Control-Allow-Origin: http://server-a.domain.com
Access-Control-Allow-Credentials: true

And you will need to send the flag "withCredentials" on all the "Server A" requests (ex: xhr.withCredentials = true;)

You can read about it here:

http://www.html5rocks.com/en/tutorials/cors/

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

ContractFilter mismatch at the EndpointDispatcher exception

I had the same issue. The problem was that I copied the code from another service as a starting point and did not change the service class in .svc file

Open the .svc file an make sure that the Service attribute is correct.

 <%@ ServiceHost Language="C#" Debug="true" Service="SME.WCF.ApplicationServices.ReportRenderer" CodeBehind="ReportRenderer.svc.cs" %>

error C2065: 'cout' : undeclared identifier

Are you sure it's compiling as C++? Check your file name (it should end in .cpp). Check your project settings.

There's simply nothing wrong with your program, and cout is in namespace std. Your installation of VS 2010 Beta 2 is defective, and I don't think it's just your installation.

I don't think VS 2010 is ready for C++ yet. The standard "Hello, World" program didn't work on Beta 1. I just tried creating a test Win32 console application, and the generated test.cpp file didn't have a main() function.

I've got a really, really bad feeling about VS 2010.

CSS - display: none; not working

In the HTML source provided, the element #tfl has an inline style "display:block". Inline style will always override stylesheets styles…

Then, you have some options (while as you said you can't modify the html code nor using javascript):

  • force display:none with !important rule (not recommended)
  • put the div offscreen with theses rules :

    #tfl {
        position: absolute;
        left: -9999px;
    }
    

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        {
        AssetID = x.AssetID,
        Status = xx.Online ?? false
        };

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness).

However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything displayed in a normal web browser.

Some things to note:

  • You must have the Python version of Selenium RC installed for this to work, and you must have set up Selenium properly. Also this is just a template crawler. You could get much crazier and more advanced with things but I just wanted to show the basic idea. As the code stands now you will be doing two requests for any given url. One request is made by Scrapy and the other is made by Selenium. I am sure there are ways around this so that you could possibly just make Selenium do the one and only request but I did not bother to implement that and by doing two requests you get to crawl the page with Scrapy too.

  • This is quite powerful because now you have the entire rendered DOM available for you to crawl and you can still use all the nice crawling features in Scrapy. This will make for slower crawling of course but depending on how much you need the rendered DOM it might be worth the wait.

    from scrapy.contrib.spiders import CrawlSpider, Rule
    from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
    from scrapy.selector import HtmlXPathSelector
    from scrapy.http import Request
    
    from selenium import selenium
    
    class SeleniumSpider(CrawlSpider):
        name = "SeleniumSpider"
        start_urls = ["http://www.domain.com"]
    
        rules = (
            Rule(SgmlLinkExtractor(allow=('\.html', )), callback='parse_page',follow=True),
        )
    
        def __init__(self):
            CrawlSpider.__init__(self)
            self.verificationErrors = []
            self.selenium = selenium("localhost", 4444, "*chrome", "http://www.domain.com")
            self.selenium.start()
    
        def __del__(self):
            self.selenium.stop()
            print self.verificationErrors
            CrawlSpider.__del__(self)
    
        def parse_page(self, response):
            item = Item()
    
            hxs = HtmlXPathSelector(response)
            #Do some XPath selection with Scrapy
            hxs.select('//div').extract()
    
            sel = self.selenium
            sel.open(response.url)
    
            #Wait for javscript to load in Selenium
            time.sleep(2.5)
    
            #Do some crawling of javascript created content with Selenium
            sel.get_text("//div")
            yield item
    
    # Snippet imported from snippets.scrapy.org (which no longer works)
    # author: wynbennett
    # date  : Jun 21, 2011
    

Reference: http://snipplr.com/view/66998/

How to remove an element slowly with jQuery?

I've modified Greg's answer to suit my case, and it works. Here it is:

$("#note-items").children('.active').hide('slow', function(){ $("#note-items").children('.active').remove(); });

href overrides ng-click in Angular.js

This worked for me in IE 9 and AngularJS v1.0.7:

<a href="javascript:void(0)" ng-click="logout()">Logout</a>

Thanks to duckeggs' comment for the working solution!

window.onload vs <body onload=""/>

There is no difference, but you should not use either.

In many browsers, the window.onload event is not triggered until all images have loaded, which is not what you want. Standards based browsers have an event called DOMContentLoaded which fires earlier, but it is not supported by IE (at the time of writing this answer). I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use. jQuery's $(document).ready(), is a good example.

Git submodule head 'reference is not a tree' error

In my case, none of answer above solve the problem even thoungh they are good answers. So I post my solution (in my case there are two git clients, client A and B):

  1. go to submodule's dir:

    cd sub
    
  2. checkout to master:

    git checkout master
    
  3. rebase to a commit code which both client can see

  4. go back to the parent's dir:

  5. commit to master

  6. change to the other client, do rebase again.

  7. finally it works fine now! Maybe lose a couple of commits but it works.

  8. FYI, don't try to remove your submodule, it will remain .git/modules there and cannot readd this submodule again, unless reactive local one.

What version of Java is running in Eclipse?

Under the help menu, there should be a menu item labeled "About Eclipse" I can't say with absolute precision because I'm using STS which is the same thing but my label is different.

In the dialog box that opens after you click the relevant about menu item there should be an installation details button in the lower left hand corner.

The version of Java that you're running Eclipse against ought to be in "System properties:" under the "Configuration" tab.

Which is a better way to check if an array has more than one element?

Obviously using count($arr) > 1 (sizeof is just an alias for count) is the best solution. Depending on the structure of your array, there might be tons of elements but no $array['1'] element.

Capturing a single image from my webcam in Java or Python

import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)& 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()

How to get the unique ID of an object which overrides hashCode()?

There is a difference between hashCode() and identityHashCode() returns. It is possible that for two unequal (tested with ==) objects o1, o2 hashCode() can be the same. See the example below how this is true.

class SeeDifferences
{
    public static void main(String[] args)
    {
        String s1 = "stackoverflow";
        String s2 = new String("stackoverflow");
        String s3 = "stackoverflow";
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println(s3.hashCode());
        System.out.println(System.identityHashCode(s1));
        System.out.println(System.identityHashCode(s2));
        System.out.println(System.identityHashCode(s3));
        if (s1 == s2)
        {
            System.out.println("s1 and s2 equal");
        } 
        else
        {
            System.out.println("s1 and s2 not equal");
        }
        if (s1 == s3)
        {
            System.out.println("s1 and s3 equal");
        }
        else
        {
            System.out.println("s1 and s3 not equal");
        }
    }
}

Java regex to extract text between tags

You're on the right track. Now you just need to extract the desired group, as follows:

final Pattern pattern = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("<tag>String I want to extract</tag>");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract

If you want to extract multiple hits, try this:

public static void main(String[] args) {
    final String str = "<tag>apple</tag><b>hello</b><tag>orange</tag><tag>pear</tag>";
    System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]
}

private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);

private static List<String> getTagValues(final String str) {
    final List<String> tagValues = new ArrayList<String>();
    final Matcher matcher = TAG_REGEX.matcher(str);
    while (matcher.find()) {
        tagValues.add(matcher.group(1));
    }
    return tagValues;
}

However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.

How to align center the text in html table row?

The CSS to center text in your td elements is

td {
  text-align: center;
  vertical-align: middle;
}

org.hibernate.MappingException: Unknown entity: annotations.Users

If your entity is mapped through annotations, add the following code to your configuration;

configuration.addAnnotatedClass(theEntityPackage.EntityClassName.class);

For example;

configuration.addAnnotatedClass(com.foo.foo1.Products.class);

if your entity is mapped with xml file, use addClass instead of addAnnotatedClass.

As an example;

configuration.addClass(com.foo.foo1.Products.class);

Ping me if you need more help.

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>

or

<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

Definition of a Balanced Tree

the aim of balanced tree is to reach the leaf in a minimum of traversal (min height). The degree of the tree is the number of branches minus 1. A Balanced tree may be not Binary.

Correct use for angular-translate in controllers

What is happening is that Angular-translate is watching the expression with an event-based system, and just as in any other case of binding or two-way binding, an event is fired when the data is retrieved, and the value changed, which obviously doesn't work for translation. Translation data, unlike other dynamic data on the page, must, of course, show up immediately to the user. It can't pop in after the page loads.

Even if you can successfully debug this issue, the bigger problem is that the development work involved is huge. A developer has to manually extract every string on the site, put it in a .json file, manually reference it by string code (ie 'pageTitle' in this case). Most commercial sites have thousands of strings for which this needs to happen. And that is just the beginning. You now need a system of keeping the translations in synch when the underlying text changes in some of them, a system for sending the translation files out to the various translators, of reintegrating them into the build, of redeploying the site so the translators can see their changes in context, and on and on.

Also, as this is a 'binding', event-based system, an event is being fired for every single string on the page, which not only is a slower way to transform the page but can slow down all the actions on the page, if you start adding large numbers of events to it.

Anyway, using a post-processing translation platform makes more sense to me. Using GlobalizeIt for example, a translator can just go to a page on the site and start editing the text directly on the page for their language, and that's it: https://www.globalizeit.com/HowItWorks. No programming needed (though it can be programmatically extensible), it integrates easily with Angular: https://www.globalizeit.com/Translate/Angular, the transformation of the page happens in one go, and it always displays the translated text with the initial render of the page.

Full disclosure: I'm a co-founder :)

Android Studio Rendering Problems : The following classes could not be found

I have faced this issue when I introduced additional supporting libraries in my project IntelliJ IDEA

So for me "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.

How do I check two or more conditions in one <c:if>?

This look like a duplicate of JSTL conditional check.

The error is having the && outside the expression. Instead use

<c:if test="${ISAJAX == 0 && ISDATE == 0}">

How to parse SOAP XML?

PHP version > 5.0 has a nice SoapClient integrated. Which doesn't require to parse response xml. Here's a quick example

$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->PaymentNotification->payment;

How to get current user in asp.net core

Perhaps I didn't see the answer, but this is how I do it.

  1. .Net Core --> Properties --> launchSettings.json

You need to have change these values

"windowsAuthentication": true, // needs to be true
"anonymousAuthentication": false,  // needs to be false 

Startup.cs --> ConfigureServices(...)

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

MVC or Web Api Controller

private readonly IHttpContextAccessor _httpContextAccessor;
//constructor then
_httpContextAccessor = httpContextAccessor;

Controller method:

string userName = _httpContextAccessor.HttpContext.User.Identity.Name;

Result is userName e.g. = Domain\username

Convert PEM to PPK file format

To SSH connectivity to AWS EC2 instance, You don't need to convert the .PEM file to PPK file even on windows machine, Simple SSH using 'git bash' tool. No need to download and convert these softwares - Hope this will save your time of downloading and converting keys and get you more time on EC2 things.

SQL Query to fetch data from the last 30 days?

The easiest way would be to specify

SELECT productid FROM product where purchase_date > sysdate-30;

Remember this sysdate above has the time component, so it will be purchase orders newer than 03-06-2011 8:54 AM based on the time now.

If you want to remove the time conponent when comparing..

SELECT productid FROM product where purchase_date > trunc(sysdate-30);

And (based on your comments), if you want to specify a particular date, make sure you use to_date and not rely on the default session parameters.

SELECT productid FROM product where purchase_date > to_date('03/06/2011','mm/dd/yyyy')

And regardng the between (sysdate-30) - (sysdate) comment, for orders you should be ok with usin just the sysdate condition unless you can have orders with order_dates in the future.

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

How can I color Python logging output?

FriendlyLog is another alternative. It works with Python 2 & 3 under Linux, Windows and MacOS.

How to convert vector to array

Vectors effectively are arrays under the skin. If you have a function:

void f( double a[]);

you can call it like this:

vector <double> v;
v.push_back( 1.23 )
f( &v[0] );

You should not ever need to convert a vector into an actual array instance.

how to send multiple data with $.ajax() jquery

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

How to check whether an array is empty using PHP?

I use this code

$variable = array();

if( count( $variable ) == 0 )
{
    echo "Array is Empty";
}
else
{
    echo "Array is not Empty";
}

But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

How do I add BundleConfig.cs to my project?

If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html

If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/

Are iframes considered 'bad practice'?

The original frameset model (Frameset and Frame-elements) were very bad from a usability standpoint. IFrame vas a later invention which didn't have as many problems as the original frameset model, but it does have its drawback.

If you allow the user to navigate inside the IFrame, then links and bookmarks will not work as expected (because you bookmark the URL of the outer page, but not the URL of the iframe).

how to deal with google map inside of a hidden div (Updated picture)

My solution was:

CSS:

.map {
   height: 400px;
   border: #ccc solid 1px;
}

jQuery:

$('.map').width(555); // width of map canvas

How to open a new tab in GNOME Terminal from command line?

You can also have each tab run a set command.

gnome-terminal --tab -e "tail -f somefile" --tab -e "some_other_command"

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

how to add value to combobox item

Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:

        Dim comboSource As New Dictionary(Of String, String)()
        cboMenu.Items.Clear()
        For I = 0 To SomeList.GetUpperBound(0)
            comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
        Next I
        cboMenu.DataSource = New BindingSource(comboSource, Nothing)
        cboMenu.DisplayMember = "Value"
        cboMenu.ValueMember = "Key"

Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:

Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
    SetListGrid(cboManufMenu.SelectedValue)
End Sub

@try - catch block in Objective-C

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

applying css to specific li class

Define them more in your css file. Instead of

li.sub-navigation-home-news 

try

#sub-navigation-home li.sub-navigation-home-news 

Check this for more details: http://www.w3.org/TR/CSS2/cascade.html#cascade

How connect Postgres to localhost server using pgAdmin on Ubuntu?

Modify password for role postgres:

sudo -u postgres psql postgres

alter user postgres with password 'postgres';

Now connect to pgadmin using username postgres and password postgres

Now you can create roles & databases using pgAdmin

How to change PostgreSQL user password?

PHP Fatal error: Uncaught exception 'Exception'

For

throw new Exception('test exception');

I got 500 (but didn't see anything in the browser), until I put

php_flag display_errors on

in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only

Convert an object to an XML string

 public static class XMLHelper
    {
        /// <summary>
        /// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
        /// </summary>
        /// <typeparam name="T">Ki?u d? li?u</typeparam>
        /// <param name="value">giá tr?</param>
        /// <param name="omitXmlDeclaration">b? qua declare</param>
        /// <param name="removeEncodingDeclaration">xóa encode declare</param>
        /// <returns>xml string</returns>
        public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
        {
            if (value == null)
            {
                return string.Empty;
            }
            try
            {
                var xmlWriterSettings = new XmlWriterSettings
                {
                    Indent = true,
                    OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
                    Encoding = Encoding.UTF8,
                    NewLineChars = "", // remove \r\n
                };

                var xmlserializer = new XmlSerializer(typeof(T));

                using (var memoryStream = new MemoryStream())
                {
                    using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
                    {
                        xmlserializer.Serialize(xmlWriter, value);
                        //return stringWriter.ToString();
                    }

                    memoryStream.Position = 0;
                    using (var sr = new StreamReader(memoryStream))
                    {
                        var pureResult = sr.ReadToEnd();
                        var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
                        if (omitEncodingDeclaration)
                            return resultAfterOmitEncoding;
                        return pureResult;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XMLSerialize error: ", ex);
            }
        }

        private static string ReplaceFirst(string text, string search, string replace)
        {
            int pos = text.IndexOf(search);

            if (pos < 0)
            {
                return text;
            }

            return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
        }
    }

A keyboard shortcut to comment/uncomment the select text in Android Studio

On Mac you need cmd + / to comment and uncomment.

How to write asynchronous functions for Node.js

Just passing by callbacks is not enough. You have to use settimer for example, to make function async.

Examples: Not async functions:

function a() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };
  b();
};

function b() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };    
  c();
};

function c() {
  for(i=0; i<10000000; i++) {
  };
  console.log("async finished!");
};

a();
console.log("This should be good");

If you will run above example, This should be good, will have to wait untill those functions will finish to work.

Pseudo multithread (async) functions:

function a() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };
    b();
  }, 0);
};

function b() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };  
    c();
  }, 0);
};

function c() {
  setTimeout ( function() {
    for(i=0; i<10000000; i++) {
    };
    console.log("async finished!");
  }, 0);
};

a();
console.log("This should be good");

This one will be trully async. This should be good will be writen before async finished.

Understanding the difference between Object.create() and new SomeFunction()

Object.create(Constructor.prototype) is the part of new Constructor

this is new Constructor implementation

// 1. define constructor function

      function myConstructor(name, age) {
        this.name = name;
        this.age = age;
      }
      myConstructor.prototype.greet = function(){
        console.log(this.name, this.age)
      };

// 2. new operator implementation

      let newOperatorWithConstructor = function(name, age) {
        const newInstance = new Object(); // empty object
        Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

// 3. produce new instance

      const instance = new myConstructor("jun", 28);
      const instance2 = newOperatorWithConstructor("jun", 28);
      console.log(instance);
      console.log(instance2);
      

new Constructor implementation contains Object.create method

      newOperatorWithConstructor = function(name, age) {
        const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

      console.log(newOperatorWithConstructor("jun", 28));

Is an empty href valid?

Try to do <a href="#" class="arrow"> instead. (Note the sharp # character).

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

Using different Web.config in development and production environment

On one project where we had 4 environments (development, test, staging and production) we developed a system where the application selected the appropriate configuration based on the machine name it was deployed to.

This worked for us because:

  • administrators could deploy applications without involving developers (a requirement) and without having to fiddle with config files (which they hated);
  • machine names adhered to a convention. We matched names using a regular expression and deployed to multiple machines in an environment; and
  • we used integrated security for connection strings. This means we could keep account names in our config files at design time without revealing any passwords.

It worked well for us in this instance, but probably wouldn't work everywhere.

Setting PHPMyAdmin Language

In config.inc.php in the top-level directory, set

$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users

If Lang isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.

Pytorch tensor to numpy array

Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

Pytorch tensor to numpy array

you need improve your question starting with your title.

Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

RuntimeError: Can't call numpy() on Variable that requires grad.

So call .detach(). Sample code:

# creating data and running through a nn and saving it

import torch
import torch.nn as nn

from pathlib import Path
from collections import OrderedDict

import numpy as np

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1

x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))

f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
y = f(x)

# save data
y.numpy()
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
np.savez(path / 'db', x=x_np, y=y_np)

print(x_np)

cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

Understanding slice notation

How to enable cURL in PHP / XAMPP

You can check phpinfo() (create a script containing and browse to it). This will tell you if you really do have it enabled. If not, read here.

It is not recommended for the faint-hearted Windows developer.

Compare objects in Angular

Assuming that the order is the same in both objects, just stringify them both and compare!

JSON.stringify(obj1) == JSON.stringify(obj2);

Remove duplicate values from JS array

var uniqueCompnies = function(companyArray) {
    var arrayUniqueCompnies = [],
        found, x, y;

    for (x = 0; x < companyArray.length; x++) {
        found = undefined;
        for (y = 0; y < arrayUniqueCompnies.length; y++) {
            if (companyArray[x] === arrayUniqueCompnies[y]) {
                found = true;
                break;
            }
        }

        if ( ! found) {
            arrayUniqueCompnies.push(companyArray[x]);
        }
    }

    return arrayUniqueCompnies;
}

var arr = [
    "Adobe Systems Incorporated",
    "IBX",
    "IBX",
    "BlackRock, Inc.",
    "BlackRock, Inc.",
];

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

I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images interface, you can define any key as a String.

When accessing a property, the "dot" syntax (images.main) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:

return json.property[0].index

where index was a variable. But it interpreted index, resulting in a:

cannot find property "index" of json.property[0]

And I had to find a workaround using your syntax:

return json.property[0][index]

It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.

E11000 duplicate key error index in mongodb mongoose

Had the same issue I resolved it by removing the unique attribute on the property.

Just find another way to validate or check for unique property values for your schema.

Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?

To get value you can use now different ways:

console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?

Should I use scipy.pi, numpy.pi, or math.pi?

One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:

import math
import numpy
import scipy
import sympy

print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False

Install MySQL on Ubuntu without a password prompt

Use:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"

Change Active Menu Item on Page Scroll?

Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.

jQuery(document).ready(function(jQuery) {            
            var topMenu = jQuery("#top-menu"),
                offset = 40,
                topMenuHeight = topMenu.outerHeight()+offset,
                // All list items
                menuItems =  topMenu.find('a[href*="#"]'),
                // Anchors corresponding to menu items
                scrollItems = menuItems.map(function(){
                  var href = jQuery(this).attr("href"),
                  id = href.substring(href.indexOf('#')),
                  item = jQuery(id);
                  //console.log(item)
                  if (item.length) { return item; }
                });

            // so we can get a fancy scroll animation
            menuItems.click(function(e){
              var href = jQuery(this).attr("href"),
                id = href.substring(href.indexOf('#'));
                  offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
              jQuery('html, body').stop().animate({ 
                  scrollTop: offsetTop
              }, 300);
              e.preventDefault();
            });

            // Bind to scroll
            jQuery(window).scroll(function(){
               // Get container scroll position
               var fromTop = jQuery(this).scrollTop()+topMenuHeight;

               // Get id of current scroll item
               var cur = scrollItems.map(function(){
                 if (jQuery(this).offset().top < fromTop)
                   return this;
               });

               // Get the id of the current element
               cur = cur[cur.length-1];
               var id = cur && cur.length ? cur[0].id : "";               

               menuItems.parent().removeClass("active");
               if(id){
                    menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
               }

            })
        })

Basically i replaced

menuItems = topMenu.find("a"),

by

menuItems =  topMenu.find('a[href*="#"]'),

To match all links with anchor somewhere, and changed all that what was necessary to make it work with this

See it in action on jsfiddle

AngularJs ReferenceError: angular is not defined

I think this will happen if you'll use 'async defer' for (the file that contains the filter) while working with angularjs:

<script src="js/filter.js" type="text/javascript" async defer></script>

if you do, just remove 'async defer'.

Git: How to check if a local repo is up to date?

You'll need to issue two commands:

  1. git fetch origin
  2. git status

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

You have declared your Class as:

@Table( name = "foobar" )
public class FooBar {

You need to write the Class Name for the search.
from FooBar

Create a variable name with "paste" in R?

In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.

output=NULL
for(i in 1:8){
   Tax=eval(as.symbol(paste("Tax",i,sep="")))
   L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
   L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
   h=hist(L_Data,breaks=breaks,plot=FALSE)
   output=cbind(output,h$counts)
}

A Java collection of value pairs? (tuples?)

First Thing on my mind when talking about key/value pairs is the Properties Class where you can save and load items to a stream/file.

removing table border

Try giving your table an ID and then using !important to set border to none in CSS. If JavaScript is tampering with your table then that should get around it.

<table id="mytable"
...

table#mytable,
table#mytable td
{
    border: none !important;
}

"installation of package 'FILE_PATH' had non-zero exit status" in R

Try use this:

    apt-get install r-base-dev

It will be help. After then I could makeinstall.packages('//package_name')

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Android: ScrollView force to bottom

Using there is another cool way to do this with Kotlin coroutines. The advantage of using a coroutine opposed to a Handler with a runnable (post/postDelayed) is that it does not fire up an expensive thread to execute a delayed action.

launch(UI){
    delay(300)
    scrollView.fullScroll(View.FOCUS_DOWN)
}

It is important to specify the coroutine's HandlerContext as UI otherwise the delayed action might not be called from the UI thread.

Subprocess changing directory

subprocess.call and other methods in the subprocess module have a cwd parameter.

This parameter determines the working directory where you want to execute your process.

So you can do something like this:

subprocess.call('ls', shell=True, cwd='path/to/wanted/dir/')

Check out docs subprocess.popen-constructor

Regular expression [Any number]

You can use the following function to find the biggest [number] in any string.

It returns the value of the biggest [number] as an Integer.

var biggestNumber = function(str) {
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;

    while ((match = pattern.exec(str)) !== null) {
        if (match.index === pattern.lastIndex) {
            pattern.lastIndex++;
        }
        match[1] = parseInt(match[1]);
        if(biggest < match[1]) {
            biggest = match[1];
        }
    }
    return biggest;
}

DEMO

The following demo calculates the biggest number in your textarea every time you click the button.

It allows you to play around with the textarea and re-test the function with a different text.

_x000D_
_x000D_
var biggestNumber = function(str) {_x000D_
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
    while ((match = pattern.exec(str)) !== null) {_x000D_
        if (match.index === pattern.lastIndex) {_x000D_
            pattern.lastIndex++;_x000D_
        }_x000D_
        match[1] = parseInt(match[1]);_x000D_
        if(biggest < match[1]) {_x000D_
            biggest = match[1];_x000D_
        }_x000D_
    }_x000D_
    return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
    alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
    <textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
    </textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
   <button id="myButton">Try me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

Alphabet range in Python

Here is a simple letter-range implementation:

Code

def letter_range(start, stop="{", step=1):
    """Yield a range of lowercase letters.""" 
    for ord_ in range(ord(start.lower()), ord(stop.lower()), step):
        yield chr(ord_)

Demo

list(letter_range("a", "f"))
# ['a', 'b', 'c', 'd', 'e']

list(letter_range("a", "f", step=2))
# ['a', 'c', 'e']

How to write console output to a txt file

PrintWriter out = null;
try {
    out = new PrintWriter(new FileWriter("C:\\testing.txt"));
    } catch (IOException e) {
            e.printStackTrace();
    }
out.println("output");
out.close();

I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.

jsonify a SQLAlchemy result set in Flask

Ok, I've been working on this for a few hours, and I've developed what I believe to be the most pythonic solution yet. The following code snippets are python3 but shouldn't be too horribly painful to backport if you need.

The first thing we're gonna do is start with a mixin that makes your db models act kinda like dicts:

from sqlalchemy.inspection import inspect

class ModelMixin:
    """Provide dict-like interface to db.Model subclasses."""

    def __getitem__(self, key):
        """Expose object attributes like dict values."""
        return getattr(self, key)

    def keys(self):
        """Identify what db columns we have."""
        return inspect(self).attrs.keys()

Now we're going to define our model, inheriting the mixin:

class MyModel(db.Model, ModelMixin):
    id = db.Column(db.Integer, primary_key=True)
    foo = db.Column(...)
    bar = db.Column(...)
    # etc ...

That's all it takes to be able to pass an instance of MyModel() to dict() and get a real live dict instance out of it, which gets us quite a long way towards making jsonify() understand it. Next, we need to extend JSONEncoder to get us the rest of the way:

from flask.json import JSONEncoder
from contextlib import suppress

class MyJSONEncoder(JSONEncoder):
    def default(self, obj):
        # Optional: convert datetime objects to ISO format
        with suppress(AttributeError):
            return obj.isoformat()
        return dict(obj)

app.json_encoder = MyJSONEncoder

Bonus points: if your model contains computed fields (that is, you want your JSON output to contain fields that aren't actually stored in the database), that's easy too. Just define your computed fields as @propertys, and extend the keys() method like so:

class MyModel(db.Model, ModelMixin):
    id = db.Column(db.Integer, primary_key=True)
    foo = db.Column(...)
    bar = db.Column(...)

    @property
    def computed_field(self):
        return 'this value did not come from the db'

    def keys(self):
        return super().keys() + ['computed_field']

Now it's trivial to jsonify:

@app.route('/whatever', methods=['GET'])
def whatever():
    return jsonify(dict(results=MyModel.query.all()))

How do I convert datetime.timedelta to minutes, hours in Python?

datetime.timedelta(hours=1, minutes=10)
#python 2.7

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

How do I find the PublicKeyToken for a particular dll?

Using PowerShell, you can execute this statement:

([system.reflection.assembly]::loadfile("C:\..\Full_Path\..\MyDLL.dll")).FullName

The output will provide the Version, Culture and PublicKeyToken as shown below:

MyDLL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

Alternative to itoa() for converting integer to string C++?

Note that all of the stringstream methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...

See here for more. Convert a number to a string with specified length in C++

Link entire table row?

Also it depends if you need to use a table element or not. You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    </span>
    <span class="td">
      cell 2
    </span>
  </a>
</div>

css:

.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}

Do I really need to encode '&' as '&amp;'?

Yes, you should try to serve valid code if possible.

Most browsers will silently correct this error, but there is a problem with relying on the error handling in the browsers. There is no standard for how to handle incorrect code, so it's up to each browser vendor to try to figure out what to do with each error, and the results may vary.

Some examples where browsers are likely to react differently is if you put elements inside a table but outside the table cells, or if you nest links inside each other.

For your specific example it's not likely to cause any problems, but error correction in the browser might for example cause the browser to change from standards compliant mode into quirks mode, which could make your layout break down completely.

So, you should correct errors like this in the code, if not for anything else so to keep the error list in the validator short, so that you can spot more serious problems.

How to use if-else option in JSTL

In addition with skaffman answer, simple if-else you can use ternary operator like this

<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>

Querying data by joining two tables in two database on different servers

A join of two tables is best done by a DBMS, so it should be done that way. You could mirror the smaller table or subset of it on one of the databases and then join them. One might get tempted of doing this on an ETL server like informatica but I guess its not advisable if the tables are huge.

Change Placeholder Text using jQuery

$(document).ready(function(){ 
     $("input[type=search]").attr("placeholder","this is a test");
});

Rails ActiveRecord date between

Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])

Get installed applications in a system

My requirement is to check if specific software is installed in my system. This solution works as expected. It might help you. I used a windows application in c# with visual studio 2015.

 private void Form1_Load(object sender, EventArgs e)
        {

            object line;
            string softwareinstallpath = string.Empty;
            string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
            {
                using (var key = baseKey.OpenSubKey(registry_key))
                {
                    foreach (string subkey_name in key.GetSubKeyNames())
                    {
                        using (var subKey = key.OpenSubKey(subkey_name))
                        {
                            line = subKey.GetValue("DisplayName");
                            if (line != null && (line.ToString().ToUpper().Contains("SPARK")))
                            {

                                softwareinstallpath = subKey.GetValue("InstallLocation").ToString();
                                listBox1.Items.Add(subKey.GetValue("InstallLocation"));
                                break;
                            }
                        }
                    }
                }
            }

            if(softwareinstallpath.Equals(string.Empty))
            {
                MessageBox.Show("The Mirth connect software not installed in this system.")
            }



            string targetPath = softwareinstallpath + @"\custom-lib\";
            string[] files = System.IO.Directory.GetFiles(@"D:\BaseFiles");

            // Copy the files and overwrite destination files if they already exist. 
            foreach (var item in files)
            {
                string srcfilepath = item;
                string fileName = System.IO.Path.GetFileName(item);
                System.IO.File.Copy(srcfilepath, targetPath + fileName, true);
            }
            return;

        }

How to check if array element is null to avoid NullPointerException in Java

The example code does not throw an NPE. (there also should not be a ';' behind the i++)

How can I query a value in SQL Server XML column

In case you want to find other node besides "Alpha", the query should be something like this:

select Roles from MyTable where Roles.exist('(/*:root/*:role[contains(.,"Beta")])') = 1

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

Install the latest version of eclipse(). It would have the option to add Tomcat 8.5.

Single huge .css file vs. multiple smaller specific .css files?

You can just use one css file for performance and then comment out sections like this:

/******** Header ************/
//some css here

/******* End Header *********/


/******** Footer ************/
//some css here

/******* End Footer *********/

etc

Can I run multiple programs in a Docker container?

You can run 2 processes in foreground by using wait. Just make a bash script with the following content. Eg start.sh:

# runs 2 commands simultaneously:

mongod & # your first application
P1=$!
python script.py & # your second application
P2=$!
wait $P1 $P2

In your Dockerfile, start it with

CMD bash start.sh

Eliminating duplicate values based on only one column of the table

This is where the window function row_number() comes in handy:

SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
     (select h.*, row_number() over (partition by siteName order by date desc) as seqnum
      from history h
     ) h
    ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date

Using CMake to generate Visual Studio C++ project files

CMake can generate really nice Visual Studio .projs/.slns, but there is always the problem with the need to modify the .cmake files rather than .proj/.sln. As it is now, we are dealing with it as follows:

  1. All source files go to /src and files visible in Visual Studio are just "links" to them defined in .filter.
  2. Programmer adds/deletes files remembering to work on the defined /src directory, not the default project's one.
  3. When he's done, he run a script that "refreshes" the respective .cmake files.
  4. He checks if the code can be built in the recreated environment.
  5. He commits the code.

At first we were a little afraid of how it will turn out, but the workflow works really well and with nice diff visible before each commit, everyone can easily see if his changes were correctly mapped in .cmake files.

One more important thing to know about is the lack of support (afaik) for "Solution Configurations" in CMake. As it stands, you have to generate two directories with projects/solutions - one for each build type (debug, release, etc.). There is no direct support for more sophisticated features - in other words: switching between configurations won't give you what you might expect.

keycloak Invalid parameter: redirect_uri

For me, I had a missing trailing slash / in the value for Valid Redirect URIs

socket.emit() vs. socket.send()

https://socket.io/docs/client-api/#socket-send-args-ack

socket.send // Sends a message event

socket.emit(eventName[, ...args][, ack]) // you can custom eventName

How do I get total physical memory size using PowerShell without WMI?

I'd like to make a note of this for people referencing in the future.

I wanted to avoid WMI because it uses a DCOM protocol, requiring the remote computer to have the necessary permissions, which could only be setup manually on that remote computer.

So, I wanted to avoid using WMI, but using get-counter often times didn't have the performance counter I wanted.

The solution I used was the Common Information Model (CIM). Unlike WMI, CIM doesn't use DCOM by default. Instead of returning WMI objects, CIM cmdlets return PowerShell objects.

CIM uses the Ws-MAN protocol by default, but it only works with computers that have access to Ws-Man 3.0 or later. So, earlier versions of PowerShell wouldn't be able to issue CIM cmdlets.

The cmdlet I ended up using to get total physical memory size was:

get-ciminstance -class "cim_physicalmemory" | % {$_.Capacity}

Java check if boolean is null

In Java, null only applies to object references; since boolean is a primitive type, it cannot be assigned null.

It's hard to get context from your example, but I'm guessing that if hideInNav is not in the object returned by getProperties(), the (default value?) you've indicated will be false. I suspect this is the bug that you're seeing, as false is not equal to null, so hideNavigation is getting the empty string?

You might get some better answers with a bit more context to your code sample.

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

Hide Show content-list with only CSS, no javascript used

There is 3 rapid examples with pure CSS and without javascript where the content appears "on click", with a "maintained click" and a third "onhover" (all only tested in Chrome). Sorry for the up of this post but this question are the first seo result and maybe my contribution can help beginner like me

I think (not tested) but the advantage of argument "content" that you can add great icon like from Font Awesome (its \f-Code) or an hexadecimal icon in place of the text "Hide" and "Show" to internationalize the trick.

example link http://jsfiddle.net/MonkeyTime/h3E9p/2/

<style>
label { position: absolute; top:0; left:0}

input#show, input#hide {
    display:none;
}

span#content {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}

input#show:checked ~ .show:before {
    content: ""
}
input#show:checked ~ .hide:before {
    content: "Hide"
}

input#hide:checked ~ .hide:before {
    content: ""
}
input#hide:checked ~ .show:before {
    content: "Show"
}
input#show:checked ~ span#content {
    opacity: 1;
    font-size: 100%;
    height: auto;
}
input#hide:checked ~ span#content {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}
</style>
<input type="radio" id="show" name="group">   
<input type="radio" id="hide" name="group" checked>
<label for="hide" class="hide"></label>
<label for="show" class="show"></label>
<span id="content">Lorem iupsum dolor si amet</span>


<style>
#show1 { position: absolute; top:20px; left:0}
#content1 {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}
#show1:before {
    content: "Show"
}
#show1:active.show1:before {
    content: "Hide"
}
#show1:active ~ span#content1 {
    opacity: 1;
    font-size: 100%;
    height: auto;
}
</style>

<div id="show1" class="show1"></div>
<span id="content1">Ipsum Lorem</span>


<style>
#show2 { position: absolute; top:40px; left:0}
#content2 {
    display: block;
    -webkit-transition: opacity 1s ease-out;
    transition: opacity 1s ease-out;
    opacity: 0; 
    height: 0;
    font-size: 0;
    overflow: hidden;
}
#show2:before {
    content: "Show"
}
#show2:hover.show2:before {
    content: "Hide"
}
#show2:hover ~ span#content2 {
    opacity: 1;
    font-size: 100%;
    height: auto;
}

/* extra */
#content, #content1, #content2 {
    float: left;
    margin: 100px auto;
}
</style>

<div id="show2" class="show2"></div>
<span id="content2">Lorem Ipsum</span>

How to determine when Fragment becomes visible in ViewPager

I figured out that onCreateOptionsMenu and onPrepareOptionsMenu methods called only in the case of the fragment really visible. I could not found any method which behaves like these, also I tried OnPageChangeListener but it did not work for the situations, for example, I need a variable initialized in onCreate method.

So these two methods can be used for this problem as a workaround, specifically for little and short jobs.

I think, this is the better solution but not the best. I will use this but wait for better solution at the same time.

Regards.

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

Here is the code for Right click on a webelement.

Actions actions = new Actions(driver);    
Action action=actions.contextClick(WebElement).build(); //pass WebElement as an argument
            action.perform();

Can I use conditional statements with EJS templates (in JMVC)?

You can also use else if syntax:

<% if (x === 1) { %>
    <p>Hello world!</p>
<% } else if (x === 2) { %>
    <p>Hi earth!</p>
<% } else { %>
    <p>Hey terra!</p>
<% } %>

iOS application: how to clear notifications?

Most likely because Notification Center is a relatively new feature, Apple didn't necessarily want to push a whole new paradigm for clearing notifications. So instead, they multi-purposed [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0]; to clear said notifications. It might seem a bit weird, and Apple might provide a more intuitive way to do this in the future, but for the time being it's the official way.

Myself, I use this snippet:

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];

which never fails to clear all of the app's notifications from Notification Center.

How to sum up elements of a C++ vector?

The easiest way is to use std:accumulate of a vector<int> A:

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);

How to _really_ programmatically change primary and accent color in Android Lollipop?

You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.

Let's say you have these style definitions:

<style name="DefaultTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/md_lime_500</item>
    <item name="colorPrimaryDark">@color/md_lime_700</item>
    <item name="colorAccent">@color/md_amber_A400</item>
</style>

<style name="OverlayPrimaryColorRed">
    <item name="colorPrimary">@color/md_red_500</item>
    <item name="colorPrimaryDark">@color/md_red_700</item>
</style>

<style name="OverlayPrimaryColorGreen">
    <item name="colorPrimary">@color/md_green_500</item>
    <item name="colorPrimaryDark">@color/md_green_700</item>
</style>

<style name="OverlayPrimaryColorBlue">
    <item name="colorPrimary">@color/md_blue_500</item>
    <item name="colorPrimaryDark">@color/md_blue_700</item>
</style>

Now you can patch your theme at runtime like so:

getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);

The method applyStylehas to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView in your activity.

Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.

What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent for example. Now you can combine different values for primary color and accent color almost arbitrarily.

You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed implicitly inherits all styles defined in AppTheme and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red and define Overlay as an empty style.

Importing variables from another file?

script1.py

title="Hello world"

script2.py is where we using script1 variable

Method 1:

import script1
print(script1.title)

Method 2:

from script1 import title
print(title)

javascript windows alert with redirect function

Alert will block the program flow so you can just write the following.

echo ("<script LANGUAGE='JavaScript'>
    window.alert('Succesfully Updated');
    window.location.href='http://someplace.com';
    </script>");

git status shows modifications, git checkout -- <file> doesn't remove them

Having consistent line endings is a good thing. For example it will not trigger unnecessary merges, albeit trivial. I have seen Visual Studio create files with mixed line endings.

Also some programs like bash (on linux) do require that .sh files are LF terminated.

To make sure this happens you can use gitattributes. It works on repository level no matter what the value of autcrlf is.

For example you can have .gitattributes like this: * text=auto

You can also be more specific per file type/extension if it did matter in your case.

Then autocrlf can convert line endings for Windows programs locally.

On a mixed C#/C++/Java/Ruby/R, Windows/Linux project this is working well. No issues so far.

Access index of last element in data frame

The former answer is now superseded by .iloc:

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58

The shortest way I can think of uses .iget():

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58

Alternatively:

>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58

There's also .first_valid_index() and .last_valid_index(), but depending on whether or not you want to rule out NaNs they might not be what you want.

Remember that df.ix[0] doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0] would produce

>>> df.ix[0]
Traceback (most recent call last):
  File "<ipython-input-489-494245247e87>", line 1, in <module>
    df.ix[0]
[...]
KeyError: 0

How to add Drop-Down list (<select>) programmatically?

This will work (pure JS, appending to a div of id myDiv):

Demo: http://jsfiddle.net/4pwvg/

_x000D_
_x000D_
var myParent = document.body;_x000D_
_x000D_
//Create array of options to be added_x000D_
var array = ["Volvo","Saab","Mercades","Audi"];_x000D_
_x000D_
//Create and append select list_x000D_
var selectList = document.createElement("select");_x000D_
selectList.id = "mySelect";_x000D_
myParent.appendChild(selectList);_x000D_
_x000D_
//Create and append the options_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
    var option = document.createElement("option");_x000D_
    option.value = array[i];_x000D_
    option.text = array[i];_x000D_
    selectList.appendChild(option);_x000D_
}
_x000D_
_x000D_
_x000D_

Vue equivalent of setTimeout?

use this.animationStop, not use this.animationStop ( )

animationRun(){
    this.sliderClass.anim = true;
    setTimeout(this.animationStop, 500);
},

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

My problem solved with these :

1- Add this to your head :

<base href="/" />

2- Use this in app.config

$locationProvider.html5Mode(true);

How to programmatically tell if a Bluetooth device is connected?

Add bluetooth permission to your AndroidManifest,

<uses-permission android:name="android.permission.BLUETOOTH" />

Then use intent filters to listen to the ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, and ACTION_ACL_DISCONNECTED broadcasts:

public void onCreate() {
    ...
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter);
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           ... //Device found
        }
        else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
           ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           ... //Done searching
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
           ... //Device is about to disconnect
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
           ... //Device has disconnected
        }           
    }
};

A few notes:

  • There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to QUERY, instead it allows you to listen to CHANGES.
  • A hoaky work around to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
  • Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How do I repair an InnoDB table?

stop your application...or stop your slave so no new rows are being added

create table <new table> like <old table>;
insert <new table> select * from <old table>;
truncate table  <old table>;
insert <old table> select * from <new table>;

restart your server or slave

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

Add and Remove Views in Android Dynamically?

//MainActivity :





 package com.edittext.demo;
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.Toast;

    public class MainActivity extends Activity {

        private EditText edtText;
        private LinearLayout LinearMain;
        private Button btnAdd, btnClear;
        private int no;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            edtText = (EditText)findViewById(R.id.edtMain);
            btnAdd = (Button)findViewById(R.id.btnAdd);
            btnClear = (Button)findViewById(R.id.btnClear);
            LinearMain = (LinearLayout)findViewById(R.id.LinearMain);

            btnAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
                        no = Integer.parseInt(edtText.getText().toString());
                        CreateEdittext();
                    }else {
                        Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnClear.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    LinearMain.removeAllViews();
                    edtText.setText("");
                }
            });

            /*edtText.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,int after) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                }
            });*/

        }

        protected void CreateEdittext() {
            final EditText[] text = new EditText[no];
            final Button[] add = new Button[no];
            final LinearLayout[] LinearChild = new LinearLayout[no];
            LinearMain.removeAllViews();

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

                View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
                text[i] = (EditText)view.findViewById(R.id.edtText);
                text[i].setId(i);
                text[i].setTag(""+i);

                add[i] = (Button)view.findViewById(R.id.btnAdd);
                add[i].setId(i);
                add[i].setTag(""+i);

                LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
                LinearChild[i].setId(i);
                LinearChild[i].setTag(""+i);

                LinearMain.addView(view);

                add[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
                        int a = Integer.parseInt(text[v.getId()].getText().toString());
                        LinearChild[v.getId()].removeAllViews();
                        for (int k = 0; k < a; k++){

                            EditText text = (EditText) new EditText(MainActivity.this);
                            text.setId(k);
                            text.setTag(""+k);

                            LinearChild[v.getId()].addView(text);
                        }
                    }
                });
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

// Now add xml main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edtMain"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Enter value" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Add" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text="Clear" />
</LinearLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp" >

    <LinearLayout
        android:id="@+id/LinearMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

// now add view xml file..

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/edtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:ems="10" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="Add" />
</LinearLayout>

<LinearLayout
    android:id="@+id/child_linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp"
    android:orientation="vertical" >
</LinearLayout>

Check if decimal value is null

you can use this code

if (DecimalVariable.Equals(null))  
{
   //something statements
}

Counting inversions in an array

Most answers are based on MergeSort but it isn't the only way to solve this is in O(nlogn)

I'll discuss a few approaches.

  1. Use a Balanced Binary Search Tree

    • Augment your tree to store frequencies for duplicate elements.
    • The idea is to keep counting greater nodes when the tree is traversed from root to a leaf for insertion.

Something like this.

Node *insert(Node* root, int data, int& count){
    if(!root) return new Node(data);
    if(root->data == data){
        root->freq++;
        count += getSize(root->right);
    }
    else if(root->data > data){
        count += getSize(root->right) + root->freq;
        root->left = insert(root->left, data, count);
    }
    else root->right = insert(root->right, data, count);
    return balance(root);
}

int getCount(int *a, int n){
    int c = 0;
    Node *root = NULL;
    for(auto i=0; i<n; i++) root = insert(root, a[i], c);
    return c;
}
  1. Use a Binary Indexed Tree
    • Create a summation BIT.
    • Loop from the end and start finding the count of greater elements.
int getInversions(int[] a) {
    int n = a.length, inversions = 0;
    int[] bit = new int[n+1];
    compress(a);
    BIT b = new BIT();
    for (int i=n-1; i>=0; i--) {
         inversions += b.getSum(bit, a[i] - 1);
         b.update(bit, n, a[i], 1);
     }
     return inversions;
}
  1. Use a Segment Tree
    • Create a summation segment Tree.
    • Loop from the end of the array and query between [0, a[i]-1] and update a[i] with 1
int getInversions(int *a, int n) {
    int N = n + 1, c = 0;
    compress(a, n);
    int tree[N<<1] = {0};
    for (int i=n-1; i>=0; i--) {
        c+= query(tree, N, 0, a[i] - 1);
        update(tree, N, a[i], 1);
    }
    return c;
}

Also, when using BIT or Segment-Tree a good idea is to do Coordinate compression

void compress(int *a, int n) {
    int temp[n];
    for (int i=0; i<n; i++) temp[i] = a[i];
    sort(temp, temp+n);
    for (int i=0; i<n; i++) a[i] = lower_bound(temp, temp+n, a[i]) - temp + 1;
}

How to set up ES cluster?

I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration discovery.zen.ping.unicast.hosts needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.

Node 1

cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
http.port : 9200
tcp.port : 9300
discovery.zen.ping.multicast.enabled: false
# I think unicast.host on master is redundant.
discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2

cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
http.port : 9201
tcp.port : 9301
discovery.zen.ping.multicast.enabled: false
# The port number of Node 1
discovery.zen.ping.unicast.hosts: ["node1.example.com:9300"]

How to get some values from a JSON string in C#?

Following code is working for me.

Usings:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

Code:

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}

jquery: get id from class selector

Doh.. If I get you right, it should be as simple as:

_x000D_
_x000D_
$('.test').click(function() {_x000D_
  console.log(this.id);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<a href="#" class="test" id="test_1">Some text</a>_x000D_
<a href="#" class="test" id="test_2">Some text</a>_x000D_
<a href="#" class="test" id="test_3">Some text</a>
_x000D_
_x000D_
_x000D_

You can just access the id property over the underlaying dom node, within the event handler.

TypeError: no implicit conversion of Symbol into Integer

You probably meant this:

require 'active_support/core_ext' # for titleize

myHash = {company_name:"MyCompany", street:"Mainstreet", postcode:"1234", city:"MyCity", free_seats:"3"}

def cleanup string
  string.titleize
end

def format(hash)
  output = {}
  output[:company_name] = cleanup(hash[:company_name])
  output[:street] = cleanup(hash[:street])
  output
end

format(myHash) # => {:company_name=>"My Company", :street=>"Mainstreet"}

Please read documentation on Hash#each

Rename computer and join to domain in one step with PowerShell

I would like to offer the following that worked in an automated capacity for me. It shows the sequence of steps and the relationship between setting the name first, then joining the domain. I use this in a script as an orchestration point for Win2008r2 and win2012r2 via Scalr CMP for EC2 and Openstack cloud instances.

$userid="$DOMAIN\$USERNAME"
$secure_string_pwd = convertto-securestring "SECRET_PASSWORD" -asplaintext -force
$creds = New-Object System.Management.Automation.PSCredential $userid,$secure_string_pwd

Rename-Computer "newhostname" -DomainCredential $creds -Force
WARNING: The changes will take effect after you restart the computer OLDHOSTNAME.

Add-Computer -NewName "newhostname" -DomainName $DOMAIN -Credential $creds \
-OUPath "OU=MYORG,OU=MYSUBORG,DC=THEDOMAIN,DC=Net" -Force
WARNING: The changes will take effect after you restart the computer OLDHOSTNAME.

Restart-Computer

One caveat is to be careful with the credentials, pull them from a key store rather than hard-coded as illustrated here ... but that's a different topic.

Thanks, everyone, for your answers.

One-liner if statements, how to convert this if-else-statement

Since expression is boolean:

return expression;

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

Default value in Doctrine

Here is how I solved it for myself. Below is an Entity example with default value for MySQL. However, this also requires the setup of a constructor in your entity, and for you to set the default value there.

Entity\Example:
  type: entity
  table: example
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    label:
      type: string
      columnDefinition: varchar(255) NOT NULL DEFAULT 'default_value' COMMENT 'This is column comment'

Rails 3.1 and Image Assets

You'll want to change the extension of your css file from .css.scss to .css.scss.erb and do:

background-image:url(<%=asset_path "admin/logo.png"%>);

You may need to do a "hard refresh" to see changes. CMD+SHIFT+R on OSX browsers.

In production, make sure

rm -rf public/assets    
bundle exec rake assets:precompile RAILS_ENV=production

happens upon deployment.

How to delete duplicates on a MySQL table?

this removes duplicates in place, without making a new table

ALTER IGNORE TABLE `table_name` ADD UNIQUE (title, SID)

note: only works well if index fits in memory

Get Max value from List<myType>

Simplest is actually just Age.Max(), you don't need any more code.

jquery $(window).height() is returning the document height

Here's a question and answer for this: Difference between screen.availHeight and window.height()

Has pics too, so you can actually see the differences. Hope this helps.

Basically, $(window).height() give you the maximum height inside of the browser window (viewport), and$(document).height() gives you the height of the document inside of the browser. Most of the time, they will be exactly the same, even with scrollbars.

Keep only date part when using pandas.to_datetime

This worked for me on UTC Timestamp (2020-08-19T09:12:57.945888)

for di, i in enumerate(df['YourColumnName']):
    df['YourColumnName'][di] = pd.Timestamp(i)

Run script with rc.local: script works, but not at boot

I am using CentOS 7.

$ cd  /etc/profile.d

$ vim yourstuffs.sh

Type the following into the yourstuffs.sh script.

type whatever you want here to execute

export LD_LIBRARY_PATH=/usr/local/cuda-7.0/lib64:$LD_LIBRARY_PATH

Save and reboot the OS.

CSS float right not working correctly

You have not used float:left command for your text.

Why is Dictionary preferred over Hashtable in C#?

In .NET, the difference between Dictionary<,> and HashTable is primarily that the former is a generic type, so you get all the benefits of generics in terms of static type checking (and reduced boxing, but this isn't as big as people tend to think in terms of performance - there is a definite memory cost to boxing, though).

Java, How to specify absolute value and square roots

Use the java.lang.Math class, and specifically for absolute value and square root:, the abs() and sqrt() methods.

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

I was getting the same error. I was using Intellij IDEA and I wanted to run Spring boot application. So, solution from my side is as follow.

Go to Run menu -> Run configuration -> Click on Add button from the left panel and select maven -> In parameters add this text -> spring-boot:run

Now press Ok and Run.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

How to create an integer array in Python?

If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:

import array
array.array('i')

See here

If you need to initialize it,

a = array.array('i',(0 for i in range(0,10)))

How to count TRUE values in a logical vector

Another option is to use summary function. It gives a summary of the Ts, Fs and NAs.

> summary(hival)
   Mode   FALSE    TRUE    NA's 
logical    4367      53    2076 
> 

JQuery create new select option

What about

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

You would do that when the responsibility of creating/updating the referenced column isn't in the current entity, but in another entity.

Update index after sorting data-frame

Since pandas 1.0.0 df.sort_values has a new parameter ignore_index which does exactly what you need:

In [1]: df2 = df.sort_values(by=['x','y'],ignore_index=True)

In [2]: df2
Out[2]:
   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

How to dynamically create generic C# object using reflection?

I know this question is resolved but, for the benefit of anyone else reading it; if you have all of the types involved as strings, you could do this as a one liner:

IYourInterface o = (Activator.CreateInstance(Type.GetType("Namespace.TaskA`1[OtherNamespace.TypeParam]") as IYourInterface);

Whenever I've done this kind of thing, I've had an interface which I wanted subsequent code to utilise, so I've casted the created instance to an interface.

click() event is calling twice in jquery

It means your code included the jquery script twice. But try this:

$("#btn").unbind("click").click(function(){

//your code

});

How can I declare dynamic String array in Java

You want to use a Set or List implementation (e.g. HashSet, TreeSet, etc, or ArrayList, LinkedList, etc..), since Java does not have dynamically sized arrays.

List<String> zoom = new ArrayList<>();
zoom.add("String 1");
zoom.add("String 2");

for (String z : zoom) {
    System.err.println(z);
}

Edit: Here is a more succinct way to initialize your List with an arbitrary number of values using varargs:

List<String> zoom = Arrays.asList("String 1", "String 2", "String n");

How to round the minute of a datetime object

A straightforward approach:

def round_time(dt, round_to_seconds=60):
    """Round a datetime object to any number of seconds
    dt: datetime.datetime object
    round_to_seconds: closest number of seconds for rounding, Default 1 minute.
    """
    rounded_epoch = round(dt.timestamp() / round_to_seconds) * round_to_seconds
    rounded_dt = datetime.datetime.fromtimestamp(rounded_epoch).astimezone(dt.tzinfo)
    return rounded_dt

Entity Framework and SQL Server View

This method works well for me. I use ISNULL() for the primary key field, and COALESCE() if the field should not be the primary key, but should also have a non-nullable value. This example yields ID field with a non-nullable primary key. The other fields are not keys, and have (None) as their Nullable attribute.

SELECT      
ISNULL(P.ID, - 1) AS ID,  
COALESCE (P.PurchaseAgent, U.[User Nickname]) AS PurchaseAgent,  
COALESCE (P.PurchaseAuthority, 0) AS PurchaseAuthority,  
COALESCE (P.AgencyCode, '') AS AgencyCode,  
COALESCE (P.UserID, U.ID) AS UserID,  
COALESCE (P.AssignPOs, 'false') AS AssignPOs,  
COALESCE (P.AuthString, '') AS AuthString,  
COALESCE (P.AssignVendors, 'false') AS AssignVendors 
FROM Users AS U  
INNER JOIN Users AS AU ON U.Login = AU.UserName  
LEFT OUTER JOIN PurchaseAgents AS P ON U.ID = P.UserID

if you really don't have a primary key, you can spoof one by using ROW_NUMBER to generate a pseudo-key that is ignored by your code. For example:

SELECT
ROW_NUMBER() OVER(ORDER BY A,B) AS Id,
A, B
FROM SOMETABLE

Compute elapsed time

Hope this will help:

<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
    <head>
        <title>compute elapsed time in JavaScript</title>

        <script type="text/javascript">

            function display_c (start) {
                window.start = parseFloat(start);
                var end = 0 // change this to stop the counter at a higher value
                var refresh = 1000; // Refresh rate in milli seconds
                if( window.start >= end ) {
                    mytime = setTimeout( 'display_ct()',refresh )
                } else {
                    alert("Time Over ");
                }
            }

            function display_ct () {
                // Calculate the number of days left
                var days = Math.floor(window.start / 86400);
                // After deducting the days calculate the number of hours left
                var hours = Math.floor((window.start - (days * 86400 ))/3600)
                // After days and hours , how many minutes are left
                var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
                // Finally how many seconds left after removing days, hours and minutes.
                var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))

                var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";

                document.getElementById('ct').innerHTML = x;
                window.start = window.start - 1;

                tt = display_c(window.start);
            }

            function stop() {
                clearTimeout(mytime);
            }

        </script>

    </head>

    <body>

        <input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
        <span id='ct' style="background-color: #FFFF00"></span>

    </body>
</html>

Is there an XSL "contains" directive?

<xsl:if test="not contains(hhref,'1234')">

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

What is the cleanest way to disable CSS transition effects temporarily?

Add an additional CSS class that blocks the transition, and then remove it to return to the previous state. This make both CSS and JQuery code short, simple and well understandable.

CSS:

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  -ms-transition: none !important;
  transition: none !important;
}

!important was added to be sure that this rule will have more "weight", because ID is normally more specific than class.

JQuery:

$('#elem').addClass('notransition'); // to remove transition
$('#elem').removeClass('notransition'); // to return to previouse transition

++i or i++ in for loops ??

For integers, there is no difference between pre- and post-increment.

If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.

Facebook Graph API error code list

I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):

/**
  * (Date: 30.01.2013)
  *
  * case 1: - "An error occured while creating the share (publishing to wall)"
  *         - "An unknown error has occurred."
  * case 2:    "An unexpected error has occurred. Please retry your request later."
  * case 3:    App must be on whitelist        
  * case 4:    Application request limit reached
  * case 5:    Unauthorized source IP address        
  * case 200:  Requires extended permissions
  * case 240:  Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
  * case 1500: The url you supplied is invalid
  * case 200:
  * case 210:  - Subject must be a page
  *            - User not visible
  */

 /**
  * Error Code 100 several issus:
  * - "Specifying multiple ids with a post method is not supported" (http status 400)
  * - "Error finding the requested story" but it is available via GET
  * - "Invalid post_id"
  * - "Code was invalid or expired. Session is invalid."
  * 
  * Error Code 2: 
  * - Service temporarily unavailable
  */

jQuery .on('change', function() {} not triggering for dynamically created inputs

Use this

$('body').on('change', '#id', function() {
  // Action goes here.
});

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Microsoft itself posted a KB article about this, and that article has a service pack that they claim fixes the problem. See below.

http://support.microsoft.com/kb/959417/

It took a while for the associated update to install itself, but once it did, I was able to run the Visual Studio setup successfully from the Add/Remove Programs control panel.

How to send a simple email from a Windows batch file?

If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

How to get value of checked item from CheckedListBox?

You can iterate over the CheckedItems property:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
    MyCompanyClass company = (MyCompanyClass)itemChecked;    
    MessageBox.Show("ID: \"" + company.ID.ToString());
}

http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx

Mean per group in a data.frame

You can also use package plyr, which is somehow more versatile:

library(plyr)

ddply(d, .(Name), summarize,  Rate1=mean(Rate1), Rate2=mean(Rate2))

  Name    Rate1    Rate2
1 Aira 16.33333 47.00000
2  Ben 31.33333 50.33333
3  Cat 44.66667 54.00000

SQL Query - Concatenating Results into One String

If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF trick:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')

The FOR XML PATH('') basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3 etc.) and the STUFF puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.

UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <, > or &, then my current solution will in fact encode those into &lt;, &gt;, and &amp;.

If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.

How to get the category title in a post in Wordpress?

Use get_the_category() like this:

<?php
foreach((get_the_category()) as $category) { 
    echo $category->cat_name . ' '; 
} 
?>

It returns a list because a post can have more than one category.

The documentation also explains how to do this from outside the loop.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

install beautiful soup using pip

The easy method that will work even in corrupted setup environment is :

To download ez_setup.py and run it using command line

python ez_setup.py

output

Extracting in c:\uu\uu\appdata\local\temp\tmpjxvil3 Now working in c:\u\u\appdata\local\temp\tmpjxvil3\setuptools-5.6 Installing Setuptools

run

pip install beautifulsoup4

output

Downloading/unpacking beautifulsoup4 Running setup.py ... egg_info for package Installing collected packages: beautifulsoup4 Running setup.py install for beautifulsoup4 Successfully installed beautifulsoup4 Cleaning up...

Bam ! |Done¬

How to create an Oracle sequence starting with max value from a table?

Based on Ivan Laharnar with less code and simplier:

declare
    lastSeq number;
begin
    SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
    if lastSeq IS NULL then lastSeq := 1; end if;
    execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;

SQL Server: Null VS Empty String

NULL is a non value, like undefined. '' is a empty string with 0 characters.
The value of a string in database depends of your value in your UI, but generally, it's an empty string '' if you specify the parameter in your query or stored procedure.

Rails: Can't verify CSRF token authenticity when making a POST request

If you only want to skip CSRF protection for one or more controller actions (instead of the entire controller), try this

skip_before_action :verify_authenticity_token, only [:webhook, :index, :create]

Where [:webhook, :index, :create] will skip the check for those 3 actions, but you can change to whichever you want to skip