Programs & Examples On #Mssqlft

An "SQL" Syntax for the Microsoft SharePoint Server.

How do I determine the dependencies of a .NET application?

Best app that I see and use, show missed/problematic dlls: http://www.dependencywalker.com/

sweet-alert display HTML code in text

Sweet alerts also has an 'html' option, set it to true.

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Handler vs AsyncTask vs Thread

Let me try and answer the question here with an example :) - MyImageSearch [Kindly refer the image here of the main activity screen - containing an edit text / search button / grid view]

MyImageSearch

Description of MyImageSearch - Once user enters the details on the edit text field and clicks on the search button, we will search images on the internet via the web services provided by flickr (you only need to register there to get a key/secret token) - for searching we send an HTTP Request and GET JSON Data back in response containing the url's of individual images which we will then use to load the grid view.

My Implementation - In the main activity I will define a inner class which extends the AsyncTask to send the HTTP Request in doInBackGround Method and fetch the JSON Response and update my local ArrayList of FlickrItems which I am going to use to update my GridView via the FlickrAdapter (extends the BaseAdapter) and call the adapter.notifyDataSetChanged() in the onPostExecute() of AsyncTask to reload the grid view. Note that here the HTTP Request is a blocking call because of which I have done it via the AsyncTask. And, I can cache the items in adapter to increase the performance or store them on SDCard. The grid that I will be inflating in the FlickrAdapter contains in my implementation a progressbar and image view. Below you can find the code for mainActivity which I used.

Answer to the Question Now - So once we have the JSON data for fetching individual Images we can implement the logic of getting the images in background via Handlers or Threads or AsyncTask. We should note here that since my images once downloaded must be displayed on the UI/main thread we cannot simply use threads as it is since they don't have access to the context. In the FlickrAdapter, the choices I could think of:

  • Choice 1: Create a LooperThread [extends thread] - and keep on downloading images sequentially in one thread by keeping this thread open [looper.loop()]
  • Choice 2: Make use of a Thread Pool and post the runnable via myHandler which contains reference to my ImageView, but since the views in Grid View are recycled, again the problem might arise where image at index 4 is displayed at index 9 [download may take more time]
  • Choice 3 [I used this]: Make use of a Thread Pool and send a message to myHandler, which contains data related to ImageView's index and ImageView itself, so while doing handleMessage() we will update the ImageView only if currentIndex matches the index of the Image we tried to download.
  • Choice 4: Make use of AsyncTask to download the images in background, but here I will not have access to the number of threads I want in the thread pool and it varies with different android version, but in Choice 3 I can make of conscious decision of the size of thread pool depending on device configuration being used.

Here the source code:

public class MainActivity extends ActionBarActivity {

    GridView imageGridView;
    ArrayList<FlickrItem> items = new ArrayList<FlickrItem>();
    FlickrAdapter adapter;

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

        imageGridView = (GridView) findViewById(R.id.gridView1);
        adapter = new FlickrAdapter(this, items);
        imageGridView.setAdapter(adapter);
    }

    // To avoid a memory leak on configuration change making it a inner class
    class FlickrDownloader extends AsyncTask<Void, Void, Void> {



        @Override
        protected Void doInBackground(Void... params) {
            FlickrGetter getter = new FlickrGetter();

            ArrayList<FlickrItem> newItems = getter.fetchItems();

            // clear the existing array
            items.clear();

            // add the new items to the array
            items.addAll(newItems);

            // is this correct ? - Wrong rebuilding the list view and should not be done in background
            //adapter.notifyDataSetChanged();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            adapter.notifyDataSetChanged();
        }

    }

    public void search(View view) {
        // get the flickr data
        FlickrDownloader downloader = new FlickrDownloader();
        downloader.execute();
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

I hope my answer though long will help in understanding some of the finer details.

Python Loop: List Index Out of Range

  1. In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
    Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.

We can fix this issue by iterating over a range of indexes instead:

for i in range(len(a))

and access the a's items like that: a[i]. This won't give any errors.

  1. In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.

To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.

  1. There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:

b = [a[i] + a[i+1] for i in range(len(a) - 1)]

This does the job in only one line.

Java Wait for thread to finish

You could use a CountDownLatch from the java.util.concurrent package. It is very useful when waiting for one or more threads to complete before continuing execution in the awaiting thread.

For example, waiting for three tasks to complete:

CountDownLatch latch = new CountDownLatch(3);
...
latch.await(); // Wait for countdown

The other thread(s) then each call latch.countDown() when complete with the their tasks. Once the countdown is complete, three in this example, the execution will continue.

How to calculate an angle from three points?

Basically what you have is two vectors, one vector from P1 to P2 and another from P1 to P3. So all you need is an formula to calculate the angle between two vectors.

Have a look here for a good explanation and the formula.

alt text

Cannot find java. Please use the --jdkhome switch

In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.

When I see a directory structure with bin and jre subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.

Replace \n with actual new line in Sublime Text

  1. Open Find and Replace Option ( CTRL + ALT + F in Mac )
  2. Type \n in find input box
  3. Click on Find All button, This will select all the \n in the text with the cursor
  4. Now press Enter, this will replace \n with the New Line

GitHub authentication failing over https, returning wrong email address

GitHub's support determined the root of the issue right away: Two-factor authorization.

To use GitHub over the shell with https, create an OAuth token. As the page notes, I did have to remove my username and password credentials from Keychain but with osx-keychain in place, the token is stored as the password and things work exactly as they would over https without two-factor authorization in place.

Formula to determine brightness of RGB color

Interestingly, this formulation for RGB=>HSV just uses v=MAX3(r,g,b). In other words, you can use the maximum of (r,g,b) as the V in HSV.

I checked and on page 575 of Hearn & Baker this is how they compute "Value" as well.

From Hearn&Baker pg 319

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

I had same issue in Android Studio 3. (the project was open) so I closed the current project and the IDE automatically prompted to download the latest components. once its done everything was working correctly.

Error after upgrading pip: cannot import name 'main'

Please run the following commands to do the fix. After running python3 -m pip install --upgrade pip, please run the following command.

hash -r pip

Source: https://github.com/pypa/pip/issues/5221

Centering text in a table in Twitter Bootstrap

I had the same problem and a better way to solve it without using !important was defining the following in my CSS:

table th.text-center, table td.text-center { 
    text-align: center;
}

That way the specifity of the text-center class works correctly in tables.

How to serialize SqlAlchemy result to JSON?

While the original question goes back awhile, the number of answers here (and my own experiences) suggest it's a non-trivial question with a lot of different approaches of varying complexity with different trade-offs.

That's why I built the SQLAthanor library that extends SQLAlchemy's declarative ORM with configurable serialization/de-serialization support that you might want to take a look at.

The library supports:

  • Python 2.7, 3.4, 3.5, and 3.6.
  • SQLAlchemy versions 0.9 and higher
  • serialization/de-serialization to/from JSON, CSV, YAML, and Python dict
  • serialization/de-serialization of columns/attributes, relationships, hybrid properties, and association proxies
  • enabling and disabling of serialization for particular formats and columns/relationships/attributes (e.g. you want to support an inbound password value, but never include an outbound one)
  • pre-serialization and post-deserialization value processing (for validation or type coercion)
  • a pretty straightforward syntax that is both Pythonic and seamlessly consistent with SQLAlchemy's own approach

You can check out the (I hope!) comprehensive docs here: https://sqlathanor.readthedocs.io/en/latest

Hope this helps!

How to remove the hash from window.location (URL) with JavaScript without page refresh?

<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("?"));
    window.history.replaceState({}, document.title, clean_uri);
}
</script>

put this code on head section

Using :focus to style outer div?

You can tab between div tags. Just add a tab index to the div. It's best to use jQuery and CSS classes to solve this problem. Here's a working sample tested in IE, Firefox, and Chrome (Latest versions... didn't test older).

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            var divParentIdFocus;
            var divParentIdUnfocus = null;

            $(document).ready(function() {              

                    $("div").focus(function() {
                        //$(this).attr("class", "highlight");
                        var curDivId = $(this).attr("id");

                        // This Check needs to be performed when/if div regains focus
                        // from child element.
                        if (divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }

                        divParentIdFocus = curDivId;
                    });


                    $("textarea").focus(function(){
                        var curDivId = $(this).closest("div").attr("id");

                        if(divParentIdFocus != curDivId){
                            divParentIdUnfocus = divParentIdFocus;
                            divParentIdFocus = curDivId;
                            refreshHighlight();
                        }
                    });

                    $("#div1").focus();
            });

            function refreshHighlight()
            {
                if(divParentIdUnfocus != null){
                    $("#" +divParentIdUnfocus).attr("class", "noHighlight");
                    divParentIdUnfocus = null;
                }

                $("#" + divParentIdFocus).attr("class", "highlight");
            }
        </script>
        <style type="text/css">
            .highlight{
                background-color:blue;
                border: 3px solid black;
                font-weight:bold;
                color: white;
            }
            .noHighlight{           
            }
            div, h1,textarea, select { outline: none; }

        </style>
    <head>
    <body>
        <div id = "div1" tabindex="100">
            <h1>Div 1</h1> <br />
            <textarea rows="2" cols="25" tabindex="101">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="102">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="103">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="104">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div2" tabindex="200">
            <h1>Div 2</h1> <br />
            <textarea rows="2" cols="25" tabindex="201">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="202">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="203">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="204">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div3" tabindex="300">
            <h1>Div 3</h1> <br />
            <textarea rows="2" cols="25" tabindex="301">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="302">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="303">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="304">~Your Text Here~</textarea> <br />
        </div>
        <div id = "div4" tabindex="400">
            <h1>Div 4</h1> <br />
            <textarea rows="2" cols="25" tabindex="401">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="402">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="403">~Your Text Here~</textarea> <br />
            <textarea rows="2" cols="25" tabindex="404">~Your Text Here~</textarea> <br />
        </div>      
    </body>
</html>

Configuring RollingFileAppender in log4j

Toolbear74 is right log4j.XML is required. In order to get the XML to validate the <param> tags need to be BEFORE the <rollingPolicy> I suggest setting a logging threshold <param name="threshold" value="info"/>

When Creating a Log4j.xml file don't forget to to copy the log4j.dtd into the same location.

Here is an example:

<?xml version="1.0" encoding="windows-1252"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<!-- Daily Rolling File Appender that compresses old files -->
  <appender name="file" class="org.apache.log4j.rolling.RollingFileAppender" >
     <param name="threshold" value="info"/>
     <rollingPolicy name="file"  
                      class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" 
               value="${catalina.base}/logs/myapp.log.%d{yyyy-MM-dd}.gz"/>
        <param name="ActiveFileName" value="${catalina.base}/logs/myapp.log"/>
     </rollingPolicy>
     <layout class="org.apache.log4j.EnhancedPatternLayout" >
        <param name="ConversionPattern" 
               value="%d{ISO8601} %-5p - %-26.26c{1} - %m%n" />
    </layout>
  </appender>

  <root>
    <priority value="debug"></priority>
    <appender-ref ref="file" />
  </root>
</log4j:configuration>

Considering that your setting a FileNamePattern and an ActiveFileName I think that setting a File property is redundant and possibly even erroneous

Try renaming your log4j.properties and dropping in a log4j.xml similar to my example and see what happens.

How to consume REST in Java

The code below will help to consume rest api via Java. URL - end point rest If you dont need any authentication you dont need to write the authStringEnd variable

The method will return a JsonObject with your response

public JSONObject getAllTypes() throws JSONException, IOException {
        String url = "/api/atlas/types";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        javax.ws.rs.client.Client client = ClientBuilder.newClient();
        WebTarget webTarget = client.target(host + url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);

        Response response = invocationBuilder.get();
        String output = response.readEntity(String.class
        );

        System.out.println(response.toString());
        JSONObject obj = new JSONObject(output);

        return obj;
    }

Python: Append item to list N times

Itertools repeat combined with list extend.

from itertools import repeat
l = []
l.extend(repeat(x, 100))

Necessary to add link tag for favicon.ico?

To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:

<link rel="icon" href="_/img/favicon.png">

This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">.

To learn more about using other file types like PNG check out this question.

For cache busting purposes:
Add a query string to the path for cache-busting purposes:

<link rel="icon" href="/favicon.ico?v=1.1"> 

Favicons are very heavily cached and this a great way to ensure a refresh.


Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link for it.


Footnote about rel="icon":
As indicated by @Semanino's answer, using rel="shortcut icon" is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon" instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel value of shortcut isn't a valid option.

'uint32_t' does not name a type

I also encountered the same problem on Mac OSX 10.6.8 and unfortunately adding #include <stdint.h> or <cstdint.h> to the corresponding file did not solve my problem. However, after more search, I found this solution advicing to add #include <sys/types.h> which worked well for me!

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

How do you get the current project directory from C# code when creating a custom MSBuild task?

If a project is running on an IIS express, the Environment.CurrentDirectory could point to where IIS Express is located ( the default path would be C:\Program Files (x86)\IIS Express ), not to where your project resides.


This is probably the most suitable directory path for various kinds of projects.

AppDomain.CurrentDomain.BaseDirectory

This is the MSDN definition.

Gets the base directory that the assembly resolver uses to probe for assemblies.

Convert comma separated string of ints to int array

This has been asked before. .Net has a built-in ConvertAll function for converting between an array of one type to an array of another type. You can combine this with Split to separate the string to an array of strings

Example function:

 static int[] ToIntArray(this string value, char separator)
 {
     return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
 }

Taken from here

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

Cannot assign requested address - possible causes?

Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:

$sock = @stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);

It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig.

How to scale down a range of numbers with a known min and max value

Here's how I understand it:


What percent does x lie in a range

Let's assume you have a range from 0 to 100. Given an arbitrary number from that range, what "percent" from that range does it lie in? This should be pretty simple, 0 would be 0%, 50 would be 50% and 100 would be 100%.

Now, what if your range was 20 to 100? We cannot apply the same logic as above (divide by 100) because:

20 / 100

doesn't give us 0 (20 should be 0% now). This should be simple to fix, we just need to make the numerator 0 for the case of 20. We can do that by subtracting:

(20 - 20) / 100

However, this doesn't work for 100 anymore because:

(100 - 20) / 100

doesn't give us 100%. Again, we can fix this by subtracting from the denominator as well:

(100 - 20) / (100 - 20)

A more generalized equation for finding out what % x lies in a range would be:

(x - MIN) / (MAX - MIN)

Scale range to another range

Now that we know what percent a number lies in a range, we can apply it to map the number to another range. Let's go through an example.

old range = [200, 1000]
new range = [10, 20]

If we have a number in the old range, what would the number be in the new range? Let's say the number is 400. First, figure out what percent 400 is within the old range. We can apply our equation above.

(400 - 200) / (1000 - 200) = 0.25

So, 400 lies in 25% of the old range. We just need to figure out what number is 25% of the new range. Think about what 50% of [0, 20] is. It would be 10 right? How did you arrive at that answer? Well, we can just do:

20 * 0.5 = 10

But, what about from [10, 20]? We need to shift everything by 10 now. eg:

((20 - 10) * 0.5) + 10

a more generalized formula would be:

((MAX - MIN) * PERCENT) + MIN

To the original example of what 25% of [10, 20] is:

((20 - 10) * 0.25) + 10 = 12.5

So, 400 in the range [200, 1000] would map to 12.5 in the range [10, 20]


TLDR

To map x from old range to new range:

OLD PERCENT = (x - OLD MIN) / (OLD MAX - OLD MIN)
NEW X = ((NEW MAX - NEW MIN) * OLD PERCENT) + NEW MIN

ModelState.AddModelError - How can I add an error that isn't for a property?

Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

About list

First a very important point, from which everything will follow (I hope).

In ordinary Python, list is not special in any way (except having cute syntax for constructing, which is mostly a historical accident). Once a list [3,2,6] is made, it is for all intents and purposes just an ordinary Python object, like a number 3, set {3,7}, or a function lambda x: x+5.

(Yes, it supports changing its elements, and it supports iteration, and many other things, but that's just what a type is: it supports some operations, while not supporting some others. int supports raising to a power, but that doesn't make it very special - it's just what an int is. lambda supports calling, but that doesn't make it very special - that's what lambda is for, after all:).

About and

and is not an operator (you can call it "operator", but you can call "for" an operator too:). Operators in Python are (implemented through) methods called on objects of some type, usually written as part of that type. There is no way for a method to hold an evaluation of some of its operands, but and can (and must) do that.

The consequence of that is that and cannot be overloaded, just like for cannot be overloaded. It is completely general, and communicates through a specified protocol. What you can do is customize your part of the protocol, but that doesn't mean you can alter the behavior of and completely. The protocol is:

Imagine Python interpreting "a and b" (this doesn't happen literally this way, but it helps understanding). When it comes to "and", it looks at the object it has just evaluated (a), and asks it: are you true? (NOT: are you True?) If you are an author of a's class, you can customize this answer. If a answers "no", and (skips b completely, it is not evaluated at all, and) says: a is my result (NOT: False is my result).

If a doesn't answer, and asks it: what is your length? (Again, you can customize this as an author of a's class). If a answers 0, and does the same as above - considers it false (NOT False), skips b, and gives a as result.

If a answers something other than 0 to the second question ("what is your length"), or it doesn't answer at all, or it answers "yes" to the first one ("are you true"), and evaluates b, and says: b is my result. Note that it does NOT ask b any questions.

The other way to say all of this is that a and b is almost the same as b if a else a, except a is evaluated only once.

Now sit for a few minutes with a pen and paper, and convince yourself that when {a,b} is a subset of {True,False}, it works exactly as you would expect of Boolean operators. But I hope I have convinced you it is much more general, and as you'll see, much more useful this way.

Putting those two together

Now I hope you understand your example 1. and doesn't care if mylist1 is a number, list, lambda or an object of a class Argmhbl. It just cares about mylist1's answer to the questions of the protocol. And of course, mylist1 answers 5 to the question about length, so and returns mylist2. And that's it. It has nothing to do with elements of mylist1 and mylist2 - they don't enter the picture anywhere.

Second example: & on list

On the other hand, & is an operator like any other, like + for example. It can be defined for a type by defining a special method on that class. int defines it as bitwise "and", and bool defines it as logical "and", but that's just one option: for example, sets and some other objects like dict keys views define it as a set intersection. list just doesn't define it, probably because Guido didn't think of any obvious way of defining it.

numpy

On the other leg:-D, numpy arrays are special, or at least they are trying to be. Of course, numpy.array is just a class, it cannot override and in any way, so it does the next best thing: when asked "are you true", numpy.array raises a ValueError, effectively saying "please rephrase the question, my view of truth doesn't fit into your model". (Note that the ValueError message doesn't speak about and - because numpy.array doesn't know who is asking it the question; it just speaks about truth.)

For &, it's completely different story. numpy.array can define it as it wishes, and it defines & consistently with other operators: pointwise. So you finally get what you want.

HTH,

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

Remove ALL white spaces from text

Regex for remove white space

\s+

_x000D_
_x000D_
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

or

[ ]+

_x000D_
_x000D_
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

Remove all white space at begin of string

^[ ]+

_x000D_
_x000D_
var str = "    Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

remove all white space at end of string

[ ]+$

_x000D_
_x000D_
var str = "Visit Microsoft!      ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
_x000D_
_x000D_
_x000D_

How do I get the directory that a program is running from?

Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.

For example:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv) {
    char the_path[256];

    getcwd(the_path, 255);
    strcat(the_path, "/");
    strcat(the_path, argv[0]);

    printf("%s\n", the_path);

    return 0;
}

When run, it outputs:

jeremy@jeremy-desktop:~/Desktop$ ./test
/home/jeremy/Desktop/./test

Where is Maven's settings.xml located on Mac OS?

It doesn't exist at first. You have to create it in your home folder, /Users/usename/.m2/ (or ~/.m2)

For example :

alt text

make div's height expand with its content

You can use CSS Grid Layout. Support is rather wide at the moment: check it on caniuse.

Here is the example on jsfiddle. Also example with tons of text stuff.

HTML code:

<div class="container">
  <div class="header">
   Header
  </div>
  <div class="content">
   Content
  </div>
  <div class="footer">
   Footer
  </div>
</div>

CSS Code:

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}

.container {
  width: 100%;
  height: 100%;

  display: grid;
  grid-template-rows: 100px auto 150px;
  grid-template-columns: auto;
}
// style stuff

Bootstrap 3: Offset isn't working?

There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.

To get the result I believe you are looking for try this:

<div class="container">
    <div class="row">
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
      <div class="col-sm-4 col-md-12">
        <p>On small screen there are 3 rows, and on a medium screen 1 row</p>
      </div>
    </div>
  </div>

Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.

Hope this helps.

Get element by id - Angular2

(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

Jenkins CI: How to trigger builds on SVN commit

You need to require only one plugin which is the Subversion plugin.

Then simply, go into Jenkins ? job_name ? Build Trigger section ? (i) Trigger build remotely (i.e., from scripts) Authentication token: Token_name

Go to the SVN server's hooks directory, and then after fire the below commands:

  1. cp post-commit.tmpl post-commit
  2. chmod 777 post-commit
  3. chown -R www-data:www-data post-commit
  4. vi post-commit

    Note: All lines should be commented Add the below line at last

Syntax (for Linux users):

/usr/bin/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name

Syntax (for Windows user):

C:/curl_for_win/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name

android.app.Application cannot be cast to android.app.Activity

in case your project use dagger, and then this error show up you can add this at android manifest

   <application
        ...
        android: name = ".BaseApplication"
        ...> ...

Query for array elements inside JSON type

Create a table with column as type json

CREATE TABLE friends ( id serial primary key, data jsonb);

Now let's insert json data

INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');

Now let's make some queries to fetch data

select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;

You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])

    name    |            work            
------------+----------------------------
 "Arya"     | ["Improvements", "Office"]
 "Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)

Now to retrieve only the values just use ->>

select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';

Why should I use a container div in HTML?

Well,

The container div is very good to have, because if You want the site centered, You just can't do it just with body or html... But You can, with divs. Why container? Its usually used, just because the code itselve has to be clean and readable. So that is container... It contains all website, in case You want to mess with it around :)

Good luck

How to check null objects in jQuery

In jQuery 1.4 you get the $.isEmptyObject function, but if you are forced to use an older version of jQ like us poor Drupal developers just steal use this code:

// This is a function similar to the jQuery 1.4 $.isEmptyObject.
function isObjectEmpty(obj) {
  for ( var name in obj ) {
    return false;
  }
  return true;
}

Use it like:

console.log(isObjectEmpty(the_object)); // Returns true or false.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I had a git conflict left in my workspace.xml i.e.

<<<<———————HEAD

which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.

Checking for the correct number of arguments

You can check the total number of arguments which are passed in command line with "$#" Say for Example my shell script name is hello.sh

sh hello.sh hello-world
# I am passing hello-world as argument in command line which will b considered as 1 argument 
if [ $# -eq 1 ] 
then
    echo $1
else
    echo "invalid argument please pass only one argument "
fi

Output will be hello-world

How can I set the 'backend' in matplotlib in Python?

FYI, I found I needed to put matplotlib.use('Agg') first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting

import matplotlib
matplotlib.use('Agg')

at the top of my master test script. I didn't have to touch any other files.

Detach (move) subdirectory into separate Git repository

I'm sure git subtree is all fine and wonderful, but my subdirectories of git managed code that I wanted to move was all in eclipse. So if you're using egit, it's painfully easy. Take the project you want to move and team->disconnect it, and then team->share it to the new location. It will default to trying to use the old repo location, but you can uncheck the use-existing selection and pick the new place to move it. All hail egit.

Spring application context external properties?

This blog can help you. The trick is to use SpEL (spring expression language) to read the system properties like user.home, to read user home directory using SpEL you could use
#{ systemProperties['user.home']} expression inside your bean elements. For example to access your properties file stored in your home directory you could use the following in your PropertyPlaceholderConfigurer, it worked for me.

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:#{ systemProperties['user.home']}/ur_folder/settings.properties</value>
    </property>
</bean>

Simple jQuery, PHP and JSONP example?

More Suggestion

JavaScript:

$.ajax({
        url: "http://FullUrl",
        dataType: 'jsonp',
        success: function (data) {

            //Data from the server in the in the variable "data"
            //In the form of an array

        }

});

PHP CallBack:

<?php

$array = array(
     '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
     '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);

if(isset ($_GET['callback']))
{
    header("Content-Type: application/json");

    echo $_GET['callback']."(".json_encode($array).")";

}
?>

Sending POST parameters with Postman doesn't work, but sending GET parameters does

I faced the same issue in PostMan and Advance REST Client both. I checked through fiddler and found that my request payload is not converted into JSON format.

I am passing my data in Body as x-www-form-urlencoded enter image description here

You can fix it by using Content-Type as application/x-www-form-urlencoded in request header. enter image description here

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

32bit windows has a 2GB process memory limit. The /3GB boot option others have mentioned will make this 3GB with just 1gb remaining for OS kernel use. Realistically if you want to use more than 2GB without hassle then a 64bit OS is required. This also overcomes the problem whereby although you may have 4GB of physical RAM, the address space requried for the video card can make a sizeable chuck of that memory unusable - usually around 500MB.

.NET Global exception handler in console application

No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

How to remove \xa0 from string in Python?

try this:

string.replace('\\xa0', ' ')

Order discrete x scale by frequency/value

The best way for me was using vector with categories in order I need as limits parameter to scale_x_discrete. I think it is pretty simple and straightforward solution.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))

enter image description here

show distinct column values in pyspark dataframe: python

you could do

distinct_column = 'somecol' 

distinct_column_vals = df.select(distinct_column).distinct().collect()
distinct_column_vals = [v[distinct_column] for v in distinct_column_vals]

Jersey Exception : SEVERE: A message body reader for Java class

To make it work you only need two things. Check if you are missing:

  1. First of all, you need @XmlRootElement annotation for your object class/entity.
  2. You need to add dependency for jersey-json if you are missing.For your reference I added this dependency into my pom.xml.

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.17.1</version>
    </dependency>
    

What is the difference between id and class in CSS, and when should I use them?

A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot. An example would be if you wanted to give all the paragraphs on your webpage the same styling, you would use classes.

Standards specify that any given ID name can only be referenced once within a page or document. Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.

Array as session variable

session_start();          //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id'];   //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);   
//print_r($_SESSION['student']);


<table class="table">     //html part
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>

    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>

Javac is not found

do this: 1. run CMD (WIN+R then type in CMD) 2. Type this:

set PATH=%PATH%; java installation path\bin

Replace "java installation path" with the directory JDK is installed in, such as C:\Program Files (x86)\Java. Be sure to add the \bin after the JDK directory, because this points to "javac" and "java" (BIN stands for "binaries")

This way, you can run the Java compiler from anywhere. It is impossible to CD to the JDK directory because it has a space in Program Files, and DOS will not let you CD to these directories.

How to use ConfigurationManager

Go to tools >> nuget >> console and type:

Install-Package System.Configuration.ConfigurationManager 

If you want a specific version:

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

Your ConfigurationManager dll will now be imported and the code will begin to work.

In Chart.js set chart title, name of x axis and y axis?

In Chart.js version 2.0, it is possible to set labels for axes:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }     
}

See Labelling documentation for more details.

Get multiple elements by Id

If you can change the markup, you might want to use class instead.

<!-- html -->
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

// javascript
var elements = document.getElementsByClassName("test");
var names = '';
for(var i=0; i<elements.length; i++) {
    names += elements[i].name;
}
document.write(names);

jsfiddle demo

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

horizontal line and right way to code it in html, css

I'd go for semantic markup, use an <hr/>.

Unless it's just a border what you want, then you can use a combination of padding, border and margin, to get the desired bound.

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

How can I get dictionary key as variable directly in Python (not by searching from value)?

Iterate over dictionary (i) will return the key, then using it (i) to get the value

for i in D:
    print "key: %s, value: %s" % (i, D[i])

Dynamic array in C#

You can do this with dynamic objects:

var dynamicKeyValueArray = new[] { new {Key = "K1", Value = 10}, new {Key = "K2", Value = 5} };

foreach(var keyvalue in dynamicKeyValueArray)
{
    Console.Log(keyvalue.Key);
    Console.Log(keyvalue.Value);
}

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

Add a header to your request to set content type to application/json

curl -H 'Content-Type: application/json' -s -XPOST http://your.domain.com/ -d YOUR_JSON_BODY

this way spring knows how to parse the content.

Insert line at middle of file with Python?

If you want to search a file for a substring and add a new text to the next line, one of the elegant ways to do it is the following:

import fileinput
for line in fileinput.FileInput(file_path,inplace=1):
    if "TEXT_TO_SEARCH" in line:
        line=line.replace(line,line+"NEW_TEXT")
    print line,

copy-item With Alternate Credentials

Here is a post where someone got it to work. It looks like it requires a registry change.

How to query values from xml nodes?

This works, been tested...

SELECT  n.c.value('OrganizationReportReferenceIdentifier[1]','varchar(128)') AS 'OrganizationReportReferenceNumber',  
        n.c.value('(OrganizationNumber)[1]','varchar(128)') AS 'OrganizationNumber'
FROM    Batches t
Cross   Apply RawXML.nodes('/GrobXmlFile/Grob/ReportHeader') n(c)  

Rerender view on browser resize with React

As of React 16.8 you can use Hooks!

/* globals window */
import React, { useState, useEffect } from 'react'
import _debounce from 'lodash.debounce'

const Example = () => {
  const [width, setWidth] = useState(window.innerWidth)

  useEffect(() => {
    const handleResize = _debounce(() => setWidth(window.innerWidth), 100)

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    }
  }, [])

  return <>Width: {width}</>
}

What to use now Google News API is deprecated?

Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431

Also, it sounds like they are building a replacement... but it's going to cost you.

I'd say, go to a different service. I think bing has a news API.

You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625

IIS - 401.3 - Unauthorized

If you are working with Application Pool authentication (instead of IUSR), which you should, then this list of checks by Jean Sun is the very best I could find to deal with 401 errors in IIS:


Open IIS Manager, navigate to your website or application folder where the site is deployed to.

  1. Open Advanced Settings (it's on the right hand Actions pane).
  2. Note down the Application Pool name then close this window
  3. Double click on the Authentication icon to open the authentication settings
  4. Disable Windows Authentication
  5. Right click on Anonymous Authentication and click Edit
  6. Choose the Application pool identity radio button the click OK
  7. Select the Application Pools node from IIS manager tree on left and select the Application Pool name you noted down in step 3
  8. Right click and select Advanced Settings
  9. Expand the Process Model settings and choose ApplicationPoolIdentityfrom the "Built-in account" drop down list then click OK.
  10. Click OK again to save and dismiss the Application Pool advanced settings page
  11. Open an Administrator command line (right click on the CMD icon and select "Run As Administrator". It'll be somewhere on your start menu, probably under Accessories.
  12. Run the following command:

    icacls <path_to_site> /grant "IIS APPPOOL\<app_pool_name>"(CI)(OI)(M)
    

    For example:

    icacls C:\inetpub\wwwroot\mysite\ /grant "IIS APPPOOL\DEFAULTAPPPOOL":(CI)(OI)(M)
    

Especially steps 5. & 6. are often overlooked and rarely mentioned on the web.

Determine if an element has a CSS class with jQuery

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:

element.classList.contains('your-class-name')

What is the difference between Swing and AWT?

  • swing component provide much flexible user interface because it follow model view controller(mvc).
  • awt is not mvc based.
  • swing works faster.
  • awt does not work faster.
  • swing components are light weight.
  • awt components are heavy weight.
  • swing occupies less memory space.
  • awt occupies more memory space.
  • swing component is platform independent.
  • awt is platform dependent.
  • swing require javax.swing package.
  • awt require javax.awt package.

How to get selected option using Selenium WebDriver with Java

In Selenium Python it is:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

def get_selected_value_from_drop_down(self):
    try:
        select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
        return select.first_selected_option.get_attribute("value")
    except NoSuchElementException, e:
        print "Element not found "
        print e

What's the difference between commit() and apply() in SharedPreferences

  • commit() is synchronously, apply() is asynchronous

  • apply() is void function.

  • commit() returns true if the new values were successfully written to persistent storage.

  • apply() guarantees complete before switching states , you don't need to worry about Android component lifecycles

If you dont use value returned from commit() and you're using commit() from main thread, use apply() instead of commit()

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

How to maintain a Unique List in Java?

I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?

If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.

Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

I was forgetting to return the other observable in pipe(switchMap(

this.dataService.getPerson(personId).pipe(
  switchMap(person => {
     //this.dataService.getCompany(person.companyId); // return missing
     return this.dataService.getCompany(person.companyId);
  })
)

Find the smallest positive integer that does not occur in a given sequence

I tried it with Swift and got 100%.

public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
if A.count == 0 {
    return 1
}
A = A.sorted()
if A[A.count - 1] <= 0 {
    return 1
}

var temp = 1

for numb in A {

    if numb > 0 {

        if numb == temp {
            temp += 1
        }else if numb != (temp - 1) {
            return temp
        }
    }
}

return temp

}

Calculating the angle between the line defined by two points

Had a need for similar functionality myself, so after much hair pulling I came up with the function below

/**
 * Fetches angle relative to screen centre point
 * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
 * 
 * @param screenPoint
 * @return angle in degress from 0-360.
 */
public double getAngle(Point screenPoint) {
    double dx = screenPoint.getX() - mCentreX;
    // Minus to correct for coord re-mapping
    double dy = -(screenPoint.getY() - mCentreY);

    double inRads = Math.atan2(dy, dx);

    // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
    if (inRads < 0)
        inRads = Math.abs(inRads);
    else
        inRads = 2 * Math.PI - inRads;

    return Math.toDegrees(inRads);
}

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

Use -notlike to filter out multiple strings in PowerShell

Yep, but you have to put the array first in the expression:

... | where { @("user1","user2") -notlike $_.username }

-Oisin

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

The SQLite command line utility has a .schema TABLENAME command that shows you the create statements.

How to use conditional breakpoint in Eclipse?

Make a normal breakpoint on the doIt(tablist[i]); line

Right-click -> Properties

Check 'Conditional'

Enter tablist[i].equalsIgnoreCase("LEADDELEGATES")

“Unable to find manifest signing certificate in the certificate store” - even when add new key

It is not enough to manually add keys to the Windows certificate store. The certificate only contains the signed public key. You must also import the private key that is associated with the public key in the certificate. A .pfx file contains both public and private keys in a single file. That is what you need to import.

How to add elements of a Java8 stream into an existing List

I would concatenate the old list and new list as streams and save the results to destination list. Works well in parallel, too.

I will use the example of accepted answer given by Stuart Marks:

List<String> destList = Arrays.asList("foo");
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");

destList = Stream.concat(destList.stream(), newList.stream()).parallel()
            .collect(Collectors.toList());
System.out.println(destList);

//output: [foo, 0, 1, 2, 3, 4, 5]

Hope it helps.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Requirements files use an expanded pip format, which is only useful if you need to complement your setup.py with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of pip freeze to freeze the entire package set to known-working versions. If you don't need the extra constraints, use only a setup.py. If you feel like you really need to ship a requirements.txt anyway, you can make it a single line:

.

It will be valid and refer exactly to the contents of the setup.py that is in the same directory.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

Java - Convert String to valid URI object

I'm going to add one suggestion here aimed at Android users. You can do this which avoids having to get any external libraries. Also, all the search/replace characters solutions suggested in some of the answers above are perilous and should be avoided.

Give this a try:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.

This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.

Detect and exclude outliers in Pandas data frame

My function for dropping outliers

def drop_outliers(df, field_name):
    distance = 1.5 * (np.percentile(df[field_name], 75) - np.percentile(df[field_name], 25))
    df.drop(df[df[field_name] > distance + np.percentile(df[field_name], 75)].index, inplace=True)
    df.drop(df[df[field_name] < np.percentile(df[field_name], 25) - distance].index, inplace=True)

How to select option in drop down using Capybara

For some reason it didn't work for me. So I had to use something else.

select "option_name_here", :from => "organizationSelect"

worked for me.

Can an AJAX response set a cookie?

For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

Reference member variables as class members

Is there a name to describe this idiom?

In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const, then the class can change the state of an object that lives outside of it.

Is this generally good practice? Are there any pitfalls to this approach?

It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.

Best way to get value from Collection by index

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = World
elem = Hello
myCollection.toArray()[0] = World

whilst:

myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = Hello
elem = World
myCollection.toArray()[0] = Hello

Why do you want to do this? Could you not just iterate over the collection?

Clone only one branch

From the announcement Git 1.7.10 (April 2012):

  • git clone learned --single-branch option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.

Git actually allows you to clone only one branch, for example:

git clone -b mybranch --single-branch git://sub.domain.com/repo.git

Note: Also you can add another single branch or "undo" this action.

The ResourceConfig instance does not contain any root resource classes

Well, it's a little late to reply. I have faced the same problem and my Google searches were in vain. However, I managed to find what the problem was. There might be many reasons for getting this error but I got the error due to the following and I wanted to share this with my fellow developers.

  1. I previously used Jersey 1.3 and I was getting this error. But when I upgraded the jars to the latest version of Jersey, this issue was resolved.
  2. Another instance in which I got this error was when I was trying to deploy my service into JBoss by building a war file. I made the mistake of including the Java files in the .war instead of java classes.

How to create a timer using tkinter?

from tkinter import *
import time
tk=Tk()
def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        label1.config(text=t,font='times 25')
    tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()

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

You have more going on than you said. I ran the following expanded test from your example:

public class test {

    public static void main(String[] args) {
        Object[][] someArray = new Object[5][];
        someArray[0] = new Object[10];
        someArray[1] = null;
        someArray[2] = new Object[1];
        someArray[3] = null;
        someArray[4] = new Object[5];

        for (int i=0; i<=someArray.length-1; i++) {
            if (someArray[i] != null) {
                System.out.println("not null");
            } else {
                System.out.println("null");
            }
        }
    }
}

and got the expected output:

$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null

Are you possibly trying to check the lengths of someArray[index]?

how to save DOMPDF generated content to file?

<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

If you want to use some variable, you may use this way:

String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

CSS strikethrough different color from text?

If you do not care about internet explorer\edge, then simplest way to achieve different color for strike-through would be to use CSS property: text-decoration-color in conjunction with text-decoration:line-through;

.yourClass {
    text-decoration: line-through !important;
    text-decoration-color: red !important;
}

-- Does not work with Edge\Internet Explorer

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Getting Lat/Lng from Google marker

var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();

More information can be found at Google Maps API - LatLng

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

Genymotion Android emulator - adb access?

You can get IP Genymotion Virtual Device Manager,then use the command like this

adb connect your ip

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

Simple insertion when table column sequence is known:

    Insert into Table1
    values(1,2,...)

Simple insertion mentioning column:

    Insert into Table1(col2,col4)
    values(1,2)

Bulk insertion when number of selected columns of a table(#table2) are equal to insertion table(Table1)

    Insert into Table1 {Column sequence}
    Select * -- column sequence should be same.
       from #table2

Bulk insertion when you want to insert only into desired column of a table(table1):

    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
    Select Column1,Column2..desired column from #table2
       from #table2

Is there an equivalent for var_dump (PHP) in Javascript?

As the others said, you can use Firebug, and that will sort you out no worries on Firefox. Chrome & Safari both have a built-in developer console which has an almost identical interface to Firebug's console, so your code should be portable across those browsers. For other browsers, there's Firebug Lite.

If Firebug isn't an option for you, then try this simple script:

function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

I'd recommend against alerting each individual property: some objects have a LOT of properties and you'll be there all day clicking "OK", "OK", "OK", "O... dammit that was the property I was looking for".

MySQL Database won't start in XAMPP Manager-osx

Try running these two commands in the terminal:

  1. sudo killall mysqld sudo
  2. /Applications/XAMPP/xamppfiles/bin/mysql.server start

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Can I set text box to readonly when using Html.TextBoxFor?

In fact the answer of Brain Mains is almost correct:

@Html.TextBoxFor(model => model.RIF, new { value = @Model.RIF, @readonly = true })

How to implement a material design circular progress bar in android

Update

As of 2019 this can be easily achieved using ProgressIndicator, in Material Components library, used with the Widget.MaterialComponents.ProgressIndicator.Circular.Indeterminate style.

For more details please check Gabriele Mariotti's answer below.

Old implementation

Here is an awesome implementation of the material design circular intermediate progress bar https://gist.github.com/castorflex/4e46a9dc2c3a4245a28e. The implementation only lacks the ability add various colors like in inbox by android app but this does a pretty great job.

CSS Input field text color of inputted text

If you want the placeholder text to be red you need to target it specifically in CSS.

Write:

input::placeholder{
  color: #f00;
}

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP without providing a password

Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant

How to load a xib file in a UIView

For swift 3 & 4

let customView = Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView

Change event on select with knockout binding, how can I know if it is a real change?

Quick and dirty, utilizing a simple flag:

var bindingsApplied = false;

var ViewModel = function() {
    // ...

    this.permissionChanged = function() {
        // ignore, if flag not set
        if (!flag) return;

        // ...
    };
};

ko.applyBindings(new ViewModel());
bindingsApplied = true; // done with the initial population, set flag to true

If this doesn't work, try wrapping the last line in a setTimeout() - events are async, so maybe the last one is still pending when applyBindings() already returned.

Enzyme - How to access and set <input> value?

None of the solutions above worked for me because I was using Formik and I needed to mark the field "touched" along with changing the field value. Following code worked for me.

const emailField = orderPageWrapper.find('input[name="email"]')

emailField.simulate('focus')
emailField.simulate('change', { target: { value: '[email protected]', name: 'email' } })
emailField.simulate('blur')

Delete last char of string

string.Join is better, but if you really want a LINQ ForEach:

var strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    if(strgroupids != string.Empty){
        strgroupids += ",";
    }

    strgroupids += g;
});

Some notes:

  • string.Join and foreach are both better than this, vastly slower, approach
  • No need to remove the last , since it's never appended
  • The increment operator (+=) is handy for appending to strings
  • .ToString() is unnecessary as it is called automatically when concatenating non-strings
  • When handling large strings, StringBuilder should be considered instead of concatenating strings

View RDD contents in Python Spark?

This error is because print isn't a function in Python 2.6.

You can either define a helper UDF that performs the print, or use the __future__ library to treat print as a function:

>>> from operator import add
>>> f = sc.textFile("README.md")
>>> def g(x):
...     print x
...
>>> wc.foreach(g)

or

>>> from __future__ import print_function
>>> wc.foreach(print)

However, I think it would be better to use collect() to bring the RDD contents back to the driver, because foreach executes on the worker nodes and the outputs may not necessarily appear in your driver / shell (it probably will in local mode, but not when running on a cluster).

>>> for x in wc.collect():
...     print x

Get individual query parameters from Uri

I had to do this for a modern windows app. I used the following:

public static class UriExtensions
{
    private static readonly Regex _regex = new Regex(@"[?&](\w[\w.]*)=([^?&]+)");

    public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
    {
        var match = _regex.Match(uri.PathAndQuery);
        var paramaters = new Dictionary<string, string>();
        while (match.Success)
        {
            paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
            match = match.NextMatch();
        }
        return paramaters;
    }
}

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en

adb remount permission denied, but able to access super user in shell -- android

Try

adb root
adb remount

to start the adb demon as root and ensure partitions are mounted in read-write mode (the essential part is adb root). After pushing, revoke root permissions again using:

adb unroot

Cause of No suitable driver found for

"no suitable driver" usually means that the syntax for the connection URL is incorrect.

Max or Default?

litt late, but I had the same concern...

Rephrasing your code from the original post, you want the max of the set S defined by

(From y In context.MyTable _
 Where y.MyField = value _
 Select y.MyCounter)

Taking in account your last comment

Suffice to say that I know I want 0 when there are no records to select from, which definitely has an impact on the eventual solution

I can rephrase your problem as: You want the max of {0 + S}. And it looks like the proposed solution with concat is semantically the right one :-)

var max = new[]{0}
          .Concat((From y In context.MyTable _
                   Where y.MyField = value _
                   Select y.MyCounter))
          .Max();

bitwise XOR of hex numbers in python

Whoa. You're really over-complicating it by a very long distance. Try:

>>> print hex(0x12ef ^ 0xabcd)
0xb922

You seem to be ignoring these handy facts, at least:

  • Python has native support for hexadecimal integer literals, with the 0x prefix.
  • "Hexadecimal" is just a presentation detail; the arithmetic is done in binary, and then the result is printed as hex.
  • There is no connection between the format of the inputs (the hexadecimal literals) and the output, there is no such thing as a "hexadecimal number" in a Python variable.
  • The hex() function can be used to convert any number into a hexadecimal string for display.

If you already have the numbers as strings, you can use the int() function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):

>>> print int("12ef", 16)
4874

So you can do two conversions, perform the XOR, and then convert back to hex:

>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922

ToList()-- does it create a new list?

I think that this is equivalent to asking if ToList does a deep or shallow copy. As ToList has no way to clone MyObject, it must do a shallow copy, so the created list contains the same references as the original one, so the code returns 5.

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

Error message: "'chromedriver' executable needs to be available in the path"

I see the discussions still talk about the old way of setting up chromedriver by downloading the binary and configuring the path manually.

This can be done automatically using webdriver-manager

pip install webdriver-manager

Now the above code in the question will work simply with below change,

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(ChromeDriverManager().install())

The same can be used to set Firefox, Edge and ie binaries.

Git: How to rebase to a specific commit?

I've used a mixture of solutions described above:

$ git branch temp <specific sha1>
$ git rebase --onto temp master topic
$ git branch -d temp

I found it much easier to read and understand. The accepted solution lead me to a merge conflict (too lazy to fix by hand):

$ git rebase temp
First, rewinding head to replay your work on top of it...
Applying: <git comment>
Using index info to reconstruct a base tree...
M       pom.xml
.git/rebase-apply/patch:10: trailing whitespace.
    <some code>
.git/rebase-apply/patch:17: trailing whitespace.
        <some other code>
warning: 2 lines add whitespace errors.
Falling back to patching base and 3-way merge...
Auto-merging pom.xml
CONFLICT (content): Merge conflict in pom.xml
error: Failed to merge in the changes.
Patch failed at 0001 <git comment>
The copy of the patch that failed is found in: .git/rebase-apply/patch

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

Confirmation before closing of tab/browser

Try this:

<script>
    window.onbeforeunload = function(e) {
       return 'Dialog text here.';
    };
</script>

more info here MDN.

How to implement the Android ActionBar back button?

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

in onCreated method for the new apis.

Android Studio - debug keystore

You can specify your own debug keystore if you wish. This solution also gives you the ability to store your keys outside of the project directory as well as enjoy automation in the signing process. Yes you can go to File -> Project Structure and assign signing keystores and passwords in the Signing tab but that will put plaintext entries into your gradle.build file which means your secrets might be disclosed (especially in repository commits). With this solution you get the control of using your own keystore and the magic of automation during debug and release builds.

1) Create a gradle.properties (if you don't already have one).

The location for this file depends on your OS:

   /home/<username>/.gradle/ (Linux)
   /Users/<username>/.gradle/ (Mac)
   C:\Users\<username>\.gradle (Windows)

2) Add an entry pointing to yourprojectname.properties file. (example for Windows)

yourprojectname.properties=c:\\Users\\<username>\\signing\\yourprojectname.properties

3) Create yourprojectname.properties file in the location you specified in Step 2 with the following information:

keystore=C:\\path\\to\\keystore\\yourapps.keystore
keystore.password=your_secret_password

4) Modify your gradle.build file to point to yourprojectname.properties file to use the variables.

if(project.hasProperty("yourprojectname.properties")
        && new File(project.property("yourprojectname.properties")).exists()) {

    Properties props = new Properties()
    props.load(new FileInputStream(file(project.property("yourprojectname.properties"))))

    android {
        signingConfigs {
            release {
                keyAlias 'release'
                keyPassword props['keystore.password']
                storeFile file(props['keystore'])
                storePassword props['keystore.password']
            }
            debug {
                keyAlias 'debug'
                keyPassword props['keystore.password']
                storeFile file(props['keystore'])
                storePassword props['keystore.password']
            }
        }
        compileSdkVersion 19
        buildToolsVersion "20.0.0"
        defaultConfig {
            applicationId "your.project.app"
            minSdkVersion 16
            targetSdkVersion 17
        }
        buildTypes {
            release {
            }
        }
    }

}

dependencies {
    ...
}

5) Enjoy! Now all of your keys will be outside of the root of the directory and yet you still have the joys of automation for each build.

If you get an error in your gradle.build file about the "props" variable it's because you are not executing the "android {}" block inside the very first if condition where the props variable gets assigned so just move the entire android{ ... } section into the condition in which the props variable is assigned then try again.

I pieced these steps together from the information found here and here.

Identifying country by IP address

Here is my solution in Python 3.x to return geo-location info given a dataframe containing IP Address(s); efficient parallelized application of function on vectorized pd.series/dataframe is the way to go.

Will contrast performance of two popular libraries to return location.

TLDR: use geolite2 method.

1. geolite2 package from geolite2 library

Input

# !pip install maxminddb-geolite2
import time
from geolite2 import geolite2
geo = geolite2.reader()
df_1 = train_data.loc[:50,['IP_Address']]

def IP_info_1(ip):
    try:
        x = geo.get(ip)
    except ValueError:   #Faulty IP value
        return np.nan
    try:
        return x['country']['names']['en'] if x is not None else np.nan
    except KeyError:   #Faulty Key value
        return np.nan

s_time = time.time()
# map IP --> country
#apply(fn) applies fn. on all pd.series elements
df_1['country'] = df_1.loc[:,'IP_Address'].apply(IP_info_1)
print(df_1.head(), '\n')
print('Time:',str(time.time()-s_time)+'s \n')

print(type(geo.get('48.151.136.76')))

Output

       IP_Address         country
0   48.151.136.76   United States
1    94.9.145.169  United Kingdom
2   58.94.157.121           Japan
3  193.187.41.186         Austria
4   125.96.20.172           China 

Time: 0.09906983375549316s 

<class 'dict'>

2. DbIpCity package from ip2geotools library

Input

# !pip install ip2geotools
import time
s_time = time.time()
from ip2geotools.databases.noncommercial import DbIpCity
df_2 = train_data.loc[:50,['IP_Address']]
def IP_info_2(ip):
    try:
        return DbIpCity.get(ip, api_key = 'free').country
    except:
        return np.nan
df_2['country'] = df_2.loc[:, 'IP_Address'].apply(IP_info_2)
print(df_2.head())
print('Time:',str(time.time()-s_time)+'s')

print(type(DbIpCity.get('48.151.136.76',api_key = 'free')))

Output

       IP_Address country
0   48.151.136.76      US
1    94.9.145.169      GB
2   58.94.157.121      JP
3  193.187.41.186      AT
4   125.96.20.172      CN

Time: 80.53318452835083s 

<class 'ip2geotools.models.IpLocation'>

A reason why the huge time difference could be due to the Data structure of the output, i.e direct subsetting from dictionaries seems way more efficient than indexing from the specicialized ip2geotools.models.IpLocation object.

Also, the output of the 1st method is dictionary containing geo-location data, subset respecitively to obtain needed info:

x = geolite2.reader().get('48.151.136.76')
print(x)

>>>
    {'city': {'geoname_id': 5101798, 'names': {'de': 'Newark', 'en': 'Newark', 'es': 'Newark', 'fr': 'Newark', 'ja': '??????', 'pt-BR': 'Newark', 'ru': '??????'}},

 'continent': {'code': 'NA', 'geoname_id': 6255149, 'names': {'de': 'Nordamerika', 'en': 'North America', 'es': 'Norteamérica', 'fr': 'Amérique du Nord', 'ja': '?????', 'pt-BR': 'América do Norte', 'ru': '???????? ???????', 'zh-CN': '???'}}, 

'country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'location': {'accuracy_radius': 1000, 'latitude': 40.7355, 'longitude': -74.1741, 'metro_code': 501, 'time_zone': 'America/New_York'}, 

'postal': {'code': '07102'}, 

'registered_country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'subdivisions': [{'geoname_id': 5101760, 'iso_code': 'NJ', 'names': {'en': 'New Jersey', 'es': 'Nueva Jersey', 'fr': 'New Jersey', 'ja': '?????????', 'pt-BR': 'Nova Jérsia', 'ru': '???-??????', 'zh-CN': '????'}}]}

How to substitute shell variables in complex text files

Looking, it turns out on my system there is an envsubst command which is part of the gettext-base package.

So, this makes it easy:

envsubst < "source.txt" > "destination.txt"

Note if you want to use the same file for both, you'll have to use something like moreutil's sponge, as suggested by Johnny Utahh: envsubst < "source.txt" | sponge "source.txt". (Because the shell redirect will otherwise empty the file before its read.)

Deactivate or remove the scrollbar on HTML

What I would try in this case is put this in the stylesheet

html, body{overflow:hidden;}

this way one disables the scrollbar, and as a cumulative effect they disable scrolling with the keyboard

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

This exact same error happened to me only when I tried to build my debug build type. The way I solved it was to change my google-services.json for my debug build type. My original field had a field called client_id and the value was android:com.example.exampleapp, and I just deleted the android: prefix and leave as com.example.exampleapp and after that my gradle build was successful.

Hope it helps!

EDIT

I've just added back the android: prefix in my google-services.json and it continued to work correctly. Not sure what happened exactly but I was able to solve my problem with the solution mentioned above.

How is length implemented in Java Arrays?

You're correct, length is a data member, not a method.

From the Arrays tutorial:

The length of an array is established when the array is created. After creation, its length is fixed.

How do you easily create empty matrices javascript?

Well, you can create an empty 1-D array using the explicit Array constructor:

a = new Array(9)

To create an array of arrays, I think that you'll have to write a nested loop as Marc described.

How does the vim "write with sudo" trick work?

The only problem with cnoremap w!! is that it replaces w with ! (and hangs until you type the next char) whenever you type w! at the : command prompt. Like when you want to actually force-save with w!. Also, even if it's not the first thing after :.

Therefore I would suggest mapping it to something like <Fn>w. I personally have mapleader = F1, so I'm using <Leader>w.

Converting strings to floats in a DataFrame

You can try df.column_name = df.column_name.astype(float). As for the NaN values, you need to specify how they should be converted, but you can use the .fillna method to do it.

Example:

In [12]: df
Out[12]: 
     a    b
0  0.1  0.2
1  NaN  0.3
2  0.4  0.5

In [13]: df.a.values
Out[13]: array(['0.1', nan, '0.4'], dtype=object)

In [14]: df.a = df.a.astype(float).fillna(0.0)

In [15]: df
Out[15]: 
     a    b
0  0.1  0.2
1  0.0  0.3
2  0.4  0.5

In [16]: df.a.values
Out[16]: array([ 0.1,  0. ,  0.4])

deleted object would be re-saved by cascade (remove deleted object from associations)

Another workaround

I completely agree with redochka and Nikos Paraskevopoulos. Mahmoud Saleh's answer get over the issue in some circumstances not every time. In my situation I really need Eager fetchtype. So as Stony mentioned above I just removed from a list which cantian the object too. Here is my code:

Rju entity

public class Rju extends AbstractCompany implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 4294142403795421252L;


    //this field just duplicates @Column(name="callname") and serves for mapping to Rju fullname field
    @Column(name = "fullname")
    private String namerju;
    @NotEmpty
    @Column(name = "briefname")
    private String briefname;

    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "otd")
    private Collection<Vstan> vStanCollection;

//  @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "rju", orphanRemoval = true)
    private Collection<Underrju> underRjuCollection;
.........
}

Underrju entity

public class Underrju extends AbstractCompany implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 2026147847398903848L;


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

    @NotNull
    @Valid
    @JoinColumn(name = "id_rju", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Rju rju;
......getters and setters..........
}

and my UnderrjuService

@Service("underrjuService")
@Transactional
public class UnderRjuServiceImpl implements UnderRjuService {

    @Autowired
    private UnderRjuDao underrjuDao;

    .............another methods........................
    @Override
    public void deleteUnderrjuById(int id) {
        Underrju underrju=underrjuDao.findById(id);
        Collection<Underrju> underrjulist=underrju.getRju().getUnderRjuCollection();
        if(underrjulist.contains(underrju)) {
            underrjulist.remove(underrju);
        }
        underrjuDao.delete(id);

    }
     .........................
}

jQuery find file extension (from string)

You can use a combination of substring and lastIndexOf

Sample

var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 

C# how to wait for a webpage to finish loading before continuing

Task method worked for me, except Browser.Task.IsCompleted has to be changed to PageLoaded.Task.IsCompleted.

Sorry I didnt add comment, that is because I need higher reputation to add comments.

docker : invalid reference format

Found that using docker-compose config reported what the problem was.

In my case, an override compose file with an entry that was overriding nothing.

AngularJS ng-style with a conditional expression

also this syntax for ternary operator will work:

  ng-style="<$scope.var><condition> ? {
        '<css-prop-1>':((<value>) / (<value2>)*100)+'%',
        '<css-prop-2>':'<string>'
      } : {
        '<css-prop-1>':'<string>',
        '<css-prop-2>':'<string>'
      }"

where <value> are $scope property values. In example:

ng-style="column.histograms.value=>0 ? 
  {
    'width':((column.histograms.value) / (column.histograms.limit)*100)+'%',
    'background':'#F03040'
  } : {
    'width':'1px',
    'background':'#2E92FA'
  }"

```

this allows for some calculaton into the css property values.

What to do with commit made in a detached head

checkout actual-branch

git merge {{commit-hash}}

Android image caching

Consider using Universal Image Loader library by Sergey Tarasevich. It comes with:

  • Multithread image loading. It lets you can define the thread pool size
  • Image caching in memory, on device's file sytem and SD card.
  • Possibility to listen to loading progress and loading events

Universal Image Loader allows detailed cache management for downloaded images, with the following cache configurations:

  • UsingFreqLimitedMemoryCache: The least frequently used bitmap is deleted when the cache size limit is exceeded.
  • LRULimitedMemoryCache: The least recently used bitmap is deleted when the cache size limit is exceeded.
  • FIFOLimitedMemoryCache: The FIFO rule is used for deletion when the cache size limit is exceeded.
  • LargestLimitedMemoryCache: The largest bitmap is deleted when the cache size limit is exceeded.
  • LimitedAgeMemoryCache: The Cached object is deleted when its age exceeds defined value.
  • WeakMemoryCache: A memory cache with only weak references to bitmaps.

A simple usage example:

ImageView imageView = groupView.findViewById(R.id.imageView);
String imageUrl = "http://site.com/image.png"; 

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
imageLoader.displayImage(imageUrl, imageView);

This example uses the default UsingFreqLimitedMemoryCache.

How to get size in bytes of a CLOB column in Oracle?

It only works till 4000 byte, What if the clob is bigger than 4000 bytes then we use this

declare
v_clob_size clob;

begin

      v_clob_size:= (DBMS_LOB.getlength(v_clob)) / 1024 / 1024;
      DBMS_OUTPUT.put_line('CLOB Size   ' || v_clob_size);   
end;

or

select (DBMS_LOB.getlength(your_column_name))/1024/1024 from your_table

How to remove title bar from the android activity?

Add this two line in your style.xml

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

PHP String to Float

Use this function to cast a float value from any kind of text style:

function parseFloat($value) {
    return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}

This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

When the form is processed, you redirect to another page:

... process complete....
header('Location: thankyou.php');

you can also redirect to the same page.

if you are doing something like comments and you want the user to stay on the same page, you can use Ajax to handle the form submission

jQuery .scrollTop(); + animation

$("body").stop().animate({
        scrollTop: 0
    }, 500, 'swing', function () {
        console.log(confirm('Like This'))
    }
);

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

How do I get whole and fractional parts from double in JSP/Java?

Main logic you have to first find how many digits are there after the decimal point.
This code works for any number upto 16 digits. If you use BigDecimal you can run it just for upto 18 digits. put the input value (your number) to the variable "num", here as an example i have hard coded it.

double num, temp=0;
double frac,j=1;

num=1034.235;
// FOR THE FRACTION PART
do{
j=j*10;
temp= num*j;
}while((temp%10)!=0);       

j=j/10;
temp=(int)num;
frac=(num*j)-(temp*j);

System.out.println("Double number= "+num);      
System.out.println("Whole part= "+(int)num+" fraction part= "+(int)frac);

IIS - can't access page by ip address instead of localhost

In my case it was because I was using a port other than the default port 80. I was able to access the site locally using localhost but not on another machine using the IP address.

To solve the issue I had to add a firewall inbound rule to allow the port. enter image description here

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

Compare two Timestamp in java

if (!mytime.before(fromtime) && !mytime.after(totime))

How to add element in List while iterating in java?

Iterate through a copy of the list and add new elements to the original list.

for (String s : new ArrayList<String>(list))     
{
    list.add("u");
}

See How to make a copy of ArrayList object which is type of List?

"R cannot be resolved to a variable"?

I have just had this problem.

It was caused because I had a redundant menu resource that referred to a non-existing string.

Removed the menu XML and back came R.

Format numbers in django templates

In case someone stumbles upon this, in Django 2.0.2 you can use this

Thousand separator. Be sure to read format localization as well.

AddTransient, AddScoped and AddSingleton Services Differences

  • Singleton is a single instance for the lifetime of the application domain.
  • Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET.
  • Transient is a single instance per code request.

Normally the code request should be made through a constructor parameter, as in

public MyConsumingClass(IDependency dependency)

I wanted to point out in @akazemis's answer that "services" in the context of DI does not imply RESTful services; services are implementations of dependencies that provide functionality.

Decrementing for loops

Check out the range documentation, you have to define a negative step:

>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

How to block users from closing a window in Javascript?

If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.

Global environment variables in a shell script

When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:

. ./setfoo.sh

This executes it in the context of the current shell, not as a sub shell.

From the bash man page:

. filename [arguments]
source filename [arguments]

Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.

If filename does not contain a slash, file names in PATH are used to find the directory containing filename.

The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.

If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.

If any arguments are supplied, they become the positional parameters when filename is executed.

Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

How to decompile an APK or DEX file on Android platform?

You need Three Tools to decompile an APK file.

  1. Dex2jar - Tools to work with android .dex and java .class files

  2. ApkTool - A tool for reverse engineering Android apk files

  3. JD-GUI - Java Decompiler is a tools to decompile and analyze Java 5 “byte code” and the later versions.

for more how-to-use-dextojar. Hope this will help You and all! :)

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

This is the way I updated the master branch

This kind of error occurs commonly after deleting the initial code on your project

So, go ahead, first of all, verify the actual remote version, then remove the origin add the comment, and copy the repo URL into the project files.

$ git remote -v
$ git remote rm origin
$ git commit -m "your commit"
$ git remote add origin https://github.com/user/repo.git
$ git push -f origin master

How to determine the Boost version on a system?

If one installed boost on macOS via Homebrew, one is likely to see the installed boost version(s) with:

ls /usr/local/Cellar/boost*

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

How to add a Browse To File dialog to a VB.NET application

You're looking for the OpenFileDialog class.

For example:

Sub SomeButton_Click(sender As Object, e As EventArgs) Handles SomeButton.Click
    Using dialog As New OpenFileDialog
        If dialog.ShowDialog() <> DialogResult.OK Then Return
        File.Copy(dialog.FileName, newPath)
    End Using
End Sub

Copying data from one SQLite database to another

Consider a example where I have two databases namely allmsa.db and atlanta.db. Say the database allmsa.db has tables for all msas in US and database atlanta.db is empty.

Our target is to copy the table atlanta from allmsa.db to atlanta.db.

Steps

  1. sqlite3 atlanta.db(to go into atlanta database)
  2. Attach allmsa.db. This can be done using the command ATTACH '/mnt/fastaccessDS/core/csv/allmsa.db' AS AM; note that we give the entire path of the database to be attached.
  3. check the database list using sqlite> .databases you can see the output as
seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /mnt/fastaccessDS/core/csv/atlanta.db                  
2    AM               /mnt/fastaccessDS/core/csv/allmsa.db 
  1. now you come to your actual target. Use the command INSERT INTO atlanta SELECT * FROM AM.atlanta;

This should serve your purpose.

How do I crop an image in Java?

You need to read about Java Image API and mouse-related API, maybe somewhere under the java.awt.event package.

For a start, you need to be able to load and display the image to the screen, maybe you'll use a JPanel.

Then from there, you will try implement a mouse motion listener interface and other related interfaces. Maybe you'll get tied on the mouseDragged method...

For a mousedragged action, you will get the coordinate of the rectangle form by the drag...

Then from these coordinates, you will get the subimage from the image you have and you sort of redraw it anew....

And then display the cropped image... I don't know if this will work, just a product of my imagination... just a thought!

What's the simplest way of detecting keyboard input in a script from the terminal?

This worked for me on macOS Sierra and Python 2.7.10 and 3.6.3

import sys,tty,os,termios
def getkey():
    old_settings = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
        while True:
            b = os.read(sys.stdin.fileno(), 3).decode()
            if len(b) == 3:
                k = ord(b[2])
            else:
                k = ord(b)
            key_mapping = {
                127: 'backspace',
                10: 'return',
                32: 'space',
                9: 'tab',
                27: 'esc',
                65: 'up',
                66: 'down',
                67: 'right',
                68: 'left'
            }
            return key_mapping.get(k, chr(k))
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
    while True:
        k = getkey()
        if k == 'esc':
            quit()
        else:
            print(k)
except (KeyboardInterrupt, SystemExit):
    os.system('stty sane')
    print('stopping.')

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

Open and write data to text file using Bash?

If you are using variables, you can use

first_var="Hello"
second_var="How are you"

If you want to concat both string and write it to file, then use below

echo "${first_var} - ${second_var}" > ./file_name.txt

Your file_name.txt content will be "Hello - How are you"

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

For (2), Guava provides exactly what you want as Int.asList(). There is an equivalent for each primitive type in the associated class, e.g., Booleans for boolean, etc.

    int[] arr={1,2,3};
    for(Integer i : Ints.asList(arr)) {
      System.out.println(i);
    }

How do I access nested HashMaps in Java?

As others have said you can do this but you should define the map with generics like so:

Map<String, Map<String, String>> map = new HashMap<String, Map<String,String>>();

However, if you just blindly run the following:

map.get("keyname").get("nestedkeyname");

you will get a null pointer exception whenever keyname is not in the map and your program will crash. You really should add the following check:

String valueFromMap = null;
if(map.containsKey("keyname")){
  valueFromMap = map.get("keyname").get("nestedkeyname");
}

The remote server returned an error: (403) Forbidden

In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.

[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true

String vs. StringBuilder

I have seen significant performance gains from using the EnsureCapacity(int capacity) method call on an instance of StringBuilder before using it for any string storage. I usually call that on the line of code after instantiation. It has the same effect as if you instantiate the StringBuilder like this:

var sb = new StringBuilder(int capacity);

This call allocates needed memory ahead of time, which causes fewer memory allocations during multiple Append() operations. You have to make an educated guess on how much memory you will need, but for most applications this should not be too difficult. I usually err on the side of a little too much memory (we are talking 1k or so).

Check if a file exists with wildcard in shell script

IMHO it's better to use find always when testing for files, globs or directories. The stumbling block in doing so is find's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find creates no echo in its exit code.

The following example tests if a directory has entries:

$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty

When A has no files grep fails:

$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty

When A does not exist grep fails again because find only prints to stderr:

$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty

Replace -not -empty by any other find expression, but be careful if you -exec a command that prints to stdout. You may want to grep for a more specific expression in such cases.

This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*:

if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
    : the glob matched
else
    : ...not
fi

Note that the else-branched is reached if xorg-x11-fonts* had not matched, or find encountered an error. To distinguish the case use $?.

Update div with jQuery ajax response html

Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.

Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way

$('#submitform').click(function() {
     $.ajax({
     url: "getinfo.asp",
     data: {
         txtsearch: $('#appendedInputButton').val()
     },
     type: "GET",
     dataType : "html",
     success: function (data){
         $('#showresults').html($('#showresults',data).html());
         // similar to $(data).find('#showresults')
     },
});

or with replaceWith()

// codes

success: function (data){
   $('#showresults').replaceWith($('#showresults',data));
},

jQuery get specific option tag text

$("#list [value='2']").text();

leave a space after the id selector.

#pragma once vs include guards?

Atop explanation by Konrad Kleine above.

A brief summary:

  • when we use # pragma once it is much of the compiler responsibility, not to allow its inclusion more than once. Which means, after you mention the code-snippet in the file, it is no more your responsibility.

Now, compiler looks, for this code-snippet at the beginning of the file, and skips it from being included (if already included once). This definitely will reduce the compilation-time (on an average and in huge-system). However, in case of mocks/test environment, will make the test-cases implementation difficult, due to circular etc dependencies.

  • Now, when we use the #ifndef XYZ_H for the headers, it is more of the developers responsibility to maintain the dependency of headers. Which means, whenever due to some new header file, there is possibility of the circular dependency, compiler will just flag some "undefined .." error messages at compile time, and it is user to check the logical connection/flow of the entities and rectify the improper includes.

This definitely will add to the compilation time (as needs to rectified and re-run). Also, as it works on the basis of including the file, based on the "XYZ_H" defined-state, and still complains, if not able to get all the definitions.

Therefore, to avoid situations like this, we should use, as;

#pragma once
#ifndef XYZ_H
#define XYZ_H
...
#endif

i.e. the combination of both.

Create a pointer to two-dimensional array

You can do it like this:

uint8_t (*matrix_ptr)[10][20] = &l_matrix;

How to disable editing of elements in combobox for c#?

Use the ComboStyle property:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

What does "for" attribute do in HTML <label> tag?

Using label for= in html form

This could permit to visualy dissociate label(s) and object while keeping them linked.

Sample: there is a checkbox and two labels. You could check/uncheck the box by clicking indifferently on any label or on box, but not on text nor on input content...

_x000D_
_x000D_
<label for="demo1"> There is a label </label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1"> There is a 2nd label </label>
<input id="demo1" type="checkbox">Demo 1</input>
_x000D_
_x000D_
_x000D_

Some useful tricks

By use stylesheet CSS power, you could do a lot of interresting things...

_x000D_
_x000D_
#demo2:checked ~ .but2:before { content: 'Des'; }
#demo2:checked ~ .box2:before { content: '?'; }
.but2:before { content: 'S'; }
.box2:before { content: '?'; }
#demo1:checked ~ .but1:before { content: 'Des'; }
#demo1:checked ~ .box1:before { content: '?'; }
.but1:before { content: 'S'; }
.box1:before { content: '?'; }
_x000D_
<input id="demo1" type="checkbox">Demo 1</input>
<input id="demo2" type="checkbox">Demo 2</input>
<br />
<label for="demo1" class="but1">elect 2</label> - 
<label for="demo2" class="but2">elect 1</label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1" class="but1">elect this 2nd label </label> - 
<label class="but2" for="demo2">elect this another 2nd label </label>
<br />
<label for="demo1" class="box1"> check 1</label>
<label for="demo2" class="box2"> check 2</label> 
_x000D_
_x000D_
_x000D_

Generate a Hash from string in Javascript

A fast and concise one which was adapted from here:

String.prototype.hashCode = function() {
  var hash = 5381, i = this.length
  while(i)
    hash = (hash * 33) ^ this.charCodeAt(--i)
  return hash >>> 0;
}

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Placeholder in UITextView

If someone needs a Solution for Swift:

Add UITextViewDelegate to your class

var placeHolderText = "Placeholder Text..."

override func viewDidLoad() {
    super.viewDidLoad()
    textView.delegate = self
}

func textViewShouldBeginEditing(textView: UITextView) -> Bool {

    self.textView.textColor = .black

    if(self.textView.text == placeHolderText) {
        self.textView.text = ""
    }

    return true
}

func textViewDidEndEditing(textView: UITextView) {
    if(textView.text == "") {
        self.textView.text = placeHolderText
        self.textView.textColor = .lightGray
    }
}

override func viewWillAppear(animated: Bool) {

    if(currentQuestion.answerDisplayValue == "") {
        self.textView.text = placeHolderText
        self.textView.textColor = .lightGray
    } else {
        self.textView.text = "xxx" // load default text / or stored 
        self.textView.textColor = .black
    }
}

Combining the results of two SQL queries as separate columns

You can aliasing both query and Selecting them in the select query
http://sqlfiddle.com/#!2/ca27b/1

SELECT x.a, y.b FROM (SELECT * from a) as x, (SELECT * FROM b) as y

Rounded table corners CSS only

Add a <div> wrapper around the table, and apply the following CSS

border-radius: x px;
overflow: hidden;
display: inline-block;

to this wrapper.

Remove an element from a Bash array

To expand on the above answers, the following can be used to remove multiple elements from an array, without partial matching:

ARRAY=(one two onetwo three four threefour "one six")
TO_REMOVE=(one four)

TEMP_ARRAY=()
for pkg in "${ARRAY[@]}"; do
    for remove in "${TO_REMOVE[@]}"; do
        KEEP=true
        if [[ ${pkg} == ${remove} ]]; then
            KEEP=false
            break
        fi
    done
    if ${KEEP}; then
        TEMP_ARRAY+=(${pkg})
    fi
done
ARRAY=("${TEMP_ARRAY[@]}")
unset TEMP_ARRAY

This will result in an array containing: (two onetwo three threefour "one six")

Why do we assign a parent reference to the child object in Java?

Let's say you'd like to have an array of instances of Parent class, and a set of child classes Child1, Child2, Child3 extending Parent. There're situations when you're only interested with the parent class implementation, which is more general, and do not care about more specific stuff introduced by child classes.

Playing .mp3 and .wav in Java?

Using MP3 Decoder/player/converter Maven Dependency.

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PlayAudio{

public static void main(String[] args) throws FileNotFoundException {

    try {
        FileInputStream fileInputStream = new FileInputStream("mp.mp3");
        Player player = new Player((fileInputStream));
        player.play();
        System.out.println("Song is playing");
        while(true){
            System.out.println(player.getPosition());
        }
    }catch (Exception e){
        System.out.println(e);
    }

  }

}