Programs & Examples On #Geodjango

GeoDjango intends to be a world-class geographic Web framework. Its goal is to make it as easy as possible to build GIS Web applications and harness the power of spatially enabled data.

What killed my process and why?

This looks like a good article on the subject: Taming the OOM killer.

The gist is that Linux overcommits memory. When a process asks for more space, Linux will give it that space, even if it is claimed by another process, under the assumption that nobody actually uses all of the memory they ask for. The process will get exclusive use of the memory it has allocated when it actually uses it, not when it asks for it. This makes allocation quick, and might allow you to "cheat" and allocate more memory than you really have. However, once processes start using this memory, Linux might realize that it has been too generous in allocating memory it doesn't have, and will have to kill off a process to free some up. The process to be killed is based on a score taking into account runtime (long-running processes are safer), memory usage (greedy processes are less safe), and a few other factors, including a value you can adjust to make a process less likely to be killed. It's all described in the article in a lot more detail.

Edit: And here is another article that explains pretty well how a process is chosen (annotated with some kernel code examples). The great thing about this is that it includes some commentary on the reasoning behind the various badness() rules.

SVG: text inside rect

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <g>
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
    </linearGradient>
  </defs>
  <rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
  <text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
  </g>
</svg> 

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

When developing using Ubuntu (Xubuntu 12.04.1) I 'HAD' to do the following:

Using

Eclipse Juno (downloaded, not installed via the software centre), Tomcat 7 (downloaded in a custom user directory) also added as a Server in Eclipse, Dynamic Web Project with a 3.0 Servlet, MySQL Server on localhost configured and tested with user and password (make sure to test) MySQL connector driver 5.1.24 jar,

I 'HAD', and I repeat 'HAD', to us the Class.Load("com.mysql.jdbc.Driver") statement along with adding the connector driver.jar to be in the web project lib folder for it to work in this situation.

IMPORTANT!!: after you copy the driver.jar to the lib make sure you refresh your project in Eclipse before running the servlet via Tomcat.

I did try adding the connector driver jar file via the Build Path with and without ClassLoad but it did not work!

Hope this helps anyone starting development with this specific situation: the Java community provides a 'LOT' of documentation but there are so many variables its hard to cover all of them and it makes things very hard on the new guy.

I think if someone could explain why Class.Load is required here (in this situation) it would be beneficial.

Enjoy

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

Could not load file or assembly '' or one of its dependencies

Thanks Riddhi M. Following worked for me.

Remove Temporary Files C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files Close VSTS and Open Again Remove and Add the same DLLs (Note: you add the same matching versions)

Best way to convert list to comma separated string in java

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator

Google Android USB Driver and ADB

Driver for Huawei was not found. So I've been using the universal ADB driver:

  • Download this:
  • Extract ADBDriverInstaller and Run the file. Make sure you have connected your device through USB to your computer.
  • A window is displayed.
  • Click Install.
  • A dialog box will appear. It will ask you to press the Restart button.

Before doing that read this link:

(The above. in brief, says to press Restart button in the dialog box. Select Troubleshoot. Select Advance Option. Select Startup Setting. Press Restart. After system's been restarted, on the appearing screen press 7)

  • When PC has been Restarted, Run the ADBDriverInstaller file again. Select your device from the options. Press install.

And it's done :)

Specify an SSH key for git push for a given domain

Even if the user and host are the same, they can still be distinguished in ~/.ssh/config. For example, if your configuration looks like this:

Host gitolite-as-alice
  HostName git.company.com
  User git
  IdentityFile /home/whoever/.ssh/id_rsa.alice
  IdentitiesOnly yes

Host gitolite-as-bob
  HostName git.company.com
  User git
  IdentityFile /home/whoever/.ssh/id_dsa.bob
  IdentitiesOnly yes

Then you just use gitolite-as-alice and gitolite-as-bob instead of the hostname in your URL:

git remote add alice git@gitolite-as-alice:whatever.git
git remote add bob git@gitolite-as-bob:whatever.git

Note

You want to include the option IdentitiesOnly yes to prevent the use of default ids. Otherwise, if you also have id files matching the default names, they will get tried first because unlike other config options (which abide by "first in wins") the IdentityFile option appends to the list of identities to try. See: https://serverfault.com/questions/450796/how-could-i-stop-ssh-offering-a-wrong-key/450807#450807

Writing File to Temp Folder

System.IO.Path.GetTempPath()

The path specified by the TMP environment variable. The path specified by the TEMP environment variable. The path specified by the USERPROFILE environment variable. The Windows directory.

How can I change the value of the elements in a vector?

You can simply access it like an array i.e. v[i] = v[i] - some_num;

Finding the number of days between two dates

Easy to using date_diff

$from=date_create(date('Y-m-d'));
$to=date_create("2013-03-15");
$diff=date_diff($to,$from);
print_r($diff);
echo $diff->format('%R%a days');

Convert unsigned int to signed int C

I know it's an old question, but it's a good one, so how about this?

unsigned short int x = 65529U;
short int y = *(short int*)&x;

printf("%d\n", y);

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

angular.service vs angular.factory

  angular.service('myService', myServiceFunction);
  angular.factory('myFactory', myFactoryFunction);

I had trouble wrapping my head around this concept until I put it to myself this way:

Service: the function that you write will be new-ed:

  myInjectedService  <----  new myServiceFunction()

Factory: the function (constructor) that you write will be invoked:

  myInjectedFactory  <---  myFactoryFunction()

What you do with that is up to you, but there are some useful patterns...

Such as writing a service function to expose a public API:

function myServiceFunction() {
  this.awesomeApi = function(optional) {
    // calculate some stuff
    return awesomeListOfValues;
  }
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.awesome = myInjectedService.awesomeApi();

Or using a factory function to expose a public API:

function myFactoryFunction() {
  var aPrivateVariable = "yay";

  function hello() {
    return "hello mars " + aPrivateVariable;
  }
  
  // expose a public API
  return {
    hello: hello
  };
}
---------------------------------------------------------------------------------
// Injected in your controller
$scope.hello = myInjectedFactory.hello();

Or using a factory function to return a constructor:

function myFactoryFunction() {
    return function() {
        var a = 2;
        this.a2 = function() {
            return a*2;
        };
    };
}
---------------------------------------------------------------------------------
// Injected in your controller
var myShinyNewObject = new myInjectedFactory();
$scope.four = myShinyNewObject.a2();

Which one to use?...

You can accomplish the same thing with both. However, in some cases the factory gives you a little bit more flexibility to create an injectable with a simpler syntax. That's because while myInjectedService must always be an object, myInjectedFactory can be an object, a function reference, or any value at all. For example, if you wrote a service to create a constructor (as in the last example above), it would have to be instantiated like so:

var myShinyNewObject = new myInjectedService.myFunction()

which is arguably less desirable than this:

var myShinyNewObject = new myInjectedFactory();

(But you should be wary about using this type of pattern in the first place because new-ing objects in your controllers creates hard-to-track dependencies that are difficult to mock for testing. Better to have a service manage a collection of objects for you than use new() wily-nilly.)


One more thing, they are all Singletons...

Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)

How to use passive FTP mode in Windows command prompt?

The quote PASV command is not a command to the ftp.exe program, it is a command to the FTP server requesting a high order port for data transfer. A passive transfer is one in which the FTP data over these high order ports while control is maintained in the lower ports.

The windows ftp.exe program can be used to send the FTP server commands to make a passive data transfer between two FTP servers. A standard windows installation will not, and probably should not, have FTP server service running as an endpoint for passive transfers. So if passive transfers are needed with a standard windows box, a solution other than ftp.exe is necessary as FTPing to localhost as one of the connections won't work in most windows environments.

You can effect a passive FTP transfer between two different hosts (but not two connections on the same host) as follows:

Open up two prompts, use one to ftp.exe connect to your source FTP server and one to ftp.exe connect to your destination FTP server.

Now establish a passive connection between the servers using the raw commands PASV and PORT. The quote PASV command will respond with an IP/port in ellipsis. Use that data for the quote PORT <data> command. Your passive link is now established assuming that firewalls haven't blocked one or more of the four ports (2 for FTP control, 2 for FTP data)

Next start receive of data with the quote STOR <filename> command to the receiving FTP server then send the control command quote RETR <filename> to the source FTP server.

so for me:

client 1
> ftp.exe server1
ftp> quote PASV
227 Entering Passive Mode (10,0,3,1,54,161)

client 2 
> ftp.exe server2
ftp> quote PORT 10,0,3,1,54,54,161
ftp> quote STOR myFile

client 1
ftp> quote RETR myFile

Cavet: I'm connecting to some old FTP servers YMMV

using CASE in the WHERE clause

SELECT *
FROM logs
WHERE pw='correct'
  AND CASE
          WHEN id<800 THEN success=1
          ELSE 1=1
      END
  AND YEAR(TIMESTAMP)=2011

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)

Return HTML content as a string, given URL. Javascript Function

after you get the response just do call this function to append data to your body element

function createDiv(responsetext)
{
    var _body = document.getElementsByTagName('body')[0];
    var _div = document.createElement('div');
    _div.innerHTML = responsetext;
    _body.appendChild(_div);
}

@satya code modified as below

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            createDiv(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();    
}

Event on a disabled input

Instead of disabled, you could consider using readonly. With some extra CSS you can style the input so it looks like an disabled field.

There is actually another problem. The event change only triggers when the element looses focus, which is not logic considering an disabled field. Probably you are pushing data into this field from another call. To make this work you can use the event 'bind'.

$('form').bind('change', 'input', function () {
    console.log('Do your thing.');
});

WPF: Create a dialog / prompt

Great answer of Josh, all credit to him, I slightly modified it to this however:

MyDialog Xaml

    <StackPanel Margin="5,5,5,5">
        <TextBlock Name="TitleTextBox" Margin="0,0,0,10" />
        <TextBox Name="InputTextBox" Padding="3,3,3,3" />
        <Grid Margin="0,10,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button Name="BtnOk" Content="OK" Grid.Column="0" Margin="0,0,5,0" Padding="8" Click="BtnOk_Click" />
            <Button Name="BtnCancel" Content="Cancel" Grid.Column="1" Margin="5,0,0,0" Padding="8" Click="BtnCancel_Click" />
        </Grid>
    </StackPanel>

MyDialog Code Behind

    public MyDialog()
    {
        InitializeComponent();
    }

    public MyDialog(string title,string input)
    {
        InitializeComponent();
        TitleText = title;
        InputText = input;
    }

    public string TitleText
    {
        get { return TitleTextBox.Text; }
        set { TitleTextBox.Text = value; }
    }

    public string InputText
    {
        get { return InputTextBox.Text; }
        set { InputTextBox.Text = value; }
    }

    public bool Canceled { get; set; }

    private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Canceled = true;
        Close();
    }

    private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        Canceled = false;
        Close();
    }

And call it somewhere else

var dialog = new MyDialog("test", "hello");
dialog.Show();
dialog.Closing += (sender,e) =>
{
    var d = sender as MyDialog;
    if(!d.Canceled)
        MessageBox.Show(d.InputText);
}

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Best Way to View Generated Source of Webpage?

I was able to solve a similar issue by logging the results of the ajax call to the console. This was the html returned and I could easily see any issues that it had.

in my .done() function of my ajax call I added console.log(results) so I could see the html in the debugger console.

_x000D_
_x000D_
function GetReversals() {_x000D_
    $("#getReversalsLoadingButton").removeClass("d-none");_x000D_
    $("#getReversalsButton").addClass("d-none");_x000D_
_x000D_
    $.ajax({_x000D_
        url: '/Home/LookupReversals',_x000D_
        data: $("#LookupReversals").serialize(),_x000D_
        type: 'Post',_x000D_
        cache: false_x000D_
    }).done(function (result) {_x000D_
        $('#reversalResults').html(result);_x000D_
        console.log(result);_x000D_
    }).fail(function (jqXHR, textStatus, errorThrown) {_x000D_
        //alert("There was a problem getting results.  Please try again. " + jqXHR.responseText + " | " + jqXHR.statusText);_x000D_
        $("#reversalResults").html("<div class='text-danger'>" + jqXHR.responseText + "</div>");_x000D_
    }).always(function () {_x000D_
        $("#getReversalsLoadingButton").addClass("d-none");_x000D_
        $("#getReversalsButton").removeClass("d-none");_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

displaying a string on the textview when clicking a button in android

public void onCreate(Bundle savedInstanceState) 
{
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);

    mybtn .setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            txtView.SetText("Your Message");
        }
    });
}

Save Screen (program) output to a file

Here's a trick: wrap it in sh -c!

screen sh -c './some-script 2>&1 | tee mylog.log'

Where 2>&1 redirects stderr to stdout so tee can catch and log error messages.

Figure out size of UILabel based on String in Swift

In Swift 5:

label.textRect(forBounds: label.bounds, limitedToNumberOfLines: 1)

btw, the value of limitedToNumberOfLines depends on your label's text lines you want.

Identify if a string is a number

You can use TryParse to determine if the string can be parsed into an integer.

int i;
bool bNum = int.TryParse(str, out i);

The boolean will tell you if it worked or not.

Doctrine 2 ArrayCollection filter method

Your use case would be :

    $ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
                        return $user->getActive() === TRUE;
                    });

if you add ->first() you'll get only the first entry returned, which is not what you want.

@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:

    $member->getComments()->filter( function($entry) use ($idsToFilter) {
        return in_array($entry->getId(), $idsToFilter);
    });

How can I check if a MySQL table exists with PHP?

The cleanest way to achieve this in PHP is to simply use DESCRIBE statement.

if ( mysql_query( "DESCRIBE `my_table`" ) ) {
    // my_table exists
}

I'm not sure why others are posting complicated queries for a such a straight forward problem.

Update

Using PDO

// assuming you have already setup $pdo
$sh = $pdo->prepare( "DESCRIBE `my_table`");
if ( $sh->execute() ) {
    // my_table exists
} else {
    // my_table does not exist    
}

Switching to landscape mode in Android Emulator

For those of you with a Chromebook Pixel/Ubuntu/Crouton with no numpad, installing the onboard keyboard worked for me.

image of onboard software keyboard on ubuntu

Just press 123 to access the numpad layout, and then press 7

If you're on Unity already, onboard may already be installed, so just type onboard from your command line to see if it's there.

If not, just type:

sudo apt-get update

sudo apt-get install onboard

PS: The Chromebook Pixel's upper keys were supposed to represent the traditional F1 through F11 function keys on Ubuntu/Crouton, so you may want to try those special hardware keys first (on their own or in combination with Ctrl). It's just that for me, I'm running an old copy of Crouton, and the only function key that seems to be recognized is F6

Find p-value (significance) in scikit-learn LinearRegression

The code in elyase's answer https://stackoverflow.com/a/27928411/4240413 does not actually work. Notice that sse is a scalar, and then it tries to iterate through it. The following code is a modified version. Not amazingly clean, but I think it works more or less.

class LinearRegression(linear_model.LinearRegression):

    def __init__(self,*args,**kwargs):
        # *args is the list of arguments that might go into the LinearRegression object
        # that we don't know about and don't want to have to deal with. Similarly, **kwargs
        # is a dictionary of key words and values that might also need to go into the orginal
        # LinearRegression object. We put *args and **kwargs so that we don't have to look
        # these up and write them down explicitly here. Nice and easy.

        if not "fit_intercept" in kwargs:
            kwargs['fit_intercept'] = False

        super(LinearRegression,self).__init__(*args,**kwargs)

    # Adding in t-statistics for the coefficients.
    def fit(self,x,y):
        # This takes in numpy arrays (not matrices). Also assumes you are leaving out the column
        # of constants.

        # Not totally sure what 'super' does here and why you redefine self...
        self = super(LinearRegression, self).fit(x,y)
        n, k = x.shape
        yHat = np.matrix(self.predict(x)).T

        # Change X and Y into numpy matricies. x also has a column of ones added to it.
        x = np.hstack((np.ones((n,1)),np.matrix(x)))
        y = np.matrix(y).T

        # Degrees of freedom.
        df = float(n-k-1)

        # Sample variance.     
        sse = np.sum(np.square(yHat - y),axis=0)
        self.sampleVariance = sse/df

        # Sample variance for x.
        self.sampleVarianceX = x.T*x

        # Covariance Matrix = [(s^2)(X'X)^-1]^0.5. (sqrtm = matrix square root.  ugly)
        self.covarianceMatrix = sc.linalg.sqrtm(self.sampleVariance[0,0]*self.sampleVarianceX.I)

        # Standard erros for the difference coefficients: the diagonal elements of the covariance matrix.
        self.se = self.covarianceMatrix.diagonal()[1:]

        # T statistic for each beta.
        self.betasTStat = np.zeros(len(self.se))
        for i in xrange(len(self.se)):
            self.betasTStat[i] = self.coef_[0,i]/self.se[i]

        # P-value for each beta. This is a two sided t-test, since the betas can be 
        # positive or negative.
        self.betasPValue = 1 - t.cdf(abs(self.betasTStat),df)

How to auto-size an iFrame?

Oli has a solution that will work for me. For the record, the page inside my iFrame is rendered by javascript, so I'll need an infinitesimal delay before reporting back the offsetHeight. It looks like something along these lines:


    $(document).ready(function(){
        setTimeout(setHeight);
    });

    function setHeight() {
        alert(document['body'].offsetHeight);   
    }

Comparing double values in C#

As a general rule:

Double representation is good enough in most cases but can miserably fail in some situations. Use decimal values if you need complete precision (as in financial applications).

Most problems with doubles doesn't come from direct comparison, it use to be a result of the accumulation of several math operations which exponentially disturb the value due to rounding and fractional errors (especially with multiplications and divisions).

Check your logic, if the code is:

x = 0.1

if (x == 0.1)

it should not fail, it's to simple to fail, if X value is calculated by more complex means or operations it's quite possible the ToString method used by the debugger is using an smart rounding, maybe you can do the same (if that's too risky go back to using decimal):

if (x.ToString() == "0.1")

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Parsing boolean values with argparse

A quite similar way is to use:

feature.add_argument('--feature',action='store_true')

and if you set the argument --feature in your command

 command --feature

the argument will be True, if you do not set type --feature the arguments default is always False!

How to tell if UIViewController's view is visible

The approach that I used for a modal presented view controller was to check the class of the presented controller. If the presented view controller was ViewController2 then I would execute some code.

UIViewController *vc = [self presentedViewController];

if ([vc isKindOfClass:[ViewController2 class]]) {
    NSLog(@"this is VC2");
}

Get the last non-empty cell in a column in Google Sheets

If A2:A contains dates contiguously then INDEX(A2:A,COUNT(A2:A)) will return the last date. The final formula is

=DAYS360(A2,INDEX(A2:A,COUNT(A2:A)))

Carriage Return\Line feed in Java

The method newLine() ensures a platform-compatible new line is added (0Dh 0Ah for DOS, 0Dh for older Macs, 0Ah for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Remove excess whitespace from within a string

$str = preg_replace('/[\s]+/', ' ', $str);

Android Use Done button on Keyboard to click button

Your Last Edittext .setOnEditorActionListener call this method automatic hit api

I was Call in LoginActivity in et_password

 et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {

                    Log.i(TAG,"Enter pressed");
                    Log.i(Check Internet," and Connect To Server");

                }
                return false;
            }
        });

Working Fine

html select only one checkbox in a group

If someone need a solution without an external javascript libraries you could use this example. A group of checkboxes allowing 0..1 values. You may click on the checkbox component or associated label text.

    <input id="mygroup1" name="mygroup" type="checkbox" value="1" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup1">Yes</label>
    <input id="mygroup0" name="mygroup" type="checkbox" value="0" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup0">No</label>

- - - - - - - - 

    function toggleRadioCheckbox(sender) {
        // RadioCheckbox: 0..1 enabled in a group 
        if (!sender.checked) return;
        var fields = document.getElementsByName(sender.name);
        for(var idx=0; idx<fields.length; idx++) {
            var field = fields[idx];
            if (field.checked && field!=sender)
                field.checked=false;
        }
    }

How to compare times in Python?

Surprised I haven't seen this one liner here:

datetime.datetime.now().hour == 8

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Installing mcrypt extension for PHP on OSX Mountain Lion

Installing php-mcrypt without the use of port or brew

Note: these instructions are long because they intend to be thorough. The process is actually fairly straight-forward. If you're an optimist, you can skip down to the building the mcrypt extension section, but you may very well see the errors I did, telling me to install autoconf and libmcrypt first.

I have just gone through this on a fresh install of OSX 10.9. The solution which worked for me was very close to that of ckm - I am including their steps as well as my own in full, for completeness. My main goal (other than "having mcrypt") was to perform the installation in a way which left the least impact on the system as a whole. That means doing things manually (no port, no brew)

To do things manually, you will first need a couple of dependencies: one for building PHP modules, and another for mcrypt specifically. These are autoconf and libmcrypt, either of which you might have already, but neither of which you will have on a fresh install of OSX 10.9.

autoconf

Autoconf (for lack of a better description) is used to tell not-quite-disparate, but still very different, systems how to compile things. It allows you to use the same set of basic commands to build modules on Linux as you would on OSX, for example, despite their different file-system hierarchies, etc. I used the method described by Ares on StackOverflow, which I will reproduce here for completeness. This one is very straight-forward:

$ mkdir -p ~/mcrypt/dependencies/autoconf
$ cd ~/mcrypt/dependencies/autoconf
$ curl -OL http://ftpmirror.gnu.org/autoconf/autoconf-latest.tar.gz
$ tar xzf autoconf-latest.tar.gz
$ cd autoconf-*/
$ ./configure --prefix=/usr/local
$ make
$ sudo make install

Next, verify the installation by running:

$ which autoconf

which should return /usr/local/bin/autoconf

libmcrypt

Next, you will need libmcrypt, used to provide the guts of the mcrypt extension (the extension itself being a provision of a PHP interface into this library). The method I used was based on the one described here, but I have attempted to simplify things as best I can:

First, download the libmcrypt source, available from SourceForge, and available as of the time of this writing, specifically, at:

http://sourceforge.net/projects/mcrypt/files/Libmcrypt/2.5.8/libmcrypt-2.5.8.tar.bz2/download

You'll need to jump through the standard SourceForge hoops to get at the real download link, but once you have it, you can pass it in to something like this:

$ mkdir -p ~/mcrypt/dependencies/libmcrypt
$ cd ~/mcrypt/dependencies/libmcrypt
$ curl -L -o libmcrypt.tar.bz2 '<SourceForge direct link URL>'
$ tar xjf libmcrypt.tar.bz2
$ cd libmcrypt-*/
$ ./configure
$ make
$ sudo make install

The only way I know of to verify that this has worked is via the ./configure step for the mcrypt extension itself (below)

building the mcrypt extension

This is our actual goal. Hopefully the brief stint into dependency hell is over now.

First, we're going to need to get the source code for the mcrypt extension. This is most-readily available buried within the source code for all of PHP. So: determine what version of the PHP source code you need.

$ php --version # to get your PHP version

now, if you're lucky, your current version will be available for download from the main mirrors. If it is, you can type something like:

$ mkdir -p ~/mcrypt/php
$ cd ~/mcrypt/php
$ curl -L -o php-5.4.17.tar.bz2 http://www.php.net/get/php-5.4.17.tar.bz2/from/a/mirror

Unfortunately, my current version (5.4.17, in this case) was not available, so I needed to use the alternative/historical links at http://downloads.php.net/stas/ (also an official PHP download site). For these, you can use something like:

$ mkdir -p ~/mcrypt/php
$ cd ~/mcrypt/php
$ curl -LO http://downloads.php.net/stas/php-5.4.17.tar.bz2

Again, based on your current version.

Once you have it, (and all the dependencies, from above), you can get to the main process of actually building/installing the module.

$ cd ~/mcrypt/php
$ tar xjf php-*.tar.bz2
$ cd php-*/ext/mcrypt
$ phpize
$ ./configure # this is the step which fails without the above dependencies
$ make
$ make test
$ sudo make install

In theory, mcrypt.so is now in your PHP extension directory. Next, we need to tell PHP about it.

configuring the mcrypt extension

Your php.ini file needs to be told to load mcrypt. By default in OSX 10.9, it actually has mcrypt-specific configuration information, but it doesn't actually activate mcrypt unless you tell it to.

The php.ini file does not, by default, exist. Instead, the file /private/etc/php.ini.default lists the default configuration, and can be used as a good template for creating the "true" php.ini, if it does not already exist.

To determine whether php.ini already exists, run:

$ ls /private/etc/php.ini

If there is a result, it already exists, and you should skip the next command.

To create the php.ini file, run:

$ sudo cp /private/etc/php.ini.default /private/etc/php.ini

Next, you need to add the line:

extension=mcrypt.so

Somewhere in the file. I would recommend searching the file for ;extension=, and adding it immediately prior to the first occurrence.

Once this is done, the installation and configuration is complete. You can verify that this has worked by running:

php -m | grep mcrypt

Which should output "mcrypt", and nothing else.

If your use of PHP relies on Apache's httpd, you will need to restart it before you will notice the changes on the web. You can do so via:

$ sudo apachectl restart

And you're done.

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy

e.g.

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

Cannot read property 'addEventListener' of null

I simply added 'async' to my script tag, which seems to have fixed the issue. I'm not sure why, if someone can explain, but it worked for me. My guess is that the page isn't waiting for the script to load, so the page loads at the same time as the JavaScript.

Async/Await enables us to write asynchronous code in a synchronous fashion. it’s just syntactic sugar using generators and yield statements to “pause” execution, giving us the ability to assign it to a variable!

Here's reference link- https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I had the same problem. The thing is. The selected item doesnt know which object it should use from the collection. So you have to say to the selected item to use the item from the collection.

public MyObject SelectedObject
 {
      get
      {
          Objects.find(x => x.id == _selectedObject.id)
          return _selectedObject;
      }
      set
      {
           _selectedObject = value;
      }
 }

I hope this helps.

Transpose a range in VBA

Something like this should do it for you.

Sub CombineColumns1()
    Dim xRng As Range
    Dim i As Long, j As Integer
    Dim xNextRow As Long
    Dim xTxt As String
    On Error Resume Next
    With ActiveSheet
        xTxt = .RangeSelection.Address
        Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
        If xRng Is Nothing Then Exit Sub
        j = xRng.Columns(1).Column
        For i = 4 To xRng.Columns.Count Step 3
            'Need to recalculate the last row, as some of the final columns may not have data in all rows
            xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1

            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
        Next
    End With
End Sub

You could do this too.

Sub TransposeFormulas()
    Dim vFormulas As Variant
    Dim oSel As Range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a range of cells first.", _
                vbOKOnly + vbInformation, "Transpose formulas"
        Exit Sub
    End If
    Set oSel = Selection
    vFormulas = oSel.Formula
    vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
    oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub

See this for more info.

http://bettersolutions.com/vba/arrays/transposing.htm

Change One Cell's Data in mysql

My answer is repeating what others have said before, but I thought I'd add an example, using MySQL, only because the previous answers were a little bit cryptic to me.

The general form of the command you need to use to update a single row's column:

UPDATE my_table SET my_column='new value' WHERE something='some value';

And here's an example.

BEFORE

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10104 | 
+------------+-------+
2 rows in set (0.00 sec)

MAKING THE CHANGE

mysql> update ae set port='10105' where aet='CDRECORD';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

AFTER

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10105 | 
+------------+-------+
2 rows in set (0.00 sec)

How to compile the finished C# project and then run outside Visual Studio?

I'm using Visual Studio 2017.

  1. Go to dropdown box build.
  2. Choose Pubish Guessing Game (or whatever your project is called.
  3. Wiz Box opens so tell it where to publish it and click Next.
  4. Choose how to install (I usually choose CD-ROM). click Next.
  5. Choose updates check (I usually choose no check) click Next.
  6. Click Finish

It will publish, complete with setup file to the location you specified.

Hope this helps

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Use latest version of Internet Explorer in the webbrowser control

I saw Veer's answer. I think it's right, but it did not I work for me. Maybe I am using .NET 4 and am using 64x OS so kindly check this.

You may put in setup or check it in start-up of your application:

private void Form1_Load(object sender, EventArgs e)
{
    var appName = Process.GetCurrentProcess().ProcessName + ".exe";
    SetIE8KeyforWebBrowserControl(appName);
}

private void SetIE8KeyforWebBrowserControl(string appName)
{
    RegistryKey Regkey = null;
    try
    {
        // For 64 bit machine
        if (Environment.Is64BitOperatingSystem)
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
        else  //For 32 bit machine
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

        // If the path is not correct or
        // if the user haven't priviledges to access the registry
        if (Regkey == null)
        {
            MessageBox.Show("Application Settings Failed - Address Not found");
            return;
        }

        string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        // Check if key is already present
        if (FindAppkey == "8000")
        {
            MessageBox.Show("Required Application Settings Present");
            Regkey.Close();
            return;
        }

        // If a key is not present add the key, Key value 8000 (decimal)
        if (string.IsNullOrEmpty(FindAppkey))
            Regkey.SetValue(appName, unchecked((int)0x1F40), RegistryValueKind.DWord);

        // Check for the key after adding
        FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        if (FindAppkey == "8000")
            MessageBox.Show("Application Settings Applied Successfully");
        else
            MessageBox.Show("Application Settings Failed, Ref: " + FindAppkey);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Application Settings Failed");
        MessageBox.Show(ex.Message);
    }
    finally
    {
        // Close the Registry
        if (Regkey != null)
            Regkey.Close();
    }
}

You may find messagebox.show, just for testing.

Keys are as the following:

  • 11001 (0x2AF9) - Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.

  • 11000 (0x2AF8) - Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.

  • 10001 (0x2711)- Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

  • 10000 (0x2710)- Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

  • 8888 (0x22B8) - Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.

  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

Reference: MSDN: Internet Feature Controls

I saw applications like Skype use 10001. I do not know.

NOTE

The setup application will change the registry. You may need to add a line in the Manifest File to avoid errors due to permissions of change in registry:

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

UPDATE 1

This is a class will get the latest version of IE on windows and make changes as should be;

public class WebBrowserHelper
{


    public static int GetEmbVersion()
    {
        int ieVer = GetBrowserVersion();

        if (ieVer > 9)
            return ieVer * 1000 + 1;

        if (ieVer > 7)
            return ieVer * 1111;

        return 7000;
    } // End Function GetEmbVersion

    public static void FixBrowserVersion()
    {
        string appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
        FixBrowserVersion(appName);
    }

    public static void FixBrowserVersion(string appName)
    {
        FixBrowserVersion(appName, GetEmbVersion());
    } // End Sub FixBrowserVersion

    // FixBrowserVersion("<YourAppName>", 9000);
    public static void FixBrowserVersion(string appName, int ieVer)
    {
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".vshost.exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".vshost.exe", ieVer);
    } // End Sub FixBrowserVersion 

    private static void FixBrowserVersion_Internal(string root, string appName, int ieVer)
    {
        try
        {
            //For 64 bit Machine 
            if (Environment.Is64BitOperatingSystem)
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
            else  //For 32 bit Machine 
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);


        }
        catch (Exception)
        {
            // some config will hit access rights exceptions
            // this is why we try with both LOCAL_MACHINE and CURRENT_USER
        }
    } // End Sub FixBrowserVersion_Internal 

    public static int GetBrowserVersion()
    {
        // string strKeyPath = @"HKLM\SOFTWARE\Microsoft\Internet Explorer";
        string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
        string[] ls = new string[] { "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" };

        int maxVer = 0;
        for (int i = 0; i < ls.Length; ++i)
        {
            object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, ls[i], "0");
            string strVal = System.Convert.ToString(objVal);
            if (strVal != null)
            {
                int iPos = strVal.IndexOf('.');
                if (iPos > 0)
                    strVal = strVal.Substring(0, iPos);

                int res = 0;
                if (int.TryParse(strVal, out res))
                    maxVer = Math.Max(maxVer, res);
            } // End if (strVal != null)

        } // Next i

        return maxVer;
    } // End Function GetBrowserVersion 


}

using of class as followed

WebBrowserHelper.FixBrowserVersion();
WebBrowserHelper.FixBrowserVersion("SomeAppName");
WebBrowserHelper.FixBrowserVersion("SomeAppName",intIeVer);

you may face a problem for in comparability of windows 10, may due to your website itself you may need to add this meta tag

<meta http-equiv="X-UA-Compatible" content="IE=11" >

Enjoy :)

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

To solve this problem (RPC:S-5:AEC-0):

  1. Go to settings
  2. Go to backup and reset
  3. Go down to recovery mode
  4. Reboot the system

This seemed to fix the problem for my tab. Now I can use Google Play store and download any app I want.

MySQL "Group By" and "Order By"

According to SQL standard you cannot use non-aggregate columns in select list. MySQL allows such usage (uless ONLY_FULL_GROUP_BY mode used) but result is not predictable.

ONLY_FULL_GROUP_BY

You should first select fromEmail, MIN(read), and then, with second query (or subquery) - Subject.

What is the proper REST response code for a valid request but an empty data?

According to w3 post,

200 OK

The request has succeeded. The information returned with the response is dependent on the method used in the request

202 Accepted

The request has been accepted for processing, but the processing has not been completed.

204 No Content

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.

400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications

401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field

404 Not Found

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent

Operand type clash: uniqueidentifier is incompatible with int

If you're accessing this via a View then try sp_recompile or refreshing views.

sp_recompile:

Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.

Arguments

[ @objname= ] 'object'

The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.

Return Code Values

0 (success) or a nonzero number (failure)

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

how to add picasso library in android studio

Add the Picasso library in Dependency

dependencies {
       ...
       implementation 'com.squareup.picasso:picasso:2.71828'
       ...
    }

Sync The Project Create one imageview in Layout

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">
</ImageView>

Add the Internet permission in Manifest file

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

//Initialize ImageView

ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.get()
   .load("YOUR IMAGE URL HERE")
   .into(imageView);

Force an SVN checkout command to overwrite current files

Try the --force option. svn help checkout gives the details.

How to find duplicate records in PostgreSQL

In your case, because of the constraint you need to delete the duplicated records.

  1. Find the duplicated rows
  2. Organize them by created_at date - in this case I'm keeping the oldest
  3. Delete the records with USING to filter the right rows
WITH duplicated AS ( 
    SELECT id,
        count(*) 
    FROM products 
    GROUP BY id 
    HAVING count(*) > 1), 
ordered AS ( 
    SELECT p.id, 
        created_at, 
        rank() OVER (partition BY p.id ORDER BY p.created_at) AS rnk 
    FROM products o 
    JOIN     duplicated d ON d.id = p.id ), 
products_to_delete AS ( 
    SELECT id, 
        created_at 
    FROM   ordered 
    WHERE  rnk = 2
) 
DELETE 
FROM products 
USING products_to_delete 
WHERE products.id = products_to_delete.id 
    AND products.created_at = products_to_delete.created_at;

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to detect input type=file "change" for the same file?

Create for the input a click event and a change event. The click event empties the input and the change event contains the code you want to execute.

So the click event will empty when you click the input button(before the select file windows opens), therefor the change event will always trigger when you select a file.

_x000D_
_x000D_
$("#input").click(function() {_x000D_
  $("#input").val("")_x000D_
});_x000D_
_x000D_
$("#input").change(function() {_x000D_
  //Your code you want to execute!_x000D_
});
_x000D_
<input id="input" type="file">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

How to update data in one table from corresponding data in another table in SQL Server 2005

UPDATE table1
SET column1 = (SELECT expression1
               FROM table2
               WHERE conditions)
[WHERE conditions];

XML Parser for C

How about one written in pure assembler :-) Don't forget to check out the benchmarks.

Algorithm to generate all possible permutations of a list?

public class PermutationGenerator
{
    private LinkedList<List<int>> _permutationsList;
    public void FindPermutations(List<int> list, int permutationLength)
    {
        _permutationsList = new LinkedList<List<int>>();
        foreach(var value in list)
        {
            CreatePermutations(value, permutationLength);
        }
    }

    private void CreatePermutations(int value, int permutationLength)
    {
        var node = _permutationsList.First;
        var last = _permutationsList.Last;
        while (node != null)
        {
            if (node.Value.Count < permutationLength)
            {
                GeneratePermutations(node.Value, value, permutationLength);
            }
            if (node == last)
            {
                break;
            }
            node = node.Next;
        }

        List<int> permutation = new List<int>();
        permutation.Add(value);
        _permutationsList.AddLast(permutation);
    }

    private void GeneratePermutations(List<int> permutation, int value, int permutationLength)
    {
       if (permutation.Count < permutationLength)
        {
            List<int> copyOfInitialPermutation = new List<int>(permutation);
            copyOfInitialPermutation.Add(value);
            _permutationsList.AddLast(copyOfInitialPermutation);
            List<int> copyOfPermutation = new List<int>();
            copyOfPermutation.AddRange(copyOfInitialPermutation);
            int lastIndex = copyOfInitialPermutation.Count - 1;
            for (int i = lastIndex;i > 0;i--)
            {
                int temp = copyOfPermutation[i - 1];
                copyOfPermutation[i - 1] = copyOfPermutation[i];
                copyOfPermutation[i] = temp;

                List<int> perm = new List<int>();
                perm.AddRange(copyOfPermutation);
                _permutationsList.AddLast(perm);
            }
        }
    }

    public void PrintPermutations(int permutationLength)
    {
        int count = _permutationsList.Where(perm => perm.Count() == permutationLength).Count();
        Console.WriteLine("The number of permutations is " + count);
    }
}

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Difference between subprocess.Popen and os.system

Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:

  • using pipe in the shell
  • better newline support
  • better handling of exceptions

Read XLSX file in Java

AFAIK there are no xlsx-libraries available yet. But there are some for old xls:

One library is jxls which internally uses the already mentioned POI.

2 other links: Handle Excel files, Java libraries to read and write Excel XLS document files.

How can I create Min stl priority_queue?

We can do this using several ways.

Using template comparator parameter

    int main() 
    {
      priority_queue<int, vector<int>, greater<int> > pq;

      pq.push(40);
      pq.push(320);
      pq.push(42);
      pq.push(65);
      pq.push(12);

      cout<<pq.top()<<endl;
      return 0;
    }

Using used defined compartor class

     struct comp
     {
        bool operator () (int lhs, int rhs)
        {
           return lhs > rhs;
        }
     };

    int main()
    {
       priority_queue<int, vector<int>, comp> pq;

       pq.push(40);
       pq.push(320);
       pq.push(42);
       pq.push(65);
       pq.push(12);

       cout<<pq.top()<<endl;

       return 0;
    }

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

it is wrong. correct will be

P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these

Waiting Time (0+3+4+6+10)/5 = 4.6

Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf

Split a string into an array of strings based on a delimiter

you can use the TStrings.DelimitedText property for split an string

check this sample

program Project28;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;

procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
   ListOfStrings.Clear;
   ListOfStrings.Delimiter       := Delimiter;
   ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
   ListOfStrings.DelimitedText   := Str;
end;


var
   OutPutList: TStringList;
begin
   OutPutList := TStringList.Create;
   try
     Split(':', 'word:doc,txt,docx', OutPutList) ;
     Writeln(OutPutList.Text);
     Readln;
   finally
     OutPutList.Free;
   end;
end.

UPDATE

See this link for an explanation of StrictDelimiter.

JUnit tests pass in Eclipse but fail in Maven Surefire

I have the similar problem, but with IntelliJ IDEA + Maven + TestNG + spring-test. (spring-test is essential of course :) ) It was fixed when I've change config of maven-surefire-plugin to disable run tests in parallel. Like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <skipTests>${maven.test.skip}</skipTests>
        <trimStackTrace>false</trimStackTrace>
        <!--<parallel>methods</parallel>-->
        <!-- to skip integration tests -->
        <excludes>
            <exclude>**/IT*Test.java</exclude>
            <exclude>**/integration/*Test.java</exclude>
        </excludes>
    </configuration>
    <executions>
        <execution>
            <id>integration-test</id>
            <phase>integration-test</phase>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <skipTests>${maven.integration-test.skip}</skipTests>
                <!-- Make sure to include this part, since otherwise it is excluding Integration tests -->
                <excludes>
                    <exclude>none</exclude>
                </excludes>
                <includes>
                    <include>**/IT*Test.java</include>
                    <include>**/integration/*Test.java</include>
                </includes>
            </configuration>
        </execution>
    </executions>
</plugin>

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

When to use the !important property in CSS

I am planning to use !important for a third-party widget meant to be embedded in a large number of websites out of my control.

I reached the conclusion !important is the only solution to protect the widget's stylesheet from the host stylesheet (apart from iframe and inline styles, which are equally bad). For instance, WordPress uses:

#left-area ul {
    list-style-type: disc;
    padding: 0 0 23px 16px;
    line-height: 26px;
}

This rule threathens to override any UL in my widget because id's have strong specificity. In that case, systematic use of !important seems to be one of the few solutions.

How do I get the current time zone of MySQL?

As Jakub Vrána (The creator or Adminer and NotORM) mentions in the comments, to select the current timezone offset in TIME use:

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

It will return: 02:00:00 if your timezone is +2:00 for that date

I made a cheatsheet here: Should MySQL have its timezone set to UTC?

Generate a random date between two other dates

from random import randrange
from datetime import timedelta

def random_date(start, end):
    """
    This function will return a random datetime between two datetime 
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last line's calculation.

example run:

from datetime import datetime

d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))

output:

2008-12-04 01:50:17

What is the --save option for npm install?

npm v6.x update ?

now you can be using one of npm i or npm i -S or npm i -P to install and save module as a dependency.

npm i is the alias of npm install

  1. npm i is equal to npm install, means default save module as a dependency;
  2. npm i -S is equal to npm install --save (npm v5-)
  3. npm i -P is equal to npm install --save-prod (npm v5+)

check your npm version

$ npm -v
6.14.4

get npm help

?  ~ npm -h

Usage: npm <command>

where <command> is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    clean-install, clean-install-test, completion, config,
    create, ddp, dedupe, deprecate, dist-tag, docs, doctor,
    edit, explore, fund, get, help, help-search, hook, i, init,
    install, install-ci-test, install-test, it, link, list, ln,
    login, logout, ls, org, outdated, owner, pack, ping, prefix,
    profile, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami

npm <command> -h  quick help on <command>
npm -l            display full usage info
npm help <term>   search for help on <term>
npm help npm      involved overview

Specify configs in the ini-formatted file:
    /Users/xgqfrms-mbp/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

[email protected] /Users/xgqfrms-mbp/.nvm/versions/node/v12.18.0/lib/node_modules/npm

get npm install help

npm -h i / npm help install

$ npm -h i  

npm install (with no args, in package dir)
npm install [<@scope>/]<pkg>
npm install [<@scope>/]<pkg>@<tag>
npm install [<@scope>/]<pkg>@<version>
npm install [<@scope>/]<pkg>@<version range>
npm install <alias>@npm:<name>
npm install <folder>
npm install <tarball file>
npm install <tarball url>
npm install <git:// url>
npm install <github username>/<github project>

aliases: i, isntall, add
common options: [--save-prod|--save-dev|--save-optional] [--save-exact] [--no-save]
?  ~ 

refs

https://docs.npmjs.com/cli/install

enter image description here

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

PHPDoc type hinting for array of objects?

I prefer to read and write clean code - as outlined in "Clean Code" by Robert C. Martin. When following his credo you should not require the developer (as user of your API) to know the (internal) structure of your array.

The API user may ask: Is that an array with one dimension only? Are the objects spread around on all levels of a multi dimensional array? How many nested loops (foreach, etc.) do i need to access all objects? What type of objects are "stored" in that array?

As you outlined you want to use that array (which contains objects) as a one dimensional array.

As outlined by Nishi you can use:

/**
 * @return SomeObj[]
 */

for that.

But again: be aware - this is not a standard docblock notation. This notation was introduced by some IDE producers.

Okay, okay, as a developer you know that "[]" is tied to an array in PHP. But what do a "something[]" mean in normal PHP context? "[]" means: create new element within "something". The new element could be everything. But what you want to express is: array of objects with the same type and it´s exact type. As you can see, the IDE producer introduces a new context. A new context you had to learn. A new context other PHP developers had to learn (to understand your docblocks). Bad style (!).

Because your array do have one dimension you maybe want to call that "array of objects" a "list". Be aware that "list" has a very special meaning in other programming languages. It would be mutch better to call it "collection" for example.

Remember: you use a programming language that enables you all options of OOP. Use a class instead of an array and make your class traversable like an array. E.g.:

class orderCollection implements ArrayIterator

Or if you want to store the internal objects on different levels within an multi dimensional array/object structure:

class orderCollection implements RecursiveArrayIterator

This solution replaces your array by an object of type "orderCollection", but do not enable code completion within your IDE so far. Okay. Next step:

Implement the methods that are introduced by the interface with docblocks - particular:

/**
 * [...]
 * @return Order
 */
orderCollection::current()

/**
 * [...]
 * @return integer E.g. database identifier of the order
 */
orderCollection::key()

/**
 * [...]
 * @return Order
 */
orderCollection::offsetGet()

Do not forget to use type hinting for:

orderCollection::append(Order $order)
orderCollection::offsetSet(Order $order)

This solution stops introducing a lot of:

/** @var $key ... */
/** @var $value ... */

all over your code files (e.g. within loops), as Zahymaka confirmed with her/his answer. Your API user is not forced to introduce that docblocks, to have code completion. To have @return on only one place reduces the redundancy (@var) as mutch as possible. Sprinkle "docBlocks with @var" would make your code worst readable.

Finaly you are done. Looks hard to achive? Looks like taking a sledgehammer to crack a nut? Not realy, since you are familiar with that interfaces and with clean code. Remember: your source code is written once / read many.

If code completion of your IDE do not work with this approach, switch to a better one (e.g. IntelliJ IDEA, PhpStorm, Netbeans) or file a feature request on the issue tracker of your IDE producer.

Thanks to Christian Weiss (from Germany) for being my trainer and for teaching me such a great stuff. PS: Meet me and him on XING.

500 Internal Server Error for php file not for html

It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess file that fixed it for me.

Key existence check in HashMap

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Because Java bytecode does not retain the names of method or constructor arguments.

How to exit an Android app programmatically?

 @Override
    public void onBackPressed() {
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory( Intent.CATEGORY_HOME );
        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(homeIntent);
    }

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +-- __init__.py
¦   +-- main.py
¦   +-- mymodule.py
+-- __init__.py
+-- run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.

Java, reading a file from current directory?

If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:

URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());

reader = new BufferedReader(new FileReader(f));

How to reset radiobuttons in jQuery so that none is checked

If you want to clear all radio buttons in the DOM:

$('input[type=radio]').prop('checked',false);

remove item from array using its name / value

Try this.(IE8+)

//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

Need to find element in selenium by css

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector(".ban.hot") has 5 matching nodes

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

Option 1: Using list items' index (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes

Example:

driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes
  • Not the native selector's way

Example:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)

Limitations

  • Not for multilanguage sites
  • Only for XPath, not for Selenium's CssSelector

Example:

driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)

Limitations

  • Not stable enough if site's structure changes
  • Only for XPath, not CssSelector

Example:

driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)

Limitations

  • Only for XPath, not CssSelector
  • Low performance
  • Tricky XPath

Example:

driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));

How to set the maximum memory usage for JVM?

If you want to limit memory for jvm (not the heap size ) ulimit -v

To get an idea of the difference between jvm and heap memory , take a look at this excellent article http://blogs.vmware.com/apps/2011/06/taking-a-closer-look-at-sizing-the-java-process.html

Should ol/ul be inside <p> or outside?

<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>

Because both <p> and <ol> are element rendered as block.

Rails: call another controller action from a controller

The logic you present is not MVC, then not Rails, compatible.

  • A controller renders a view or redirect

  • A method executes code

From these considerations, I advise you to create methods in your controller and call them from your action.

Example:

 def index
   get_variable
 end

 private

 def get_variable
   @var = Var.all
 end

That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.

Vocabulary is extremely important that's why I insist much.

mysql: SOURCE error 2?

solution - 1) Make sure you're in the root folder of your app. eg app/db/schema.sql.

solution - 2) open/reveal the folder on your window and drag&&drop in the command line next to keywork source (space) filesource. eg source User/myMAC/app/db/schema.sql

How to read a single character from the user?

A comment in one of the other answers mentioned cbreak mode, which is important for Unix implementations because you generally don't want ^C (KeyboardError) to be consumed by getchar (as it will when you set the terminal to raw mode, as done by most other answers).

Another important detail is that if you're looking to read one character and not one byte, you should read 4 bytes from the input stream, as that's the maximum number of bytes a single character will consist of in UTF-8 (Python 3+). Reading only a single byte will produce unexpected results for multi-byte characters such as keypad arrows.

Here's my changed implementation for Unix:

import contextlib
import os
import sys
import termios
import tty


_MAX_CHARACTER_BYTE_LENGTH = 4


@contextlib.contextmanager
def _tty_reset(file_descriptor):
    """
    A context manager that saves the tty flags of a file descriptor upon
    entering and restores them upon exiting.
    """
    old_settings = termios.tcgetattr(file_descriptor)
    try:
        yield
    finally:
        termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings)


def get_character(file=sys.stdin):
    """
    Read a single character from the given input stream (defaults to sys.stdin).
    """
    file_descriptor = file.fileno()
    with _tty_reset(file_descriptor):
        tty.setcbreak(file_descriptor)
        return os.read(file_descriptor, _MAX_CHARACTER_BYTE_LENGTH)

Why is Dictionary preferred over Hashtable in C#?

Since .NET Framework 3.5 there is also a HashSet<T> which provides all the pros of the Dictionary<TKey, TValue> if you need only the keys and no values.

So if you use a Dictionary<MyType, object> and always set the value to null to simulate the type safe hash table you should maybe consider switching to the HashSet<T>.

Finding elements not in a list

>> items = [1,2,3,4]
>> Z = [3,4,5,6]

>> print list(set(items)-set(Z))
[1, 2]

Is it possible to style a mouseover on an image map using CSS?

You can do this by just changing the html. Here's an example:

<hmtl>
  <head>
    <title>Some title</title>
  </head>
  <body> 
  <map name="navigatemap">
    <area shape="rect"  
          coords="166,4,319,41" 
          href="WII.htm"  
          onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
          onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverWII).png'" 
    />
    <area shape="rect"
          coords="330,4,483,41" 
          href="OT.htm"  
          onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
          onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOT).png'" 
    />

    <area shape="rect" 
          coords="491,3,645,41" 
          href="OP.htm"  
          onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
          onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOP).png'" 
   />
  </map> 

  <img src="Assets/NavigationBar(OnHome).png" 
     name="navbar" 
     usemap="#navigatemap" />
  </body>
</html>

How to make a list of n numbers in Python and randomly select any number?

You can use:

import random
random.choice(range(n))

or:

random.choice(range(1,n+1))

if you want it from 1 to n and not from 0.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

https://code.visualstudio.com/Docs/setup

Tip: If you want to run VSCode from the terminal, append the following to your .bashrc file

code () {
if [[ $# = 0 ]]
then
    open -a "Visual Studio Code"
else
    [[ $1 = /* ]] && F="$1" || F="$PWD/${1#./}"
    open -a "Visual Studio Code" --args "$F"
fi
}

Then $ source ~/.bashrc

How do I log a Python error with debug information?

Quoting

What if your application does logging some other way – not using the logging module?

Now, traceback could be used here.

import traceback

def log_traceback(ex, ex_traceback=None):
    if ex_traceback is None:
        ex_traceback = ex.__traceback__
    tb_lines = [ line.rstrip('\n') for line in
                 traceback.format_exception(ex.__class__, ex, ex_traceback)]
    exception_logger.log(tb_lines)
  • Use it in Python 2:

    try:
        # your function call is here
    except Exception as ex:
        _, _, ex_traceback = sys.exc_info()
        log_traceback(ex, ex_traceback)
    
  • Use it in Python 3:

    try:
        x = get_number()
    except Exception as ex:
        log_traceback(ex)
    

How to update gradle in android studio?

Open File > Project Structure > Project Tab

enter image description here

Android Studio has built in project structure menu to check and update gradle and plugin used in the current project.

Below Website gives a detailed explanation on how to update gradle and gradle plugin of Android Studio.

Update gradle plugin Android Studio

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
  //reference to the button that triggered the function:
  $event.target
};

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796

How to tell when UITableView has completed ReloadData?

Details

  • Xcode Version 10.2.1 (10E1001), Swift 5

Solution

import UIKit

// MARK: - UITableView reloading functions

protocol ReloadCompletable: class { func reloadData() }

extension ReloadCompletable {
    func run(transaction closure: (() -> Void)?, completion: (() -> Void)?) {
        guard let closure = closure else { return }
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        closure()
        CATransaction.commit()
    }

    func run(transaction closure: (() -> Void)?, completion: ((Self) -> Void)?) {
        run(transaction: closure) { [weak self] in
            guard let self = self else { return }
            completion?(self)
        }
    }

    func reloadData(completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadData() }, completion: closure)
    }
}

// MARK: - UITableView reloading functions

extension ReloadCompletable where Self: UITableView {
    func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadRows(at: indexPaths, with: animation) }, completion: closure)
    }

    func reloadSections(_ sections: IndexSet, with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadSections(sections, with: animation) }, completion: closure)
    }
}

// MARK: - UICollectionView reloading functions

extension ReloadCompletable where Self: UICollectionView {

    func reloadSections(_ sections: IndexSet, completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadSections(sections) }, completion: closure)
    }

    func reloadItems(at indexPaths: [IndexPath], completion closure: ((Self) -> Void)?) {
        run(transaction: { [weak self] in self?.reloadItems(at: indexPaths) }, completion: closure)
    }
}

Usage

UITableView

// Activate
extension UITableView: ReloadCompletable { }

// ......
let tableView = UICollectionView()

// reload data
tableView.reloadData { tableView in print(collectionView) }

// or
tableView.reloadRows(at: indexPathsToReload, with: rowAnimation) { tableView in print(tableView) }

// or
tableView.reloadSections(IndexSet(integer: 0), with: rowAnimation) { _tableView in print(tableView) }

UICollectionView

// Activate
extension UICollectionView: ReloadCompletable { }

// ......
let collectionView = UICollectionView()

// reload data
collectionView.reloadData { collectionView in print(collectionView) }

// or
collectionView.reloadItems(at: indexPathsToReload) { collectionView in print(collectionView) }

// or
collectionView.reloadSections(IndexSet(integer: 0)) { collectionView in print(collectionView) }

Full sample

Do not forget to add the solution code here

import UIKit

class ViewController: UIViewController {

    private weak var navigationBar: UINavigationBar?
    private weak var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationItem()
        setupTableView()
    }
}
// MARK: - Activate UITableView reloadData with completion functions

extension UITableView: ReloadCompletable { }

// MARK: - Setup(init) subviews

extension ViewController {

    private func setupTableView() {
        guard let navigationBar = navigationBar else { return }
        let tableView = UITableView()
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.dataSource = self
        self.tableView = tableView
    }

    private func setupNavigationItem() {
        let navigationBar = UINavigationBar()
        view.addSubview(navigationBar)
        self.navigationBar = navigationBar
        navigationBar.translatesAutoresizingMaskIntoConstraints = false
        navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        navigationBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        navigationBar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        let navigationItem = UINavigationItem()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "all", style: .plain, target: self, action: #selector(reloadAllCellsButtonTouchedUpInside(source:)))
        let buttons: [UIBarButtonItem] = [
                                            .init(title: "row", style: .plain, target: self,
                                                  action: #selector(reloadRowButtonTouchedUpInside(source:))),
                                            .init(title: "section", style: .plain, target: self,
                                                  action: #selector(reloadSectionButtonTouchedUpInside(source:)))
                                            ]
        navigationItem.leftBarButtonItems = buttons
        navigationBar.items = [navigationItem]
    }
}

// MARK: - Buttons actions

extension ViewController {

    @objc func reloadAllCellsButtonTouchedUpInside(source: UIBarButtonItem) {
        let elementsName = "Data"
        print("-- Reloading \(elementsName) started")
        tableView?.reloadData { taleView in
            print("-- Reloading \(elementsName) stopped \(taleView)")
        }
    }

    private var randomRowAnimation: UITableView.RowAnimation {
        return UITableView.RowAnimation(rawValue: (0...6).randomElement() ?? 0) ?? UITableView.RowAnimation.automatic
    }

    @objc func reloadRowButtonTouchedUpInside(source: UIBarButtonItem) {
        guard let tableView = tableView else { return }
        let elementsName = "Rows"
        print("-- Reloading \(elementsName) started")
        let indexPathToReload = tableView.indexPathsForVisibleRows?.randomElement() ?? IndexPath(row: 0, section: 0)
        tableView.reloadRows(at: [indexPathToReload], with: randomRowAnimation) { _tableView in
            //print("-- \(taleView)")
            print("-- Reloading \(elementsName) stopped in \(_tableView)")
        }
    }

    @objc func reloadSectionButtonTouchedUpInside(source: UIBarButtonItem) {
        guard let tableView = tableView else { return }
        let elementsName = "Sections"
        print("-- Reloading \(elementsName) started")
        tableView.reloadSections(IndexSet(integer: 0), with: randomRowAnimation) { _tableView in
            //print("-- \(taleView)")
            print("-- Reloading \(elementsName) stopped in \(_tableView)")
        }
    }
}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(Date())"
        return cell
    }
}

Results

enter image description here

Open Google Chrome from VBA/Excel

shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca")

CSS transition fade in

I always prefer to use mixins for small CSS classes like fade in / out incase you want to use them in more than one class.

@mixin fade-in {
    opacity: 1;
    animation-name: fadeInOpacity;
    animation-iteration-count: 1;
    animation-timing-function: ease-in;
    animation-duration: 2s;
}

@keyframes fadeInOpacity {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

and if you don't want to use mixins, you can create a normal class .fade-in.

iPhone: How to get current milliseconds?

[NSDate timeIntervalSinceReferenceDate] is another option, if you don't want to include the Quartz framework. It returns a double, representing seconds.

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

Inverse dictionary lookup in Python

Since this is still very relevant, the first Google hit and I just spend some time figuring this out, I'll post my (working in Python 3) solution:

testdict = {'one'   : '1',
            'two'   : '2',
            'three' : '3',
            'four'  : '4'
            }

value = '2'

[key for key in testdict.items() if key[1] == value][0][0]

Out[1]: 'two'

It will give you the first value that matches.

Hibernate SessionFactory vs. JPA EntityManagerFactory

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration.

Using similar callbacks while using SessionFactory will require extra efforts.

Related Hibernate docs can be found here and here.

Related SOF Question and Spring Forum discussion

How does the Python's range function work?

It is looping, probably the problem is in the part of the print...

If you can't find the logic where the system prints, just add the folling where you want the content out:

for i in range(len(vs)):
    print vs[i]
    print fs[i]
    print rs[i]

UTF-8 encoding problem in Spring MVC

I've resolved this issue by inferring the produced return type into the first GET requestMethod. The important part here is the

produces="application/json;charset=UTF-8

So every one how use /account/**, Spring will return application/json;charset=UTF-8 content type.

@Controller
@Scope("session") 
@RequestMapping(value={"/account"}, method = RequestMethod.GET,produces="application/json;charset=UTF-8")
public class AccountController {

   protected final Log logger = LogFactory.getLog(getClass());

   ....//More parameters and method here...

   @RequestMapping(value={"/getLast"}, method = RequestMethod.GET)
   public @ResponseBody String getUltimo(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{

      ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
      try {
        Account account = accountDao.getLast();
        return writer.writeValueAsString(account);
      }
      catch (Exception e) {
        return errorHandler(e, response, writer);
      }
}

So, you do not have to set up for each method in your Controller, you can do it for the entire class. If you need more control over a specific method, you just only have to infer the produces return content type.

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

Same problem occurd with me, with AWS RDS MySQL. Just now, answered similar question here. Looked various sources, but as of this thread, almost all lack of answer. While this thread helped me, tweak in mind to update hostnames at server. Access your SSH and follow the steps:

cd /etc/
sudo nano hosts

Now, Appending here your hostnames: For example:

127.0.0.1 localhost
127.0.0.1 subdomain.domain.com [if cname redirected to endpoints]
127.0.0.1 xxxxxxxx.xxxx.xxxxx.rds.amazonaws.com [Endpoints]

and now, configuring config/database.php as follows:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => '35.150.12.345',
    'username' => 'user-name-here',
    'password' => 'password-here',
    'database' => 'database-name-here',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

where 35.150.12.345 is your IPv4 Public IP, located at ec2-dashboard > Network Interfaces > Description : RDSNetworkInterface >> IPv4 Public IP('35.150.12.345') there.

Note: Please note that only IPV4 will work at 'hostname' option. hostname, cname, domains will output database connection error.

React - Preventing Form Submission

componentDidUpdate(){               
    $(".wpcf7-submit").click( function(event) {
        event.preventDefault();
    })
}

You can use componentDidUpdate and event.preventDefault() to disable form submission.As react does not support return false.

Hidden Features of C#?

Empty blocks with braces are allowed.

You can write code like this

{
    service.DoTonsOfWork(args);
}

It's helpful when you want to try something without a using or try... finally that you've already written.

//using(var scope = new TransactionScope)
{
    service.DoTonsOfWork(args);
}

Proper way to set response status and JSON content in a REST API made with nodejs and express

You could do it this way:

res.status(400).json(json_response);

This will set the HTTP status code to 400, it works even in express 4.

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

html button to send email

This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto link/action is sparsely supported, but maybe this can help...

HTML:

<form id="fr1">
    <input type="text" id="tb1" />
    <input type="text" id="tb2" />
    <input type="button" id="bt1" value="click" />
</form>

JavaScript (with jQuery):

$(document).ready(function() {
    $('#bt1').click(function() {
        $('#fr1').attr('action',
                       'mailto:[email protected]?subject=' +
                       $('#tb1').val() + '&body=' + $('#tb2').val());
        $('#fr1').submit();
    });
});

Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit type, it's just a button type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.

It's working in so much as it submits the form to a mailto action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.

HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.

Replace X-axis with own values

Yo could also set labels = FALSE inside axis(...) and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it

lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)

Detailed explanation here

Image with rotated labels

android - save image into gallery

I've tried a lot of things to let this work on Marshmallow and Lollipop. Finally i ended up moving the saved picture to the DCIM folder (new Google Photo app scan images only if they are inside this folder apparently)

public static File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
         .format(System.currentTimeInMillis());
    File storageDir = new File(Environment
         .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/");
    if (!storageDir.exists())
        storageDir.mkdirs();
    File image = File.createTempFile(
            timeStamp,                   /* prefix */
            ".jpeg",                     /* suffix */
            storageDir                   /* directory */
    );
    return image;
}

And then the standard code for scanning files which you can find in the Google Developers site too.

public static void addPicToGallery(Context context, String photoPath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(photoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}

Please remember that this folder could not be present in every device in the world and that starting from Marshmallow (API 23), you need to request the permission to WRITE_EXTERNAL_STORAGE to the user.

Arrays.asList() of an array

This works from Java 5 to 7:

public int getTheNumber(Integer... factors) {
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}

In Java 4 there is no vararg... :-)

htaccess - How to force the client's browser to clear the cache?

Adding 'random' numbers to URLs seems inelegant and expensive to me. It also spoils the URL of the pages, which can look like index.html?t=1614333283241 and btw users will have dozens of URLs cached for only one use.
I think this kind of things is what .htaccess files are meant to solve at the server side, between your functional code an the users.

I copy/paste this code from here that allows filtering by file extension to force the browser not to cache them. If you want to return to normal behavior, just delete or comment it.

Create or edit an .htaccess file on every folder you want to prevent caching, then paste this code changing file extensions to your needs, or even to match one individual file.
If the file already exists on your host be cautious modifying what's in it.
(kudos to the link)

# DISABLE CACHING
<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
</IfModule>

<FilesMatch "\.(css|flv|gif|htm|html|ico|jpe|jpeg|jpg|js|mp3|mp4|png|pdf|swf|txt)$">
    <IfModule mod_expires.c>
        ExpiresActive Off
    </IfModule>
    <IfModule mod_headers.c>
        FileETag None
        Header unset ETag
        Header unset Pragma
        Header unset Cache-Control
        Header unset Last-Modified
        Header set Pragma "no-cache"
        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
        Header set Expires "jue, 1 Jan 1970 00:00:00 GMT"
    </IfModule>
</FilesMatch>

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

Try this

$servers = Get-Content test.txt

$reg=""

foreach ($server in $servers) 

{

$reg=$reg+$server+"`t"+([System.Net.Dns]::GetHostAddresses($server) | foreach {echo $_.IPAddressToString})+"`n"

 }
$reg >reg.csv

jQuery get the rendered height of an element?

Have you set the height in the css specifically? If you haven't you need to use offsetHeight; rather than height

var h = document.getElementById('someDiv').style.offsetHeight;

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

PNG transparency issue in IE8

FIXED!

I've been wrestling with the same issue, and just had a breakthrough! We've established that if you give the image a background color or image, the png displays properly on top of it. The black border is gone, but now you've got an opaque background, and that pretty much defeats the purpose.

Then I remembered a rgba to ie filter converter I came across. (Thanks be to Michael Bester). So I wondered what would happen if I gave my problem pngs an ie filtered background emulating rgba(255,255,255,0), fully expecting it not to work, but lets try it anyway...

.item img {
    background: transparent;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)"; /* IE8 */   
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF);   /* IE6 & 7 */      
    zoom: 1;

}

Presto! Goodbye black, and hello working alpha channels in ie7 and 8. Fade your pngs in and out, or animate them across the screen - it's all good.

In Postgresql, force unique on combination of two columns

CREATE TABLE someTable (
    id serial PRIMARY KEY,
    col1 int NOT NULL,
    col2 int NOT NULL,
    UNIQUE (col1, col2)
)

autoincrement is not postgresql. You want a serial.

If col1 and col2 make a unique and can't be null then they make a good primary key:

CREATE TABLE someTable (
    col1 int NOT NULL,
    col2 int NOT NULL,
    PRIMARY KEY (col1, col2)
)

Spring Boot @autowired does not work, classes in different package

In my case @component was not working because I initialized that class instance by using new <classname>().

If we initialize instance by conventional Java way anywhere in code, then spring won't add that component in IOC container.

How to convert an integer to a character array using C

Use itoa, as is shown here.

char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);

buf will be a string array as you documented. You might need to increase the size of the buffer.

Remove a git commit which has not been pushed

One way would be to delete the local branch and checkout that branch from the server if your local branch is ahead of remote by multiple commits and you need to uncommit all of them.

List of Java class file format major version numbers?

These come from the class version. If you try to load something compiled for java 6 in a java 5 runtime you'll get the error, incompatible class version, got 50, expected 49. Or something like that.

See here in byte offset 7 for more info.

Additional info can also be found here.

How to find foreign key dependencies in SQL Server?

Just a note for @"John Sansom" answer,

If the foreign key dependencies are sought, I think that the PT Where clause should be:

i1.CONSTRAINT_TYPE = 'FOREIGN KEY'  -- instead of 'PRIMARY KEY'

and its the ON condition:

ON PT.TABLE_NAME = FK.TABLE_NAME – instead of PK.TABLE_NAME

As commonly is used the primary key of the foreign table, I think this issue has not been noticed before.

Powershell script to check if service is started, if not then start it

Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.

I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".

$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped') 
{
    Start-Service $Service -ErrorAction SilentlyContinue
    Start-Sleep 10
} 
Return "$($Service) has STARTED"

How to pass variable number of arguments to printf/sprintf

have a look at vsnprintf as this will do what ya want http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/

you will have to init the va_list arg array first, then call it.

Example from that link: /* vsprintf example */

#include <stdio.h>
#include <stdarg.h>

void Error (char * format, ...)
{
  char buffer[256];
  va_list args;
  va_start (args, format);
  vsnprintf (buffer, 255, format, args);


  //do something with the error

  va_end (args);
}

How to execute an .SQL script file using c#

This works for me:

public void updatedatabase()
{

    SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
    try
    {

        conn.Open();

        string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));

        // split script on GO command
        IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        foreach (string commandString in commandStrings)
        {
            if (commandString.Trim() != "")
            {
                new SqlCommand(commandString, conn).ExecuteNonQuery();
            }
        }
        lblmsg.Text = "Database updated successfully.";

    }
    catch (SqlException er)
    {
        lblmsg.Text = er.Message;
        lblmsg.ForeColor = Color.Red;
    }
    finally
    {
        conn.Close();
    }
}

Get data from fs.readFile

To elaborate on what @Raynos said, the function you have defined is an asynchronous callback. It doesn't execute right away, rather it executes when the file loading has completed. When you call readFile, control is returned immediately and the next line of code is executed. So when you call console.log, your callback has not yet been invoked, and this content has not yet been set. Welcome to asynchronous programming.

Example approaches

const fs = require('fs');
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    const content = data;

    // Invoke the next step here however you like
    console.log(content);   // Put all of the code here (not the best solution)
    processFile(content);   // Or put the next step in a function and invoke it
});

function processFile(content) {
    console.log(content);
}

Or better yet, as Raynos example shows, wrap your call in a function and pass in your own callbacks. (Apparently this is better practice) I think getting into the habit of wrapping your async calls in function that takes a callback will save you a lot of trouble and messy code.

function doSomething (callback) {
    // any async callback invokes callback with response
}

doSomething (function doSomethingAfter(err, result) {
    // process the async result
});

How can I get table names from an MS Access Database?

Getting a list of tables:

SELECT 
    Table_Name = Name, 
FROM 
    MSysObjects 
WHERE 
    (Left([Name],1)<>"~") 
    AND (Left([Name],4) <> "MSys") 
    AND ([Type] In (1, 4, 6)) 
ORDER BY 
    Name

How to cin to a vector

You can simply do this with the help of for loop
->Ask on runtime from a user (how many inputs he want to enter) and the treat same like arrays.

int main() {
        int sizz,input;
        std::vector<int> vc1;

        cout<< "How many Numbers you want to enter : ";
        cin >> sizz;
        cout << "Input Data : " << endl;
        for (int i = 0; i < sizz; i++) {//for taking input form the user
            cin >> input;
            vc1.push_back(input);
        }
        cout << "print data of vector : " << endl;
        for (int i = 0; i < sizz; i++) {
            cout << vc1[i] << endl;
        }
     }

Import Excel to Datagridview

try this following snippet, its working fine.

private void button1_Click(object sender, EventArgs e)
{
     try
     {
             OpenFileDialog openfile1 = new OpenFileDialog();
             if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             {
                   this.textBox1.Text = openfile1.FileName;
             }
             {
                   string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                   OleDbConnection conn = new OleDbConnection(pathconn);
                   OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                   DataTable dt = new DataTable();
                   MyDataAdapter.Fill(dt);
                   dataGridView1.DataSource = dt;
             }
      }
      catch { }
}

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

How to exit from ForEach-Object in PowerShell

You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

  1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
  2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

Solution-1: use Where-Object filter BEFORE Foreach-Object:

[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
     if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
     $_;
}

OR

1..10 | Where-Object {$_ -le 2} | Foreach-Object {
     $_;
}

Solution-2: Converted Foreach-Object into standard Foreach looping construct:

Foreach ($i in 1..10) { 
     if ($i -eq 3) {break;}
     $i;
}

PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
     if ($_ -eq 3) {return;}  #skips only 3rd iteration.
     $_;
}

HTH

Hide Command Window of .BAT file that Executes Another .EXE File

Try this:

@echo off 
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe
exit

Getting raw SQL query string from PDO prepared statements

You can extend PDOStatement class to capture the bounded variables and store them for later use. Then 2 methods may be added, one for variable sanitizing ( debugBindedVariables ) and another to print the query with those variables ( debugQuery ):

class DebugPDOStatement extends \PDOStatement{
  private $bound_variables=array();
  protected $pdo;

  protected function __construct($pdo) {
    $this->pdo = $pdo;
  }

  public function bindValue($parameter, $value, $data_type=\PDO::PARAM_STR){
    $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>$value);
    return parent::bindValue($parameter, $value, $data_type);
  }

  public function bindParam($parameter, &$variable, $data_type=\PDO::PARAM_STR, $length=NULL , $driver_options=NULL){
    $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>&$variable);
    return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);
  }

  public function debugBindedVariables(){
    $vars=array();

    foreach($this->bound_variables as $key=>$val){
      $vars[$key] = $val->value;

      if($vars[$key]===NULL)
        continue;

      switch($val->type){
        case \PDO::PARAM_STR: $type = 'string'; break;
        case \PDO::PARAM_BOOL: $type = 'boolean'; break;
        case \PDO::PARAM_INT: $type = 'integer'; break;
        case \PDO::PARAM_NULL: $type = 'null'; break;
        default: $type = FALSE;
      }

      if($type !== FALSE)
        settype($vars[$key], $type);
    }

    if(is_numeric(key($vars)))
      ksort($vars);

    return $vars;
  }

  public function debugQuery(){
    $queryString = $this->queryString;

    $vars=$this->debugBindedVariables();
    $params_are_numeric=is_numeric(key($vars));

    foreach($vars as $key=>&$var){
      switch(gettype($var)){
        case 'string': $var = "'{$var}'"; break;
        case 'integer': $var = "{$var}"; break;
        case 'boolean': $var = $var ? 'TRUE' : 'FALSE'; break;
        case 'NULL': $var = 'NULL';
        default:
      }
    }

    if($params_are_numeric){
      $queryString = preg_replace_callback( '/\?/', function($match) use( &$vars) { return array_shift($vars); }, $queryString);
    }else{
      $queryString = strtr($queryString, $vars);
    }

    echo $queryString.PHP_EOL;
  }
}


class DebugPDO extends \PDO{
  public function __construct($dsn, $username="", $password="", $driver_options=array()) {
    $driver_options[\PDO::ATTR_STATEMENT_CLASS] = array('DebugPDOStatement', array($this));
    $driver_options[\PDO::ATTR_PERSISTENT] = FALSE;
    parent::__construct($dsn,$username,$password, $driver_options);
  }
}

And then you can use this inherited class for debugging purpouses.

$dbh = new DebugPDO('mysql:host=localhost;dbname=test;','user','pass');

$var='user_test';
$sql=$dbh->prepare("SELECT user FROM users WHERE user = :test");
$sql->bindValue(':test', $var, PDO::PARAM_STR);
$sql->execute();

$sql->debugQuery();
print_r($sql->debugBindedVariables());

Resulting in

SELECT user FROM users WHERE user = 'user_test'

Array ( [:test] => user_test )

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

Opening popup windows in HTML

HTML alone does not support this. You need to use some JS.

And also consider nowadays people use popup blocker in browsers.

<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Assuming you want uppercase case letters:

function numberToLetter(num){
        var alf={
            '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G'
        };
        if(num.length== 1) return alf[num] || ' ';
        return num.split('').map(numberToLetter);
    }

Example:

numberToLetter('023') is ["A", "C", "D"]

numberToLetter('5') is "F"

number to letter function

Getting 400 bad request error in Jquery Ajax POST

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object. So the correct version is here:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

May be it will help someone else.

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

Delete directory with files in it?

2 cents to add to THIS answer above, which is great BTW

After your glob (or similar) function has scanned/read the directory, add a conditional to check the response is not empty, or an invalid argument supplied for foreach() warning will be thrown. So...

if( ! empty( $files ) )
{
    foreach( $files as $file )
    {
        // do your stuff here...
    }
}

My full function (as an object method):

    private function recursiveRemoveDirectory( $directory )
    {
        if( ! is_dir( $directory ) )
        {
            throw new InvalidArgumentException( "$directory must be a directory" );
        }

        if( substr( $directory, strlen( $directory ) - 1, 1 ) != '/' )
        {
            $directory .= '/';
        }

        $files = glob( $directory . "*" );

        if( ! empty( $files ) )
        {
            foreach( $files as $file )
            {
                if( is_dir( $file ) )
                {
                    $this->recursiveRemoveDirectory( $file );
                }
                else
                {
                    unlink( $file );
                }
            }               
        }
        rmdir( $directory );

    } // END recursiveRemoveDirectory()

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

If you are installing first time then please try login with username and password as root

What does java:comp/env/ do?

After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay

How to dock "Tool Options" to "Toolbox"?

In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.

Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.

split string only on first instance - java

String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);

Result ::
splitData[0] =>  This
splitData[1] =>  is test string  


String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);

Result ::
splitData[0] =>  This
splitData[1] =>  is
splitData[1] =>  test string on web

By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

This code defines a function fixed_sum_digits returning a generator enumerating all six digits numbers such that the sum of digits is 20.

def iter_fun(sum, deepness, myString, Total):
    if deepness == 0:
        if sum == Total:
            yield myString
    else:  
        for i in range(min(10, Total - sum + 1)):
            yield from iter_fun(sum + i,deepness - 1,myString + str(i),Total)

def fixed_sum_digits(digits, Tot):
    return iter_fun(0,digits,"",Tot) 

Try to write it without yield from. If you find an effective way to do it let me know.

I think that for cases like this one: visiting trees, yield from makes the code simpler and cleaner.

Addition for BigDecimal

It's actually rather easy. Just do this:

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);

See also: BigDecimal#add(java.math.BigDecimal)

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

How to show x and y axes in a MATLAB graph?

This should work in Matlab:

set(gca, 'XAxisLocation', 'origin')

Options are: bottom, top, origin.

For Y.axis:

YAxisLocation; left, right, origin

python, sort descending dataframe with pandas

Edit: This is out of date, see @Merlin's answer.

[False], being a nonempty list, is not the same as False. You should write:

test = df.sort('one', ascending=False)

HTML5 Video autoplay on iPhone

Does playsinline attribute help?

Here's what I have:

<video autoplay loop muted playsinline class="video-background ">
  <source src="videos/intro-video3.mp4" type="video/mp4">
</video>

See the comment on playsinline here: https://webkit.org/blog/6784/new-video-policies-for-ios/

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case if you are using UITableView do not forget to add UITableViewDelegate and UITableViewDataSource next to viewcontroller like this. class MenuController: UIViewController, UITableViewDelegate, UITableViewDataSource

When converting old projects (written in Swift 2.3) to Swift 3 it needs adding these keywords.

What is an unhandled promise rejection?

In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.

How does one convert a HashMap to a List in Java?

Basically you should not mess the question with answer, because it is confusing.

Then you could specify what convert mean and pick one of this solution

List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));

List<String> valueList = Collections.list(Collections.enumeration(map.values()));

How to expand a list to function arguments in Python

Try the following:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

How can I call PHP functions by JavaScript?

You need to create an API : Your js functions execute AJAX requests on your web service

  var mult = function(arg1, arg2)
    $.ajax({
      url: "webservice.php?action=mult&arg1="+arg1+"&arg2="+arg2
    }).done(function(data) {
      console.log(data);
    });
  }

on the php side, you'll have to check the action parameter in order to execute the propre function (basically a switch statement on the $_GET["action"] variable)

Can't create project on Netbeans 8.2

I had the same problem I installed NetBeans 8.2 on macOS High Sierra, and by default settings, NetBeans will work with the latest JDK release (currently JDK 9).

NetBeans Problem

What I did was forcing NetBeans to use JDK 8, you must config your netbeans.conf file, you can find it on:

/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf

enter image description here

You need to uncomment and update your path to JDK, you will find yours at:

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

enter image description here

Just save it, restart NetBeans and you are done!

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

Permissions error when connecting to EC2 via SSH on Mac OSx

Are you sure you have used the right instance? I ran into this problem and realized that something like 4 of the ubuntu instances i tried did not have SSH servers installed on them.

For a list of good servers see "Getting the images" about half way down. Sounds like you may be using something else... the default username is ubuntu on these images.

https://help.ubuntu.com/community/EC2StartersGuide

How to check the exit status using an if statement

You could try to find out if $? is empty by using the said script below:

# Code that may fail here
if [ -z "$?" ]
then
      echo "Code if not failed"
else
      echo "Code if failed"
fi

How to get names of enum entries?

As of TypeScript 2.4, enums can contain string intializers https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html

This allows you to write:

 enum Order {
      ONE = "First",
      TWO = "Second"
 }

console.log(`One is ${Order.ONE.toString()}`);

and get this output:

One is First

Cannot open solution file in Visual Studio Code

Use vscode-solution-explorer extension:

This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.

https://github.com/fernandoescolar/vscode-solution-explorer

enter image description here

Thanks @fernandoescolar

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Ternary operators in JavaScript without an "else"

In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;

will become :

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

It's more clear, it's more "javascript" style.

How to generate UML diagrams (especially sequence diagrams) from Java code?

I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code.

you can install PlantUML plugin in the netbeans by this method:

Netbeans Menu -> Tools -> Plugin

Now select Available Plugins and then find PlantUML and install it.

For more information go to website: www.plantuml.com

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

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

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

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

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

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

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

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

What about new objects?

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

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

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

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

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

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

VBA: Convert Text to Number

The solution that for me works is:

For Each xCell In Selection

  xCell.Value = CDec(xCell.Value)

Next xCell 

Can you control how an SVG's stroke-width is drawn?

Here is a work around for inner bordered rect using symbol and use.

Example: https://jsbin.com/yopemiwame/edit?html,output

SVG:

<svg>
  <symbol id="inner-border-rect">
    <rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
  </symbol>
  ...
  <use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>

Note: Make sure to replace the ? in use with real values.

Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.

Circular gradient in android

You can get a circular gradient using android:type="radial":

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:type="radial" android:gradientRadius="250dp"
        android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>

When to use single quotes, double quotes, and backticks in MySQL

(There are good answers above regarding the SQL nature of your question, but this may also be relevant if you are new to PHP.)

Perhaps it is important to mention that PHP handles single and double quoted strings differently...

Single-quoted strings are 'literals' and are pretty much WYSIWYG strings. Double-quoted strings are interpreted by PHP for possible variable-substitution (backticks in PHP are not exactly strings; they execute a command in the shell and return the result).

Examples:

$foo = "bar";
echo 'there is a $foo'; // There is a $foo
echo "there is a $foo"; // There is a bar
echo `ls -l`; // ... a directory list

Creating a new empty branch for a new project

Make an empty new branch like this:

true | git mktree | xargs git commit-tree | xargs git branch proj-doc

If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:

git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc

which might be more convenient than git branch --orphan if that would leave you with a lot of git rm and git mving to do.

Try

git branch --set-upstream proj-doc origin/proj-doc

and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.

how to play video from url

pDialog = new ProgressDialog(this);

    // Set progressbar message
    pDialog.setMessage("Buffering...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    // Show progressbar
    pDialog.show();

    try {
        // Start the MediaController
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoView);      

        Uri videoUri = Uri.parse(videoUrl);
        mVideoView.setMediaController(mediacontroller);
        mVideoView.setVideoURI(videoUri);

    } catch (Exception e) {

        e.printStackTrace();
    }

    mVideoView.requestFocus();
    mVideoView.setOnPreparedListener(new OnPreparedListener() {
        // Close the progress bar and play the video
        public void onPrepared(MediaPlayer mp) {
            pDialog.dismiss();
            mVideoView.start();
        }
    });
    mVideoView.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            finish();               
        }
    });

How do I set up IntelliJ IDEA for Android applications?

Once I have followed all these steps, I start to receive error messages in all android classes calls like:

Cannot resolve Android Classes

I revolved that including android.jar in the SDKs Platform Settings:

SKDs Classpath

Fastest way to implode an associative array with keys

If you're not concerned about the exact formatting however you do want something simple but without the line breaks of print_r you can also use json_encode($value) for a quick and simple formatted output. (note it works well on other data types too)

$str = json_encode($arr);
//output...
[{"id":"123","name":"Ice"},{"id":"234","name":"Cake"},{"id":"345","name":"Pie"}]

How to fill the whole canvas with specific color?

You can change the background of the canvas by doing this:

<head>
    <style>
        canvas {
            background-color: blue;
        }
    </style>
</head>

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Postgres user does not exist?

psql -U postgres

Worked fine for me in case of db name: postgres & username: postgres. So you do not need to write sudo.

And in the case other db, you may try

psql -U yourdb postgres

As it is given in Postgres help:

psql [OPTION]... [DBNAME [USERNAME]]

Why is <deny users="?" /> included in the following example?

Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.

Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

replace NULL with Blank value or Zero in sql server

Different ways to replace NULL in sql server

Replacing NULL value using:

1. ISNULL() function

2. COALESCE() function

3. CASE Statement

SELECT Name as EmployeeName, ISNULL(Bonus,0) as EmployeeBonus from tblEmployee

SELECT Name as EmployeeName, COALESCE(Bonus, 0) as EmployeeBonus 
FROM tblEmployee

SELECT Name as EmployeeName, CASE WHEN Bonus IS NULL THEN 0 
ELSE Bonus  END as EmployeeBonus 
FROM  tblEmployee

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Printing with sed or awk a line following a matching pattern

If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.

sed '/pattern/ { N; s/.*\n//; q }; d'