Programs & Examples On #Entitydatasource

EntityDataSource is an ASP.NET web server control available in .NET Framework 3.5 SP1 or later. It supports declarative data-binding of other web controls to an Entity Data Model of Entity Framework.

Easiest way to read/write a file's content in Python

with open('x.py') as f: s = f.read()

***grins***

initializing a Guava ImmutableMap

Notice that your error message only contains five K, V pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of() methods, accepting between zero and five key-value pairings. There is not an of(...) overload accepting a varags parameter because K and V can be different types.

You want an ImmutableMap.Builder:

ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
    .put("key1", "value1") 
    .put("key2", "value2") 
    .put("key3", "value3") 
    .put("key4", "value4") 
    .put("key5", "value5") 
    .put("key6", "value6") 
    .put("key7", "value7") 
    .put("key8", "value8") 
    .put("key9", "value9")
    .build();

Check if a file exists or not in Windows PowerShell?

Just to offer the alternative to the Test-Path cmdlet (since nobody mentioned it):

[System.IO.File]::Exists($path)

Does (almost) the same thing as

Test-Path $path -PathType Leaf

except no support for wildcard characters

How to unit test abstract classes: extend with stubs?

If an abstract class is appropriate for your implementation, test (as suggested above) a derived concrete class. Your assumptions are correct.

To avoid future confusion, be aware that this concrete test class is not a mock, but a fake.

In strict terms, a mock is defined by the following characteristics:

  • A mock is used in place of each and every dependency of the subject class being tested.
  • A mock is a pseudo-implementation of an interface (you may recall that as a general rule, dependencies should be declared as interfaces; testability is one primary reason for this)
  • Behaviors of the mock's interface members -- whether methods or properties -- are supplied at test-time (again, by use of a mocking framework). This way, you avoid coupling of the implementation being tested with the implementation of its dependencies (which should all have their own discrete tests).

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

Using quotation marks inside quotation marks

When you have several words like this which you want to concatenate in a string, I recommend using format or f-strings which increase readability dramatically (in my opinion).

To give an example:

s = "a word that needs quotation marks"
s2 = "another word"

Now you can do

print('"{}" and "{}"'.format(s, s2))

which will print

"a word that needs quotation marks" and "another word"

As of Python 3.6 you can use:

print(f'"{s}" and "{s2}"')

yielding the same output.

jQuery append() vs appendChild()

No longer

now append is a method in JavaScript

MDN documentation on append method

Quoting MDN

The ParentNode.append method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

This is not supported by IE and Edge but supported by Chrome(54+), Firefox(49+) and Opera(39+).

The JavaScript's append is similar to jQuery's append.

You can pass multiple arguments.

_x000D_
_x000D_
var elm = document.getElementById('div1');
elm.append(document.createElement('p'),document.createElement('span'),document.createElement('div'));
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
_x000D_
_x000D_

Angular IE Caching issue for $http

I get it resolved appending datetime as an random number:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Which HTML elements can receive focus?

The ally.js accessibility library provides an unofficial, test-based list here:

https://allyjs.io/data-tables/focusable.html

(NB: Their page doesn't say how often tests were performed.)

How can I remove specific rules from iptables?

Use -D command, this is how man page explains it:

-D, --delete chain rule-specification
-D, --delete chain rulenum
    Delete  one  or more rules from the selected chain.  
    There are two versions of this command: 
    the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match.

Do realize this command, like all other command(-A, -I) works on certain table. If you'are not working on the default table(filter table), use -t TABLENAME to specify that target table.

Delete a rule to match

iptables -D INPUT -i eth0 -p tcp --dport 443 -j ACCEPT

Note: This only deletes the first rule matched. If you have many rules matched(this can happen in iptables), run this several times.

Delete a rule specified as a number

iptables -D INPUT 2

Other than counting the number you can list the line-number with --line-number parameter, for example:

iptables -t nat -nL --line-number

Error while sending QUERY packet

You cannot have the WHERE clause in an INSERT statement.

insert into table1(data) VALUES(:data) where sno ='45830'

Should be

insert into table1(data) VALUES(:data)


Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:

SET GLOBAL max_allowed_packet=32M

Change the 32M (32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.

Function overloading in Python: Missing

Oftentimes you see the suggestion use use keyword arguments, with default values, instead. Look into that.

What is the main difference between PATCH and PUT request?

Here are the difference between POST, PUT and PATCH methods of a HTTP protocol.

POST

A HTTP.POST method always creates a new resource on the server. Its a non-idempotent request i.e. if user hits same requests 2 times it would create another new resource if there is no constraint.

http post method is like a INSERT query in SQL which always creates a new record in database.

Example: Use POST method to save new user, order etc where backend server decides the resource id for new resource.

PUT

In HTTP.PUT method the resource is first identified from the URL and if it exists then it is updated otherwise a new resource is created. When the target resource exists it overwrites that resource with a complete new body. That is HTTP.PUT method is used to CREATE or UPDATE a resource.

http put method is like a MERGE query in SQL which inserts or updates a record depending upon whether the given record exists.

PUT request is idempotent i.e. hitting the same requests twice would update the existing recording (No new record created). In PUT method the resource id is decided by the client and provided in the request url.

Example: Use PUT method to update existing user or order.

PATCH

A HTTP.PATCH method is used for partial modifications to a resource i.e. delta updates.

http patch method is like a UPDATE query in SQL which sets or updates selected columns only and not the whole row.

Example: You could use PATCH method to update order status.

PATCH /api/users/40450236/order/10234557

Request Body: {status: 'Delivered'}

Bad Request - Invalid Hostname IIS7

Did you check the binding is IIS? (inetmgr.exe) It may not be registered to accept all hostnames on 8080.

For example, if you set it up for mysite.com:8080 and hit it at localhost:8080, IIS will get the request but not have a hostname binding to match so it rejects.

Outside of that, you should check the IIS logs (C:\inetpub\logs\wmsvc#) on the server and see if you are seeing your request. Then you'll know if its a problem on your client or on the server itself.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

I wrote this so I could edit all tables and columns to null at once:

select 
case
when sc.max_length = '-1' and st.name in ('char','decimal','nvarchar','varchar')
then
'alter table  [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(MAX) NULL'
when st.name in ('char','decimal','nvarchar','varchar')
then
'alter table  [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(' + cast(sc.max_length as varchar(4)) + ') NULL'
else
'alter table  [' + so.name + '] alter column [' + sc.name + '] ' + st.name + ' NULL'
end as query
from sys.columns sc
inner join sys.types st on st.system_type_id = sc.system_type_id
inner join sys.objects so on so.object_id = sc.object_id
where so.type = 'U'
and st.name <> 'timestamp'
order by st.name

How to find out when a particular table was created in Oracle?

SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'

PHP prepend leading zero before single digit number, on-the-fly

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Why can't I have abstract static methods in C#?

The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).

Switching from zsh to bash on OSX, and back again?

if it is just a temporary switch

you can use exec as mentioned above, but for more of a permanent solution.

you can use chsh -s /bin/bash (to switch to bash) and chsh -s /bin/zsh (to switch to zsh)

How to get the row number from a datatable?

Try:

int i = Convert.ToInt32(dt.Rows.Count);

I think it's the shortest, thus the simplest way.

How can I indent multiple lines in Xcode?

In Xcode 9, you can finally use Tab and Shift+Tab to indent multiple lines of code. Yay!

Adding CSRFToken to Ajax request

Here is code that I used to prevent CSRF token problem when sending POST request with ajax

$(document).ready(function(){
    function getCookie(c_name) {
        if(document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if(c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if(c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
    }

    $(function () {
        $.ajaxSetup({
            headers: {
                "X-CSRFToken": getCookie("csrftoken")
            }
        });
    });

});

How to check whether a Button is clicked by using JavaScript

Try adding an event listener for clicks:

document.getElementById('button').addEventListener("click", function() {
   alert("You clicked me");
}?);?

Using addEventListener is probably a better idea then setting onclick - onclick can easily be overwritten by another piece of code.

You can use a variable to store whether or not the button has been clicked before:

var clicked = false
document.getElementById('button').addEventListener("click", function() {
   clicked = true
}?);?

addEventListener on MDN

Truncate (not round) decimal places in SQL Server

Round has an optional parameter

Select round(123.456, 2, 1)  will = 123.45
Select round(123.456, 2, 0)  will = 123.46

Does Enter key trigger a click event?

<form (keydown)="someMethod($event)">
     <input type="text">
</form>
someMethod(event:any){
   if(event.keyCode == 13){
      alert('Entered Click Event!');
   }else{
   }
}

querySelectorAll with multiple conditions

With pure JavaScript you can do this (such as SQL) and anything you need, basically:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<input type='button' value='F3' class="c2" id="btn_1">_x000D_
<input type='button' value='F3' class="c3" id="btn_2">_x000D_
<input type='button' value='F1' class="c2" id="btn_3">_x000D_
_x000D_
<input type='submit' value='F2' class="c1" id="btn_4">_x000D_
<input type='submit' value='F1' class="c3" id="btn_5">_x000D_
<input type='submit' value='F2' class="c1" id="btn_6">_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<script>_x000D_
    function myFunction() _x000D_
    {_x000D_
        var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
_x000D_
            arrFiltered.forEach(function (el)_x000D_
            {                _x000D_
                var node = document.createElement("p");_x000D_
                _x000D_
                node.innerHTML = el.getAttribute('id');_x000D_
_x000D_
                window.document.body.appendChild(node);_x000D_
            });_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

disable textbox using jquery?

I would've done it slightly different

 <input type="radio" value="1" name="userradiobtn" id="userradiobtn" />   
 <input type="radio" value="2" name="userradiobtn" id="userradiobtn" />    
 <input type="radio" value="3" name="userradiobtn" id="userradiobtn" class="disablebox"/>   
 <input type="checkbox" value="4" name="chkbox" id="chkbox" class="showbox"/>    
 <input type="text" name="usertxtbox" id="usertxtbox" class="showbox" />   

Notice class attribute

 $(document).ready(function() {      
    $('.disablebox').click(function() {
        $('.showbox').attr("disabled", true);           
    });
});

This way should you need to add more radio buttons you don't need to worry about changing the javascript

Nginx: Job for nginx.service failed because the control process exited

Try set a user in nginx.conf, maybe that's why he can not start the service:

User www-data;

What is the garbage collector in Java?

Many people think garbage collection collects and discards dead objects.
In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage.

When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system. To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm.

Check this for more detail information: http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx

Git says local branch is behind remote branch, but it's not

This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:

git co master
git pull

Which fetched those changes. Then,

git co develop
git pull

Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.

How to jump back to NERDTree from file in tab?

You can focus on a split window using # ctrl-ww.

for example, pressing:

1 ctrl-ww

would focus on the first window, usually being NERDTree.

Return background color of selected cell

The code below gives the HEX and RGB value of the range whether formatted using conditional formatting or otherwise. If the range is not formatted using Conditional Formatting and you intend to use iColor function in the Excel as UDF. It won't work. Read the below excerpt from MSDN.

Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, if you use a line similar to:

Range.DisplayFormat.Interior.ColorIndex

then the worksheet function executes to return a #VALUE! error. If you are not finding color of the conditionally formatted range, then I encourage you to rather use

Range.Interior.ColorIndex

as then the function can also be used as UDF in Excel. Such as iColor(B1,"HEX")

Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
    Dim colorVal As Variant
    colorVal = rng.DisplayFormat.Interior.Color
    Select Case UCase(formatType)
        Case "HEX"
            iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
                           Format(Hex((colorVal \ 256) Mod 256),"00") & _
                           Format(Hex((colorVal \ 65536)),"00")
        Case "RGB"
            iColor = Format((colorVal Mod 256),"00") & ", " & _
                     Format(((colorVal \ 256) Mod 256),"00") & ", " & _
                     Format((colorVal \ 65536),"00")
        Case "IDX"
            iColor = rng.Interior.ColorIndex
        Case Else
            iColor = colorVal
    End Select
End Function

'Example use of the iColor function
Sub Get_Color_Format()
    Dim rng As Range

    For Each rng In Selection.Cells
        rng.Offset(0, 1).Value = iColor(rng, "HEX")
        rng.Offset(0, 2).Value = iColor(rng, "RGB")
    Next
End Sub

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

Returning anonymous type in C#

You can only use dynamic keyword,

   dynamic obj = GetAnonymousType();

   Console.WriteLine(obj.Name);
   Console.WriteLine(obj.LastName);
   Console.WriteLine(obj.Age); 


   public static dynamic GetAnonymousType()
   {
       return new { Name = "John", LastName = "Smith", Age=42};
   }

But with dynamic type keyword you will loose compile time safety, IDE IntelliSense etc...

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

How to convert a date String to a Date or Calendar object?

The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date / java.util.Calendar classes.

Joda's DateFormatter can parse a String to a Joda DateTime.

The maximum value for an int type in Go

From math lib: https://github.com/golang/go/blob/master/src/math/const.go#L39

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Printf("max int64: %d\n", math.MaxInt64)
}

How to find serial number of Android device?

The IMEI is good but only works on Android devices with phone. You should consider support for Tablets or other Android devices as well, that do not have a phone.

You have some alternatives like: Build class members, BT MAC, WLAN MAC, or even better - a combination of all these.

I have explained these details in an article on my blog, see: http://www.pocketmagic.net/?p=1662

Node.js version on the command line? (not the REPL)

By default node package is nodejs, so use

$ nodejs -v

or

$ nodejs --version 

You can make a link using

$ sudo ln -s /usr/bin/nodejs /usr/bin/node

then u can use

$ node --version

or

$ node -v

In Java, remove empty elements from a list of Strings

If you get UnsupportedOperationException from using one of ther answer above and your List is created from Arrays.asList(), it is because you can't edit such List.

To fix, wrap the Arrays.asList() inside new LinkedList<String>():

    List<String> list = new LinkedList<String>(Arrays.asList(split));

Source is from this answer.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

npm config set strict-ssl false -g

To save it globally

Difference between RUN and CMD in a Dockerfile

I found this article very helpful to understand the difference between them:

RUN - RUN instruction allows you to install your application and packages required for it. It executes any commands on top of the current image and creates a new layer by committing the results. Often you will find multiple RUN instructions in a Dockerfile.

CMD - CMD instruction allows you to set a default command, which will be executed only when you run container without specifying a command. If Docker container runs with a command, the default command will be ignored. If Dockerfile has more than one CMD instruction, all but last
CMD instructions are ignored.

App not setup: This app is still in development mode

Go to Settings->Basic, on top you will find a Switch button which will say App is in development mode.

enter image description here

Click on in development switch button, it will ask you to make app live, and after providing all necessary things, it will become live.

enter image description here

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

If you are just targeting specific domains you can try and add this in your application's Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Blade if(isset) is not working Laravel

Use ?? , 'or' not supported in updated version.

{{ $usersType or '' }}  ?
{{ $usersType ?? '' }} ?

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

How to get href value using jQuery?

**Replacing  href attribut value to other** 
 
 <div class="cpt">
   <a href="/ref/ref/testone.html">testoneLink</a>
 </div>

  <div class="test" >
      <a href="/ref/ref/testtwo.html">testtwoLInk</a>
  </div>

 <!--Remove first default Link from href attribut -->
<script>
     Remove first default Link from href attribut
    $(".cpt a").removeAttr("href");
    
    Add  Link to same href attribut
    var testurl= $(".test").find("a").attr("href");
    $(".test a").attr('href', testurl);
</script>

Dump all tables in CSV format using 'mysqldump'

First, I can give you the answer for one table:

The trouble with all these INTO OUTFILE or --tab=tmpfile (and -T/path/to/directory) answers is that it requires running mysqldump on the same server as the MySQL server, and having those access rights.

My solution was simply to use mysql (not mysqldump) with the -B parameter, inline the SELECT statement with -e, then massage the ASCII output with sed, and wind up with CSV including a header field row:

Example:

 mysql -B -u username -p password database -h dbhost -e "SELECT * FROM accounts;" \
 | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g"

"id","login","password","folder","email" "8","mariana","xxxxxxxxxx","mariana","" "3","squaredesign","xxxxxxxxxxxxxxxxx","squaredesign","[email protected]" "4","miedziak","xxxxxxxxxx","miedziak","[email protected]" "5","Sarko","xxxxxxxxx","Sarko","" "6","Logitrans Poland","xxxxxxxxxxxxxx","LogitransPoland","" "7","Amos","xxxxxxxxxxxxxxxxxxxx","Amos","" "9","Annabelle","xxxxxxxxxxxxxxxx","Annabelle","" "11","Brandfathers and Sons","xxxxxxxxxxxxxxxxx","BrandfathersAndSons","" "12","Imagine Group","xxxxxxxxxxxxxxxx","ImagineGroup","" "13","EduSquare.pl","xxxxxxxxxxxxxxxxx","EduSquare.pl","" "101","tmp","xxxxxxxxxxxxxxxxxxxxx","_","[email protected]"

Add a > outfile.csv at the end of that one-liner, to get your CSV file for that table.

Next, get a list of all your tables with

mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"

From there, it's only one more step to make a loop, for example, in the Bash shell to iterate over those tables:

 for tb in $(mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"); do
     echo .....;
 done

Between the do and ; done insert the long command I wrote in Part 1 above, but substitute your tablename with $tb instead.

Override default Spring-Boot application.properties settings in Junit Test

TLDR:

So what I did was to have the standard src/main/resources/application.properties and also a src/test/resources/application-default.properties where i override some settings for ALL my tests.

Whole Story

I ran into the same problem and was not using profiles either so far. It seemed to be bothersome to have to do it now and remember declaring the profile -- which can be easily forgotten.

The trick is, to leverage that a profile specific application-<profile>.properties overrides settings in the general profile. See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties.

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Controlling a USB power supply (on/off) with Linux

USB 5v power is always on (even when the computer is turned off, on some computers and on some ports.) You will probably need to program an Arduino with some sort of switch, and control it via Serial library from USB plugged in to the computer.

In other words, a combination of this switch tutorial and this tutorial on communicating via Serial libary to Arduino plugged in via USB.

CSS Input with width: 100% goes outside parent's bound

If all above fail, try setting the following properties for your input, to have it take max space but not overflow:

input {
    min-width: 100%;
    max-width: 100%;
}

How to list all properties of a PowerShell object

The most succinct way to do this is:

Get-WmiObject -Class win32_computersystem -Property *

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

Compare two different files line by line in python

If you are specifically looking for getting the difference between two files, then this might help:

with open('first_file', 'r') as file1:
    with open('second_file', 'r') as file2:
        difference = set(file1).difference(file2)

difference.discard('\n')

with open('diff.txt', 'w') as file_out:
    for line in difference:
        file_out.write(line)

Align div right in Bootstrap 3

i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right only push the div to the right, but not the content inside the div.

HTML:

<div class="row">
  <div class="container">
    <div class="col-md-4 someclass">
      left content
    </div>
    <div class="col-md-4 col-md-offset-4 someclass">
      <div class="yellow_background totheright">right content</div>
    </div>
  </div>
</div>

CSS:

.someclass{ /*this class for testing purpose only*/
    border:1px solid blue;
    line-height:2em;
}

.totheright{ /*this will align the text to the right*/
  text-align:right;
}

.yellow_background{
    background-color:yellow;
}

Another modification:

...
<div class="yellow_background totheright">
  <span>right content</span>
  <br/>image also align-right<br/>
  <img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...

hope it will clear your problem

Quick way to create a list of values in C#?

You can drop the new string[] part:

List<string> values = new List<string> { "one", "two", "three" };

Transparent scrollbar with css

Try this one, it works fine for me.

In CSS:

::-webkit-scrollbar
{
    width: 0px;
}
::-webkit-scrollbar-track-piece
{
    background-color: transparent;
    -webkit-border-radius: 6px;
}

and here is the working demo: https://jsfiddle.net/qpvnecz5/

format statement in a string resource file

You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.

Quote from Android Docs: String Formatting and Styling:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal integer. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);

How to perform case-insensitive sorting in JavaScript?

myArray.sort(
  function(a, b) {
    if (a.toLowerCase() < b.toLowerCase()) return -1;
    if (a.toLowerCase() > b.toLowerCase()) return 1;
    return 0;
  }
);

EDIT: Please note that I originally wrote this to illustrate the technique rather than having performance in mind. Please also refer to answer @Ivan Krechetov for a more compact solution.

Regex: ignore case sensitivity

The i flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i or /(?i)G[ab].*/.

How to match letters only using java regex, matches method?

"[a-zA-Z]" matches only one character. To match multiple characters, use "[a-zA-Z]+".

Since a dot is a joker for any character, you have to mask it: "abc\." To make the dot optional, you need a question mark: "abc\.?"

If you write the Pattern as literal constant in your code, you have to mask the backslash:

System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));

Combining both patterns:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));

Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:

System.out.println ("abc.".matches ("\\w+\\.?"));   

PowerShell: how to grep command output?

Your problem is that alias emits a stream of AliasInfo objects, rather than a stream of strings. This does what I think you want.

alias | out-string -stream | select-string Alias

or as a function

function grep {
  $input | out-string -stream | select-string $args
}

alias | grep Alias

When you don't handle things that are in the pipeline (like when you just ran 'alias'), the shell knows to use the ToString() method on each object (or use the output formats specified in the ETS info).

Automated Python to Java translation

It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).

PHP cURL GET request and request's body

The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:

curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );

EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).

Programmatically set TextBlock Foreground Color

To get the Color from Hex.

using System.Windows.Media;

Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");

and then set the foreground

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(color); 

Add image to left of text via css

.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px;  /* width of the image plus a little extra padding */
display: block;  /* may not need this, but I've found I do */
}

Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).

ViewPager PagerAdapter not updating the View

1.First you have to set the getItemposition method in your Pageradapter class 2.You have to read the Exact position of your View Pager 3.then send that position as data location of your new one 4.Write update button onclick listener inside the setonPageChange listener

that program code is little bit i modified to set the particular position element only

public class MyActivity extends Activity {

private ViewPager myViewPager;
private List<String> data;
public int location=0;
public Button updateButton;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    data = new ArrayList<String>();
    data.add("A");
    data.add("B");
    data.add("C");
    data.add("D");
    data.add("E");
    data.add("F");

    myViewPager = (ViewPager) findViewById(R.id.pager);
    myViewPager.setAdapter(new MyViewPagerAdapter(this, data));

      updateButton = (Button) findViewById(R.id.update);

    myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
             //Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageSelected( int i) {
          // here you will get the position of selected page
            final int k = i;
             updateViewPager(k);

        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
}

private void updateViewPager(final int i) {  
    updateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
            data.set(i, "Replaced "+i);         
            myViewPager.getAdapter().notifyDataSetChanged();
        }
    });

}

private class MyViewPagerAdapter extends PagerAdapter {

    private List<String> data;
    private Context ctx;

    public MyViewPagerAdapter(Context ctx, List<String> data) {
        this.ctx = ctx;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public Object instantiateItem(View collection, int position) {          

        TextView view = new TextView(ctx);
        view.setText(data.get(position));
        ((ViewPager)collection).addView(view);            
        return view;
    }

    @Override
    public void destroyItem(View collection, int position, Object view) {
         ((ViewPager) collection).removeView((View) view);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
    }

    @Override
    public void startUpdate(View arg0) {
    }

    @Override
    public void finishUpdate(View arg0) {
    }
}
}

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

Why are hexadecimal numbers prefixed with 0x?

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example:

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or whatever ..

For binary it would be:

0b00000001

Hope I have helped in some way.

Good day!

ArrayList or List declaration in Java

Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach

List<String> strings = new ArrayList<String>();

because it's hide the implementation detail from user. You precisely

List<String> strings = new ArrayList<String>(); 

it's generic approach and this specialized approach

ArrayList<String> strings = new ArrayList<String>();

For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces

Run parallel multiple commands at once in the same terminal

This bash script is for N parallel threads. Each argument is a command.

trap will kill all subprocesses when SIGINT is catched.
wait $PID_LIST is waiting each process to complete. When all processes have completed, the program exits.

#!/bin/bash

for cmd in "$@"; do {
  echo "Process \"$cmd\" started";
  $cmd & pid=$!
  PID_LIST+=" $pid";
} done

trap "kill $PID_LIST" SIGINT

echo "Parallel processes have started";

wait $PID_LIST

echo
echo "All processes have completed";

Save this script as parallel_commands and make it executable.
This is how to use this script:

parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"

Example:

parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"

Start 4 parallel sleep and waits until "sleep 4" finishes.

Using querySelectorAll to retrieve direct children

The following solution is different to the ones proposed so far, and works for me.

The rationale is that you select all matching children first, and then filter out the ones which are not direct children. A child is a direct child if it does not have a matching parent with the same selector.

function queryDirectChildren(parent, selector) {
    const nodes = parent.querySelectorAll(selector);
    const filteredNodes = [].slice.call(nodes).filter(n => 
        n.parentNode.closest(selector) === parent.closest(selector)
    );
    return filteredNodes;
}

HTH!

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.

Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModules basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandlers can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

I have the same problem and tried all the solutions posted here like :

sudo apt-get autoremove mysql-server

but unfortunately it doesn't work for me on ubuntu 16.04. To uninstall the right package you need to :

sudo apt-get remove mysql-

when you tried to autocomplete using tab the command it will list the following package :

mysql-client           mysql-client-core-5.7  mysql-server           mysql-server-core-5.7  mysql-workbench        mythes-en-us           
mysql-client-5.7       mysql-common           mysql-server-5.7       mysql-utilities        mysql-workbench-data   

obviously choose the mysql-server-core-5.7 so it would be :

sudo apt-get remove mysql-server-core-5.7

and now you can uninstall all mysql and reinstall again using these command from johnny's answer :

sudo apt-get remove --purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mysql-server mysql-client

Now I solved it and the Error is GONE.

Best way to specify whitespace in a String.Split operation

So don't copy and paste! Extract a function to do your splitting and reuse it.

public static string[] SplitWhitespace (string input)
{
    char[] whitespace = new char[] { ' ', '\t' };
    return input.Split(whitespace);
}

Code reuse is your friend.

How do I add a ToolTip to a control?

Here is your article for doing it with code

private void Form1_Load(object sender, System.EventArgs e)
{
     // Create the ToolTip and associate with the Form container.
     ToolTip toolTip1 = new ToolTip();

     // Set up the delays for the ToolTip.
     toolTip1.AutoPopDelay = 5000;
     toolTip1.InitialDelay = 1000;
     toolTip1.ReshowDelay = 500;
     // Force the ToolTip text to be displayed whether or not the form is active.
     toolTip1.ShowAlways = true;

     // Set up the ToolTip text for the Button and Checkbox.
     toolTip1.SetToolTip(this.button1, "My button1");
     toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

Fatal error: Call to undefined function mcrypt_encrypt()

My Environment: Windows 10, Xampp Control Panel v3.2.4, PHP 7.3.2

Step-1: Download a suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Step-2: Unzip and copy php_mcrypt.dll file to ../xampp/php/ext/

Step-3: Open ../xampp/php/php.ini file and add a line extension=php_mcrypt.dll

Step-4: Restart apache, DONE!

How to split page into 4 equal parts?

If you want to have control over where they are placed separate from source code order:

Demo: http://jsfiddle.net/NmL2W/

<div id="NW"></div>
<div id="NE"></div>
<div id="SE"></div>?
<div id="SW"></div>
html, body { height:100%; margin:0; padding:0 }
div { position:fixed; width:50%; height:50% }
#NW { top:0;   left:0;   background:orange  }
#NE { top:0;   left:50%; background:blue    }
#SW { top:50%; left:0;   background:green   }
#SE { top:50%; left:50%; background:red     }    ?

Note: if you want padding on your regions, you'll need to set the box-sizing to border-box:

div {
  /* ... */
  padding:1em;
  box-sizing:border-box;
  -moz-box-sizing:border-box;
  -webkit-box-sizing:border-box;
}

…otherwise your "50%" width and height become "50% + 2em", which will lead to visual overlaps.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

PowerShell script to check the status of a URL

Below is the PowerShell code that I use for basic web URL testing. It includes the ability to accept invalid certs and get detailed information about the results of checking the certificate.

$CertificateValidatorClass = @'
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace CertificateValidation
{
    public class CertificateValidationResult
    {
        public string Subject { get; internal set; }
        public string Thumbprint { get; internal set; }
        public DateTime Expiration { get; internal set; }
        public DateTime ValidationTime { get; internal set; }
        public bool IsValid { get; internal set; }
        public bool Accepted { get; internal set; }
        public string Message { get; internal set; }

        public CertificateValidationResult()
        {
            ValidationTime = DateTime.UtcNow;
        }
    }

    public static class CertificateValidator
    {
        private static ConcurrentStack<CertificateValidationResult> certificateValidationResults = new ConcurrentStack<CertificateValidationResult>();

        public static CertificateValidationResult[] CertificateValidationResults
        {
            get
            {
                return certificateValidationResults.ToArray();
            }
        }

        public static CertificateValidationResult LastCertificateValidationResult
        {
            get
            {
                CertificateValidationResult lastCertificateValidationResult = null;
                certificateValidationResults.TryPeek(out lastCertificateValidationResult);

                return lastCertificateValidationResult;
            }
        }

        public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            StringBuilder certificateValidationMessage = new StringBuilder();
            bool allowCertificate = true;

            if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
            {
                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    certificateValidationMessage.AppendFormat("The remote certificate name does not match.\r\n", certificate.Subject);
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    certificateValidationMessage.AppendLine("The certificate chain has the following errors:");
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus chainStatus in chain.ChainStatus)
                    {
                        certificateValidationMessage.AppendFormat("\t{0}", chainStatus.StatusInformation);

                        if (chainStatus.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked)
                        {
                            allowCertificate = false;
                        }
                    }
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
                {
                    certificateValidationMessage.AppendLine("The remote certificate was not available.");
                    allowCertificate = false;
                }

                System.Console.WriteLine();
            }
            else
            {
                certificateValidationMessage.AppendLine("The remote certificate is valid.");
            }

            CertificateValidationResult certificateValidationResult = new CertificateValidationResult
                {
                    Subject = certificate.Subject,
                    Thumbprint = certificate.GetCertHashString(),
                    Expiration = DateTime.Parse(certificate.GetExpirationDateString()),
                    IsValid = (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None),
                    Accepted = allowCertificate,
                    Message = certificateValidationMessage.ToString()
                };

            certificateValidationResults.Push(certificateValidationResult);
            return allowCertificate;
        }

        public static void SetDebugCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
        }

        public static void SetDefaultCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = null;
        }

        public static void ClearCertificateValidationResults()
        {
            certificateValidationResults.Clear();
        }
    }
}
'@

function Set-CertificateValidationMode
{
    <#
    .SYNOPSIS
    Sets the certificate validation mode.
    .DESCRIPTION
    Set the certificate validation mode to one of three modes with the following behaviors:
        Default -- Performs the .NET default validation of certificates. Certificates are not checked for revocation and will be rejected if invalid.
        CheckRevocationList -- Cerftificate Revocation Lists are checked and certificate will be rejected if revoked or invalid.
        Debug -- Certificate Revocation Lists are checked and revocation will result in rejection. Invalid certificates will be accepted. Certificate validation
                 information is logged and can be retrieved from the certificate handler.
    .EXAMPLE
    Set-CertificateValidationMode Debug
    .PARAMETER Mode
    The mode for certificate validation.
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param
    (
        [Parameter()]
        [ValidateSet('Default', 'CheckRevocationList', 'Debug')]
        [string] $Mode
    )

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        switch ($Mode)
        {
            'Debug'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDebugCertificateValidation()
            }
            'CheckRevocationList'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
            'Default'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $false
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
        }
    }
}

function Clear-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Clears the collection of certificate validation results.
    .DESCRIPTION
    Clears the collection of certificate validation results.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        [CertificateValidation.CertificateValidator]::ClearCertificateValidationResults()
        Sleep -Milliseconds 20
    }
}

function Get-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug cerificate validation mode was enabled.
    .DESCRIPTION
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug certificate validation mode was enabled in reverse chronological order.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        return [CertificateValidation.CertificateValidator]::CertificateValidationResults
    }
}

function Test-WebUrl
{
    <#
    .SYNOPSIS
    Tests and reports information about the provided web URL.
    .DESCRIPTION
    Tests a web URL and reports the time taken to get and process the request and response, the HTTP status, and the error message if an error occurred.
    .EXAMPLE
    Test-WebUrl 'http://websitetotest.com/'
    .EXAMPLE
    'https://websitetotest.com/' | Test-WebUrl
    .PARAMETER HostName
    The Hostname to add to the back connection hostnames list.
    .PARAMETER UseDefaultCredentials
    If present the default Windows credential will be used to attempt to authenticate to the URL; otherwise, no credentials will be presented.
    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Uri] $Url,
        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get',
        [Parameter()]
        [switch] $UseDefaultCredentials
    )

    process
    {
        [bool] $succeeded = $false
        [string] $statusCode = $null
        [string] $statusDescription = $null
        [string] $message = $null
        [int] $bytesReceived = 0
        [Timespan] $timeTaken = [Timespan]::Zero 

        $timeTaken = Measure-Command `
            {
                try
                {
                    [Microsoft.PowerShell.Commands.HtmlWebResponseObject] $response = Invoke-WebRequest -UseDefaultCredentials:$UseDefaultCredentials -Method $Method -Uri $Url
                    $succeeded = $true
                    $statusCode = $response.StatusCode.ToString('D')
                    $statusDescription = $response.StatusDescription
                    $bytesReceived = $response.RawContent.Length

                    Write-Verbose "$($Url.ToString()): $($statusCode) $($statusDescription) $($message)"
                }
                catch [System.Net.WebException]
                {
                    $message = $Error[0].Exception.Message
                    [System.Net.HttpWebResponse] $exceptionResponse = $Error[0].Exception.GetBaseException().Response

                    if ($exceptionResponse -ne $null)
                    {
                        $statusCode = $exceptionResponse.StatusCode.ToString('D')
                        $statusDescription = $exceptionResponse.StatusDescription
                        $bytesReceived = $exceptionResponse.ContentLength

                        if ($statusCode -in '401', '403', '404')
                        {
                            $succeeded = $true
                        }
                    }
                    else
                    {
                        Write-Warning "$($Url.ToString()): $($message)"
                    }
                }
            }

        return [PSCustomObject] @{ Url = $Url; Succeeded = $succeeded; BytesReceived = $bytesReceived; TimeTaken = $timeTaken.TotalMilliseconds; StatusCode = $statusCode; StatusDescription = $statusDescription; Message = $message; }
    }
}

Set-CertificateValidationMode Debug
Clear-CertificateValidationResults

Write-Host 'Testing web sites:'
'https://expired.badssl.com/', 'https://wrong.host.badssl.com/', 'https://self-signed.badssl.com/', 'https://untrusted-root.badssl.com/', 'https://revoked.badssl.com/', 'https://pinning-test.badssl.com/', 'https://sha1-intermediate.badssl.com/' | Test-WebUrl | ft -AutoSize

Write-Host 'Certificate validation results (most recent first):'
Get-CertificateValidationResults | ft -AutoSize

"document.getElementByClass is not a function"

The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)

_x000D_
_x000D_
function stop(ta) {_x000D_
  console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
  ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
_x000D_
_x000D_

Why doesn't JavaScript support multithreading?

However you can use eval function to bring concurrency TO SOME EXTENT

/* content of the threads to be run */
var threads = [
        [
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');",
            "document.write('Foo <br/>');"
        ],
        [
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');",
            "document.write('Bar <br/>');"
        ]
    ];

window.onload = function() {
    var lines = 0, quantum = 3, max = 0;

    /* get the longer thread length */
    for(var i=0; i<threads.length; i++) {
        if(max < threads[i].length) {
            max = threads[i].length;
        }
    }

    /* execute them */
    while(lines < max) {
        for(var i=0; i<threads.length; i++) {
            for(var j = lines; j < threads[i].length && j < (lines + quantum); j++) {
                eval(threads[i][j]);
            }
        }
        lines += quantum;
    }
}

dictionary update sequence element #0 has length 3; 2 is required

I was getting this error when I was updating the dictionary with the wrong syntax:

Try with these:

lineItem.values.update({attribute,value})

instead of

lineItem.values.update({attribute:value})

Prevent textbox autofill with previously entered values

For firefox

Either:

<asp:TextBox id="Textbox1" runat="server" autocomplete="off"></asp:TextBox>

Or from the CodeBehind:

Textbox1.Attributes.Add("autocomplete", "off");

Getting input values from text box

This is the sample code for the email and javascript.

params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += "      Query:    ";
content += unescape(params["FormsMultiLine4"]);
var email = "[email protected]";
document.write('<a href="mailto:'+email+'?subject='+subject+'&body='+content+'">SUBMIT QUERY</a>');

Check whether a cell contains a substring

This formula seems more intuitive to me:

=SUBSTITUTE(A1,"SomeText","") <> A1

this returns TRUE if "SomeText" is contained within A1.

The IsNumber/Search and IsError/Find formulas mentioned in the other answers certainly do work, but I always find myself needing to look at the help or experimenting in Excel too often with those ones.

Checking to see if a DateTime variable has had a value assigned

DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:

DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;

console.writeline and System.out.println

Here are the primary differences between using System.out/.err/.in and System.console():

  • System.console() returns null if your application is not run in a terminal (though you can handle this in your application)
  • System.console() provides methods for reading password without echoing characters
  • System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding

This latter behaviour may not be immediately obvious, but code like this can demonstrate the difference:

public class ConsoleDemo {
  public static void main(String[] args) {
    String[] data = { "\u250C\u2500\u2500\u2500\u2500\u2500\u2510", 
        "\u2502Hello\u2502",
        "\u2514\u2500\u2500\u2500\u2500\u2500\u2518" };
    for (String s : data) {
      System.out.println(s);
    }
    for (String s : data) {
      System.console().writer().println(s);
    }
  }
}

On my Windows XP which has a system encoding of windows-1252 and a default console encoding of IBM850, this code will write:

???????
?Hello?
???????
+-----+
¦Hello¦
+-----+

Note that this behaviour depends on the console encoding being set to a different encoding to the system encoding. This is the default behaviour on Windows for a bunch of historical reasons.

How to add CORS request in header in Angular 5

In my experience the plugins worked with HTTP but not with the latest httpClient. Also, configuring the CORS response headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server.

Read more about this here.

proxy.conf.json file:

{
  "/posts": {
    "target": "https://example.com",
    "secure": true,
    "pathRewrite": {
    "^/posts": ""
  },
    "changeOrigin": true
  }
}

I placed the proxy.conf.json file right next the the package.json file in the same directory.

Then I modified the start command in the package.json file:

"start": "ng serve --proxy-config proxy.conf.json"

The HTTP call from my app component:

return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
  console.log(returnedStuff);
});

Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json

ERROR: Cannot open source file " "

  1. Copy the contents of the file,
  2. Create an .h file, give it the name of the original .h file
  3. Copy the contents of the original file to the newly created one
  4. Build it
  5. VOILA!!

jquery change div text

I think this will do:

$('#'+div_id+' .widget-head > span').text("new dialog title");

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Check if string contains only whitespace

I'm assuming in your scenario, an empty string is a string that is truly empty or one that contains all white space.

if(str.strip()):
    print("string is not empty")
else:
    print("string is empty")

Note this does not check for None

Get last record of a table in Postgres

you can use

SELECT timestamp, value, card 
FROM my_table 
ORDER BY timestamp DESC 
LIMIT 1

assuming you want also to sort by timestamp?

how to select rows based on distinct values of A COLUMN only

use this(assume that your table name is emails):

select * from emails as a 
inner join  
(select EmailAddress, min(Id) as id from emails 
group by EmailAddress ) as b 
on a.EmailAddress = b.EmailAddress 
and a.Id = b.id

hope this help..

Sample random rows in dataframe

Select a Random sample from a tibble type in R:

library("tibble")    
a <- your_tibble[sample(1:nrow(your_tibble), 150),]

nrow takes a tibble and returns the number of rows. The first parameter passed to sample is a range from 1 to the end of your tibble. The second parameter passed to sample, 150, is how many random samplings you want. The square bracket slicing specifies the rows of the indices returned. Variable 'a' gets the value of the random sampling.

SQL split values to multiple rows

My variant: stored procedure that takes table name, field names and delimiter as arguments. Inspired by post http://www.marcogoncalves.com/2011/03/mysql-split-column-string-into-rows/

delimiter $$

DROP PROCEDURE IF EXISTS split_value_into_multiple_rows $$
CREATE PROCEDURE split_value_into_multiple_rows(tablename VARCHAR(20),
    id_column VARCHAR(20), value_column VARCHAR(20), delim CHAR(1))
  BEGIN
    DECLARE id INT DEFAULT 0;
    DECLARE value VARCHAR(255);
    DECLARE occurrences INT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE splitted_value VARCHAR(255);
    DECLARE done INT DEFAULT 0;
    DECLARE cur CURSOR FOR SELECT tmp_table1.id, tmp_table1.value FROM 
        tmp_table1 WHERE tmp_table1.value IS NOT NULL AND tmp_table1.value != '';
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SET @expr = CONCAT('CREATE TEMPORARY TABLE tmp_table1 (id INT NOT NULL, value VARCHAR(255)) ENGINE=Memory SELECT ',
        id_column,' id, ', value_column,' value FROM ',tablename);
    PREPARE stmt FROM @expr;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    DROP TEMPORARY TABLE IF EXISTS tmp_table2;
    CREATE TEMPORARY TABLE tmp_table2 (id INT NOT NULL, value VARCHAR(255) NOT NULL) ENGINE=Memory;

    OPEN cur;
      read_loop: LOOP
        FETCH cur INTO id, value;
        IF done THEN
          LEAVE read_loop;
        END IF;

        SET occurrences = (SELECT CHAR_LENGTH(value) -
                           CHAR_LENGTH(REPLACE(value, delim, '')) + 1);
        SET i=1;
        WHILE i <= occurrences DO
          SET splitted_value = (SELECT TRIM(SUBSTRING_INDEX(
              SUBSTRING_INDEX(value, delim, i), delim, -1)));
          INSERT INTO tmp_table2 VALUES (id, splitted_value);
          SET i = i + 1;
        END WHILE;
      END LOOP;

      SELECT * FROM tmp_table2;
    CLOSE cur;
    DROP TEMPORARY TABLE tmp_table1;
  END; $$

delimiter ;

Usage example (normalization):

CALL split_value_into_multiple_rows('my_contacts', 'contact_id', 'interests', ',');

CREATE TABLE interests (
  interest_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  interest VARCHAR(30) NOT NULL
) SELECT DISTINCT value interest FROM tmp_table2;

CREATE TABLE contact_interest (
  contact_id INT NOT NULL,
  interest_id INT NOT NULL,
  CONSTRAINT fk_contact_interest_my_contacts_contact_id FOREIGN KEY (contact_id) REFERENCES my_contacts (contact_id),
  CONSTRAINT fk_contact_interest_interests_interest_id FOREIGN KEY (interest_id) REFERENCES interests (interest_id)
) SELECT my_contacts.contact_id, interests.interest_id
    FROM my_contacts, tmp_table2, interests
    WHERE my_contacts.contact_id = tmp_table2.id AND interests.interest = tmp_table2.value;

Intersection and union of ArrayLists in Java

public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
    Set<T> set1, set2;
    if (col1 instanceof Set) {
        set1 = (Set) col1;
    } else {
        set1 = new HashSet<>(col1);
    }

    if (col2 instanceof Set) {
        set2 = (Set) col2;
    } else {
        set2 = new HashSet<>(col2);
    }

    Set<T> intersection = new HashSet<>(Math.min(set1.size(), set2.size()));

    for (T t : set1) {
        if (set2.contains(t)) {
            intersection.add(t);
        }
    }

    return intersection;
}

JDK8+ (Probably Best Performance)

public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
    boolean isCol1Larger = col1.size() > col2.size();
    Set<T> largerSet;
    Collection<T> smallerCol;

    if (isCol1Larger) {
        if (col1 instanceof Set) {
            largerSet = (Set<T>) col1;
        } else {
            largerSet = new HashSet<>(col1);
        }
        smallerCol = col2;
    } else {
        if (col2 instanceof Set) {
            largerSet = (Set<T>) col2;
        } else {
            largerSet = new HashSet<>(col2);
        }
        smallerCol = col1;
    }

    return smallerCol.stream()
            .filter(largerSet::contains)
            .collect(Collectors.toSet());
}

If you don't care about performance and prefer smaller code just use:

col1.stream().filter(col2::contains).collect(Collectors.toList());

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

Java - JPA - @Version annotation

Version used to ensure that only one update in a time. JPA provider will check the version, if the expected version already increase then someone else already update the entity so an exception will be thrown.

So updating entity value would be more secure, more optimist.

If the value changes frequent, then you might consider not to use version field. For an example "an entity that has counter field, that will increased everytime a web page accessed"

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

In where shall I use isset() and !empty()

isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.

So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:

$var = "";
var_dump(isset($var));

The type comparison tables in PHP’s manual is quite handy for such questions.

isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)

Where does mysql store data?

From here:

Windows

  1. Locate the my.ini, which store in the MySQL installation folder.

For Example, C:\Program Files\MySQL\MySQL Server 5.1\my.ini

  1. Open the “my.ini” with our favor text editor.
#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files/MySQL/MySQL Server 5.1/"
 
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"

Find the “datadir”, this is the where does MySQL stored the data in Windows.


Linux

  1. Locate the my.cnf with the find / -name my.cnf command.
yongmo@myserver:~$ find / -name my.cnf
find: /home/lost+found: Permission denied
find: /lost+found: Permission denied
/etc/mysql/my.cnf
  1. View the my.cnf file like this: cat /etc/mysql/my.cnf
yongmo@myserver:~$ cat /etc/mysql/my.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
[mysqld]
#
# * Basic Settings
#
user   = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket  = /var/run/mysqld/mysqld.sock
port   = 3306
basedir  = /usr
datadir  = /var/lib/mysql
tmpdir  = /tmp
language = /usr/share/mysql/english
skip-external-locking
  1. Find the “datadir”, this is where does MySQL stored the data in Linux system.

Import data into Google Colaboratory

You can also use my implementations on google.colab and PyDrive at https://github.com/ruelj2/Google_drive which makes it a lot easier.

!pip install - U - q PyDrive  
import os  
os.chdir('/content/')  
!git clone https://github.com/ruelj2/Google_drive.git  

from Google_drive.handle import Google_drive  
Gd = Google_drive()  

Then, if you want to load all files in a Google Drive directory, just

Gd.load_all(local_dir, drive_dir_ID, force=False)  

Or just a specific file with

Gd.load_file(local_dir, file_ID)

Have Excel formulas that return 0, make the result blank

Use conditional formatting (Home tab, styles section) and apply highlight cells rule (putting 0 in the Format cells that are equal to box) but select custom format then the Number tab. Select Category custom and in the type box put:

0;-0;;@

Sounds complicated but is actually simple.

This gives the advantage that the cell looks empty but 0 is still the underlying value, so any formulas you use against that cell/selection will still see it as being numeric and saves on lots of messing around with chained IF statements.

Border length smaller than div width?

I added line under under h3 tag like this

<h3 class="home_title">Your title here</h3> 
.home_title{
    display:block;
}
.home_title:after {
    display:block;
    clear:both;
    content : "";
    position: relative;
    left    : 0;
    bottom  : 0;
    max-width:250px;
    height  : 1px;
    width   : 50%;  /* or 100px */
    border-bottom:1px solid #e2000f;
    margin:0 auto;
    padding:4px 0px;
}

Manipulate a url string by adding GET parameters

$parameters = array();

foreach ($get as $key => $value)
{
     $parameters[] = $key.'='.$value;
}

$url = 'http://example.com/movies?'.implode('&', $parameters);

How to fix "The ConnectionString property has not been initialized"

Use [] instead of () as below example.

SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
            DataTable data = new DataTable();
            DataSet ds = new DataSet();

SQLite UPSERT / UPDATE OR INSERT

Q&A Style

Well, after researching and fighting with the problem for hours, I found out that there are two ways to accomplish this, depending on the structure of your table and if you have foreign keys restrictions activated to maintain integrity. I'd like to share this in a clean format to save some time to the people that may be in my situation.


Option 1: You can afford deleting the row

In other words, you don't have foreign key, or if you have them, your SQLite engine is configured so that there no are integrity exceptions. The way to go is INSERT OR REPLACE. If you are trying to insert/update a player whose ID already exists, the SQLite engine will delete that row and insert the data you are providing. Now the question comes: what to do to keep the old ID associated?

Let's say we want to UPSERT with the data user_name='steven' and age=32.

Look at this code:

INSERT INTO players (id, name, age)

VALUES (
    coalesce((select id from players where user_name='steven'),
             (select max(id) from drawings) + 1),
    32)

The trick is in coalesce. It returns the id of the user 'steven' if any, and otherwise, it returns a new fresh id.


Option 2: You cannot afford deleting the row

After monkeying around with the previous solution, I realized that in my case that could end up destroying data, since this ID works as a foreign key for other table. Besides, I created the table with the clause ON DELETE CASCADE, which would mean that it'd delete data silently. Dangerous.

So, I first thought of a IF clause, but SQLite only has CASE. And this CASE can't be used (or at least I did not manage it) to perform one UPDATE query if EXISTS(select id from players where user_name='steven'), and INSERT if it didn't. No go.

And then, finally I used the brute force, with success. The logic is, for each UPSERT that you want to perform, first execute a INSERT OR IGNORE to make sure there is a row with our user, and then execute an UPDATE query with exactly the same data you tried to insert.

Same data as before: user_name='steven' and age=32.

-- make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

-- make sure it has the right data
UPDATE players SET user_name='steven', age=32 WHERE user_name='steven'; 

And that's all!

EDIT

As Andy has commented, trying to insert first and then update may lead to firing triggers more often than expected. This is not in my opinion a data safety issue, but it is true that firing unnecessary events makes little sense. Therefore, a improved solution would be:

-- Try to update any existing row
UPDATE players SET age=32 WHERE user_name='steven';

-- Make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

How to disable anchor "jump" when loading a page?

Does your fix not work? I'm not sure if I understand the question correctly - do you have a demo page? You could try:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}

Edit: tested and works in Firefox, IE & Chrome on Windows.
Edit 2: move setTimeout() inside if block, props @vsync.

How do I use method overloading in Python?

Python 3.x includes standard typing library which allows for method overloading with the use of @overload decorator. Unfortunately, this is to make the code more readable, as the @overload decorated methods will need to be followed by a non-decorated method that handles different arguments. More can be found here here but for your example:

from typing import overload
from typing import Any, Optional
class A(object):
    @overload
    def stackoverflow(self) -> None:    
        print('first method')
    @overload
    def stackoverflow(self, i: Any) -> None:
        print('second method', i)
    def stackoverflow(self, i: Optional[Any] = None) -> None:
        if not i:
            print('first method')
        else:
            print('second method', i)

ob=A()
ob.stackoverflow(2)

How can I read and manipulate CSV file data in C++?

You can try the Boost Tokenizer library, in particular the Escaped List Separator

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.

But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.

This may help to understand:

public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy).

Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:

public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).

This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that

  • it's a bit slower (having to maintain another table and joins uses three tables instead of just two),
  • the join syntax is more complex (which can be tedious if you have to manually write many queries, for example when you try to debug something)
  • it's more error prone because you can suddenly get too many or too few results when something goes wrong in the code which manages the connection table.

That's why I rarely recommend this approach.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

I had this same problem too, and it was tricky. For me, it was because I'm using Ext.Js javascript library. If you are doing a response.redirect in server-side code that you accessed in an Ajax call, there are problems. Ext.js has a workaround with their Ext.Redirect method.

Server.Mappath in C# classlibrary

Architecturally, System.web should not be referred in Business Logic Layer (BLL). Employ BLL into the solution structure to follow the separate of concern principle so refer System.Web is a bad practice. BLL should not load/run in Asp.net context. Because of the reason you should consider using of System.AppDomain.CurrentDomain.BaseDirectory instead of System.Web.HttpContext.Current.Server.MapPath

Last non-empty cell in a column

Using following simple formula is much faster

=LOOKUP(2,1/(A:A<>""),A:A)

For Excel 2003:

=LOOKUP(2,1/(A1:A65535<>""),A1:A65535)

It gives you following advantages:

  • it's not array formula
  • it's not volatile formula

Explanation:

  • (A:A<>"") returns array {TRUE,TRUE,..,FALSE,..}
  • 1/(A:A<>"") modifies this array to {1,1,..,#DIV/0!,..}.
  • Since LOOKUP expects sorted array in ascending order, and taking into account that if the LOOKUP function can not find an exact match, it chooses the largest value in the lookup_range (in our case {1,1,..,#DIV/0!,..}) that is less than or equal to the value (in our case 2), formula finds last 1 in array and returns corresponding value from result_range (third parameter - A:A).

Also little note - above formula doesn't take into account cells with errors (you can see it only if last non empty cell has error). If you want to take them into account, use:

=LOOKUP(2,1/(NOT(ISBLANK(A:A))),A:A)

image below shows the difference:

enter image description here

Best way to find the months between two dates

Assuming that you wanted to know the "fraction" of the month that dates were in, which I did, then you need to do a bit more work.

from datetime import datetime, date
import calendar

def monthdiff(start_period, end_period, decimal_places = 2):
    if start_period > end_period:
        raise Exception('Start is after end')
    if start_period.year == end_period.year and start_period.month == end_period.month:
        days_in_month = calendar.monthrange(start_period.year, start_period.month)[1]
        days_to_charge = end_period.day - start_period.day+1
        diff = round(float(days_to_charge)/float(days_in_month), decimal_places)
        return diff
    months = 0
    # we have a start date within one month and not at the start, and an end date that is not
    # in the same month as the start date
    if start_period.day > 1:
        last_day_in_start_month = calendar.monthrange(start_period.year, start_period.month)[1]
        days_to_charge = last_day_in_start_month - start_period.day +1
        months = months + round(float(days_to_charge)/float(last_day_in_start_month), decimal_places)
        start_period = datetime(start_period.year, start_period.month+1, 1)

    last_day_in_last_month = calendar.monthrange(end_period.year, end_period.month)[1]
    if end_period.day != last_day_in_last_month:
        # we have lest days in the last month
        months = months + round(float(end_period.day) / float(last_day_in_last_month), decimal_places)
        last_day_in_previous_month = calendar.monthrange(end_period.year, end_period.month - 1)[1]
        end_period = datetime(end_period.year, end_period.month - 1, last_day_in_previous_month)

    #whatever happens, we now have a period of whole months to calculate the difference between

    if start_period != end_period:
        months = months + (end_period.year - start_period.year) * 12 + (end_period.month - start_period.month) + 1

    # just counter for any final decimal place manipulation
    diff = round(months, decimal_places)
    return diff

assert monthdiff(datetime(2015,1,1), datetime(2015,1,31)) == 1
assert monthdiff(datetime(2015,1,1), datetime(2015,02,01)) == 1.04
assert monthdiff(datetime(2014,1,1), datetime(2014,12,31)) == 12
assert monthdiff(datetime(2014,7,1), datetime(2015,06,30)) == 12
assert monthdiff(datetime(2015,1,10), datetime(2015,01,20)) == 0.35
assert monthdiff(datetime(2015,1,10), datetime(2015,02,20)) == 0.71 + 0.71
assert monthdiff(datetime(2015,1,31), datetime(2015,02,01)) == round(1.0/31.0,2) + round(1.0/28.0,2)
assert monthdiff(datetime(2013,1,31), datetime(2015,02,01)) == 12*2 + round(1.0/31.0,2) + round(1.0/28.0,2)

provides an example that works out the number of months between two dates inclusively, including the fraction of each month that the date is in. This means that you can work out how many months is between 2015-01-20 and 2015-02-14, where the fraction of the date in the month of January is determined by the number of days in January; or equally taking into account that the number of days in February can change form year to year.

For my reference, this code is also on github - https://gist.github.com/andrewyager/6b9284a4f1cdb1779b10

Run Java Code Online

I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com

How do I monitor the computer's CPU, memory, and disk usage in Java?

The following code is Linux (maybe Unix) only, but it works in a real project.

    private double getAverageValueByLinux() throws InterruptedException {
    try {

        long delay = 50;
        List<Double> listValues = new ArrayList<Double>();
        for (int i = 0; i < 100; i++) {
            long cput1 = getCpuT();
            Thread.sleep(delay);
            long cput2 = getCpuT();
            double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
            listValues.add(cpuproc);
        }
        listValues.remove(0);
        listValues.remove(listValues.size() - 1);
        double sum = 0.0;
        for (Double double1 : listValues) {
            sum += double1;
        }
        return sum / listValues.size();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }

}

private long getCpuT throws FileNotFoundException, IOException {
    BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
    String line = reader.readLine();
    Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
    Matcher m = pattern.matcher(line);

    long cpuUser = 0;
    long cpuSystem = 0;
    if (m.find()) {
        cpuUser = Long.parseLong(m.group(1));
        cpuSystem = Long.parseLong(m.group(3));
    }
    return cpuUser + cpuSystem;
}

Laravel is there a way to add values to a request array

The best one I have used and researched on it is $request->merge([]) (Check My Piece of Code):

public function index(Request $request) {
    not_permissions_redirect(have_premission(2));
    $filters = (!empty($request->all())) ? true : false;
    $request->merge(['type' => 'admin']);
    $users = $this->service->getAllUsers($request->all());
    $roles = $this->roles->getAllAdminRoles();
    return view('users.list', compact(['users', 'roles', 'filters']));
}

Check line # 3 inside the index function.

How do I add the contents of an iterable to a set?

For the benefit of anyone who might believe e.g. that doing aset.add() in a loop would have performance competitive with doing aset.update(), here's an example of how you can test your beliefs quickly before going public:

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 294 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 950 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 458 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 598 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 1.89 msec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 891 usec per loop

Looks like the cost per item of the loop approach is over THREE times that of the update approach.

Using |= set() costs about 1.5x what update does but half of what adding each individual item in a loop does.

Add padding on view programmatically

You can set padding to your view by pro grammatically throughout below code -

view.setPadding(0,1,20,3);

And, also there are different type of padding available -

Padding

PaddingBottom

PaddingLeft

PaddingRight

PaddingTop

These, links will refer Android Developers site. Hope this helps you lot.

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

HTML form readonly SELECT tag/input

If you are using jquery validate, you can do the following below, I used the disabled attribute without a problem:

$(function(){
    $('#myform').validate({
        submitHandler:function(form){
            $('select').removeAttr('disabled');
            form.submit();
        }
    });
});

How to generate random colors in matplotlib?

If you want to ensure the colours are distinct - but don't know how many colours are needed. Try something like this. It selects colours from opposite sides of the spectrum and systematically increases granularity.

import math

def calc(val, max = 16):
    if val < 1:
        return 0
    if val == 1:
        return max

    l = math.floor(math.log2(val-1))    #level 
    d = max/2**(l+1)                    #devision
    n = val-2**l                        #node
    return d*(2*n-1)
import matplotlib.pyplot as plt

N = 16
cmap = cmap = plt.cm.get_cmap('gist_rainbow', N)

fig, axs = plt.subplots(2)
for ax in axs:
    ax.set_xlim([ 0, N])
    ax.set_ylim([-0.5, 0.5])
    ax.set_yticks([])

for i in range(0,N+1):
    v = int(calc(i, max = N))
    rect0 = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(i))
    rect1 = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(v))
    axs[0].add_artist(rect0)
    axs[1].add_artist(rect1)

plt.xticks(range(0, N), [int(calc(i, N)) for i in range(0, N)])
plt.show()

output

Thanks to @Ali for providing the base implementation.

Working with dictionaries/lists in R

Yes, the list type is a good approximation. You can use names() on your list to set and retrieve the 'keys':

> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12

$tac
[1] 22

$toe
[1] 33

> names(foo)
[1] "tic" "tac" "toe"
> 

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

Most efficient way to check if a file is empty in Java on Windows

String line = br.readLine();
String[] splitted = line.split("anySplitCharacter");
if(splitted.length == 0)
    //file is empty
else
    //file is not empty

I had the same problem with my text file. Although it was empty, the value being returned by the readLine method was not null. Therefore, I tried to assign its value to the String array which I was using to access the splitted attributes of my data. It did work for me. Try this out and tell me if it works for u as well.

diff to output only the file names

You can also use rsync

rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out

Windows- Pyinstaller Error "failed to execute script " When App Clicked

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing '-w' from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command : " --hidden-import = missingmodule "

I solved my problem through this.

How can I time a code segment for testing performance with Pythons timeit?

Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.

And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).

That said, you can simply put your code in a function and run that function with timeit.timeit():

def function_to_repeat():
    # ...

duration = timeit.timeit(function_to_repeat, number=1000)

This would disable the garbage collection, repeatedly call the function_to_repeat() function, and time the total duration of those calls using timeit.default_timer(), which is the most accurate available clock for your specific platform.

You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup argument to either import or create those dependencies, and pass them into your function:

def function_to_repeat(var1, var2):
    # ...

duration = timeit.timeit(
    'function_to_repeat(var1, var2)',
    'from __main__ import function_to_repeat, var1, var2', 
    number=1000)

would grab the globals function_to_repeat, var1 and var2 from your script and pass those to the function each repetition.

SLF4J: Class path contains multiple SLF4J bindings

I just ignored/removed that jar file.

enter image description here

Collapsing Sidebar with Bootstrap

http://getbootstrap.com/examples/offcanvas/

This is the official example, may be better for some. It is under their Experiments examples section, but since it is official, it should be kept up to date with the current bootstrap release.

Looks like they have added an off canvas css file used in their example:

http://getbootstrap.com/examples/offcanvas/offcanvas.css

And some JS code:

$(document).ready(function () {
  $('[data-toggle="offcanvas"]').click(function () {
    $('.row-offcanvas').toggleClass('active')
  });
});

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

I suffered alot trying to find a solution to it and finally I found the solution by first setting the jre path to system variables by navigating to::

control panel > System and Security > System > Advanced system settings 

Under System variables click on new

Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin

Where Variable value should be the path to your JDK's bin folder.

Then open command prompt and Change directory to the same JDK's bin folder like this

C:\Program Files (x86)\Java\jre1.8.0_171\bin 

then copy and paste the code below in cmd

keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android   

How to get date representing the first day of a month?

select last_day(add_months(sysdate,-1))+1 from dual;

How to add an object to an ArrayList in Java

You need to use the new operator when creating the object

Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step

or else

Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list

and your constructor shouldn't contain void. Else it becomes a method in your class.

public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such

Show empty string when date field is 1/1/1900

Use this inside of query, no need to create extra variables.

CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN ''  ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'

Works like a charm.

Check if list contains element that contains a string and get that element

If you want a list of strings containing your string:

var newList = myList.Where(x => x.Contains(myString)).ToList();

Another option is to use Linq FirstOrDefault

var element = myList.Where(x => x.Contains(myString)).FirstOrDefault();

Keep in mind that Contains method is case sensitive.

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

How do I compute derivative using Numpy?

You can use scipy, which is pretty straight forward:

scipy.misc.derivative(func, x0, dx=1.0, n=1, args=(), order=3)

Find the nth derivative of a function at a point.

In your case:

from scipy.misc import derivative

def f(x):
    return x**2 + 1

derivative(f, 5, dx=1e-6)
# 10.00000000139778

Lightweight workflow engine for Java

I'd recommend you yo use an out-of-the-box solution. Given that the development of a workflow engine requires a vast amount of resources and time, a ready-made engine is a better option. Have a look at Workflow Engine. It's a lightweight component that enables you to add custom executable workflows of any complexity to any Java solutions.

How to search for rows containing a substring?

Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

What is the purpose of nameof?

Previously we were using something like that:

// Some form.
SetFieldReadOnly( () => Entity.UserName );
...
// Base form.
private void SetFieldReadOnly(Expression<Func<object>> property)
{
    var propName = GetPropNameFromExpr(property);
    SetFieldsReadOnly(propName);
}

private void SetFieldReadOnly(string propertyName)
{
    ...
}

Reason - compile time safety. No one can silently rename property and break code logic. Now we can use nameof().

How to get the current time in milliseconds from C in Linux?

C11 timespec_get

It returns up to nanoseconds, rounded to the resolution of the implementation.

It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime.

#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

More details here: https://stackoverflow.com/a/36095407/895245

How to delete an element from a Slice in Golang

Minor point (code golf), but in the case where order does not matter you don't need to swap the values. Just overwrite the array position being removed with a duplicate of the last position and then return a truncated array.

func remove(s []int, i int) []int {
    s[i] = s[len(s)-1]
    return s[:len(s)-1]
}

Same result.

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

Passing capturing lambda as function pointer

A simular answer but i made it so you don't have to specify the type of returned pointer (note that the generic version requires C++20):

#include <iostream>


template<typename Function>
struct function_traits;

template <typename Ret, typename... Args>
struct function_traits<Ret(Args...)> {
    typedef Ret(*ptr)(Args...);
};

template <typename Ret, typename... Args>
struct function_traits<Ret(*const)(Args...)> : function_traits<Ret(Args...)> {};

template <typename Cls, typename Ret, typename... Args>
struct function_traits<Ret(Cls::*)(Args...) const> : function_traits<Ret(Args...)> {};

using voidfun = void(*)();

template <typename F>
voidfun lambda_to_void_function(F lambda) {
    static auto lambda_copy = lambda;

    return []() {
        lambda_copy();
    };
}

// requires C++20
template <typename F>
auto lambda_to_pointer(F lambda) -> typename function_traits<decltype(&F::operator())>::ptr {
    static auto lambda_copy = lambda;
    
    return []<typename... Args>(Args... args) {
        return lambda_copy(args...);
    };
}



int main() {
    int num;

    void(*foo)() = lambda_to_void_function([&num]() {
        num = 1234;
    });
    foo();
    std::cout << num << std::endl; // 1234

    int(*bar)(int) = lambda_to_pointer([&](int a) -> int {
        num = a;
        return a;
    });
    std::cout << bar(4321) << std::endl; // 4321
    std::cout << num << std::endl; // 4321
}

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

How can I throw CHECKED exceptions from inside Java 8 streams?

You can!

Extending @marcg 's UtilException and adding throw E where necessary: this way, the compiler will ask you to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.

Instructions: just copy/paste LambdaExceptionUtil in your IDE and then use it as shown in the below LambdaExceptionUtilTest.

public final class LambdaExceptionUtil {

    @FunctionalInterface
    public interface Consumer_WithExceptions<T, E extends Exception> {
        void accept(T t) throws E;
    }

    @FunctionalInterface
    public interface Function_WithExceptions<T, R, E extends Exception> {
        R apply(T t) throws E;
    }

    /**
     * .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name))));
     */
    public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E {
        return t -> {
            try {
                consumer.accept(t);
            } catch (Exception exception) {
                throwActualException(exception);
            }
        };
    }

    /**
     * .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
     */
    public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E  {
        return t -> {
            try {
                return function.apply(t);
            } catch (Exception exception) {
                throwActualException(exception);
                return null;
            }
        };
    }

    @SuppressWarnings("unchecked")
    private static <E extends Exception> void throwActualException(Exception exception) throws E {
        throw (E) exception;
    }

}

Some test to show usage and behaviour:

public class LambdaExceptionUtilTest {

    @Test(expected = MyTestException.class)
    public void testConsumer() throws MyTestException {
        Stream.of((String)null).forEach(rethrowConsumer(s -> checkValue(s)));
    }

    private void checkValue(String value) throws MyTestException {
        if(value==null) {
            throw new MyTestException();
        }
    }

    private class MyTestException extends Exception { }

    @Test
    public void testConsumerRaisingExceptionInTheMiddle() {
        MyLongAccumulator accumulator = new MyLongAccumulator();
        try {
            Stream.of(2L, 3L, 4L, null, 5L).forEach(rethrowConsumer(s -> accumulator.add(s)));
            fail();
        } catch (MyTestException e) {
            assertEquals(9L, accumulator.acc);
        }
    }

    private class MyLongAccumulator {
        private long acc = 0;
        public void add(Long value) throws MyTestException {
            if(value==null) {
                throw new MyTestException();
            }
            acc += value;
        }
    }

    @Test
    public void testFunction() throws MyTestException {
        List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
        assertEquals(2, sizes.size());
        assertEquals(4, sizes.get(0).intValue());
        assertEquals(5, sizes.get(1).intValue());
    }

    private Integer transform(String value) throws MyTestException {
        if(value==null) {
            throw new MyTestException();
        }
        return value.length();
    }

    @Test(expected = MyTestException.class)
    public void testFunctionRaisingException() throws MyTestException {
        Stream.of("ciao", null, "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
    }

}

Sort an array in Java

Java 8 provides the option of using streams which can be used to sort int[] array as:

int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2

As mentioned in doc for parallelSort :

The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.

So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort simply calls sequential sort algorithm.

Just in case we want to reverse sort the integer array we can make use of comparator as:

int[] reverseSorted = IntStream.of(array).boxed()
                        .sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();

Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.

Converting java.util.Properties to HashMap<String,String>

i use this:

for (Map.Entry<Object, Object> entry:properties.entrySet()) {
    map.put((String) entry.getKey(), (String) entry.getValue());
}

What is the difference between Scala's case class and class?

Unlike classes, case classes are just used to hold data.

Case classes are flexible for data-centric applications, which means you can define data fields in case class and define business logic in a companion object. In this way, you are separating the data from the business logic.

With the copy method, you can inherit any or all required properties from the source and can change them as you like.

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

I started digging myself and I found one potential advantage of using setUp(). If any exceptions are thrown during the execution of setUp(), JUnit will print a very helpful stack trace. On the other hand, if an exception is thrown during object construction, the error message simply says JUnit was unable to instantiate the test case and you don't see the line number where the failure occurred, probably because JUnit uses reflection to instantiate the test classes.

None of this applies to the example of creating an empty collection, since that will never throw, but it is an advantage of the setUp() method.

Convert datetime object to a String of date only in Python

You can convert datetime to string.

published_at = "{}".format(self.published_at)

Notification bar icon turns white in Android 5 Lollipop

Post android Lollipop release android has changed the guidelines for displaying notification icons in the Notification bar. The official documentation says "Update or remove assets that involve color. The system ignores all non-alpha channels in action icons and in the main notification icon. You should assume that these icons will be alpha-only. The system draws notification icons in white and action icons in dark gray.” Now what that means in lay man terms is "Convert all parts of the image that you don’t want to show to transparent pixels. All colors and non transparent pixels are displayed in white"

You can see how to do this in detail with screenshots here https://blog.clevertap.com/fixing-notification-icon-for-android-lollipop-and-above/

Hope that helps

How to var_dump variables in twig templates?

The complete recipe here for quicker reference (note that all the steps are mandatory):

1) when instantiating Twig, pass the debug option

$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);

2) add the debug extension

$twig->addExtension(new \Twig_Extension_Debug());

3) Use it like @Hazarapet Tunanyan pointed out

{{ dump(MyVar) }}

or

{{ dump() }}

or

{{ dump(MyObject.MyPropertyName) }}

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

WordPress asking for my FTP credentials to install plugins

On OSX, I used the following, and it worked:

sudo chown -R _www:_www {path to wordpress folder}

_www is the user that PHP runs under on the Mac.

(You may also need to chmod some folders too. I had done that first and it didn't fix it. It wasn't until I did the chown command that it worked, so I'm not sure if it was the chown command alone, or a combination of chmod and chown.)

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

php string to int

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);

How do you append rows to a table using jQuery?

Try:

$("#myTable").append("<tr><%= escape_javascript( render :partial => name_of_partial ) %></tr>");

And in the partial, you should have:

<td>row1</td>
<td>row2</td>

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):
        pass

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1

Or:

class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):
        pass

thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

If a folder does not exist, create it

Directory.CreateDirectory explains how to try and to create the FilePath if it does not exist.

Directory.Exists explains how to check if a FilePath exists. However, you don't need this as CreateDirectory will check it for you.

What is the difference between Class.getResource() and ClassLoader.getResource()?

To answer the question whether there is any caching going on.

I investigated this point further by running a stand-alone Java application that continuously loaded a file from disk using the getResourceAsStream ClassLoader method. I was able to edit the file, and the changes were reflected immediately, i.e., the file was reloaded from disk without caching.

However: I'm working on a project with several maven modules and web projects that have dependencies on each other. I'm using IntelliJ as my IDE to compile and run the web projects.

I noticed that the above seemed to no longer hold true, the reason being that the file that I was being loaded is now baked into a jar and deployed to the depending web project. I only noticed this after trying to change the file in my target folder, to no avail. This made it seem as though there was caching going on.

How can I check if my python object is a number?

Sure you can use isinstance, but be aware that this is not how Python works. Python is a duck typed language. You should not explicitly check your types. A TypeError will be raised if the incorrect type was passed.

So just assume it is an int. Don't bother checking.

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

Reset IntelliJ UI to Default

The existing answers are outdated. This is now doable from the menu:

Window -> Restore Default Layout (shift+f12)

Make sure nothing is currently running, as the Run/Debug window layout will not be reset otherwise.

How to change fonts in matplotlib (python)?

Say you want Comic Sans for the title and Helvetica for the x label.

csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}

plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

Allow Access-Control-Allow-Origin header using HTML5 fetch API

This worked for me :

npm install -g local-cors-proxy

API endpoint that we want to request that has CORS issues:

https://www.yourdomain.com/test/list

Start Proxy:

lcp --proxyUrl https://www.yourdomain.com

 Proxy Active 

 Proxy Url: http://www.yourdomain.com:28080
 Proxy Partial: proxy
 PORT: 8010

Then in your client code, new API endpoint:

http://localhost:8010/proxy/test/list

End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

Main Class:

public class AndroidLocationActivity extends Activity {

Button btnGPSShowLocation;
Button btnNWShowLocation;

AppLocationService appLocationService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    appLocationService = new AppLocationService(
            AndroidLocationActivity.this);

    btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
    btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location gpsLocation = appLocationService
                    .getLocation(LocationManager.GPS_PROVIDER);

            if (gpsLocation != null) {
                double latitude = gpsLocation.getLatitude();
                double longitude = gpsLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (GPS): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();
            } else {
                showSettingsAlert("GPS");
            }

        }
    });

    btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
    btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            Location nwLocation = appLocationService
                    .getLocation(LocationManager.NETWORK_PROVIDER);

            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                Toast.makeText(
                        getApplicationContext(),
                        "Mobile Location (NW): \nLatitude: " + latitude
                                + "\nLongitude: " + longitude,
                        Toast.LENGTH_LONG).show();

            } else {
                showSettingsAlert("NETWORK");
            }

        }
    });

}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            AndroidLocationActivity.this);

    alertDialog.setTitle(provider + " SETTINGS");

    alertDialog.setMessage(provider
            + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    AndroidLocationActivity.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}

}

Next Class:

public class AppLocationService extends Service implements LocationListener {

protected LocationManager locationManager;
Location location;

private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

public AppLocationService(Context context) {
    locationManager = (LocationManager) context
            .getSystemService(LOCATION_SERVICE);
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider,
                MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }
    }
    return null;
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

Don't forget to add in your manifest.

<!-- to get location using GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- to get location using NetworkProvider -->
<uses-permission android:name="android.permission.INTERNET" />

How can I extract a predetermined range of lines from a text file on Unix?

I was looking for an answer to this but I had to end up writing my own code which worked. None of the answers above were satisfactory. Consider you have very large file and have certain line numbers that you want to print out but the numbers are not in order. You can do the following:

My relatively large file for letter in {a..k} ; do echo $letter; done | cat -n > myfile.txt

 1  a
 2  b
 3  c
 4  d
 5  e
 6  f
 7  g
 8  h
 9  i
10  j
11  k

Specific line numbers I want: shuf -i 1-11 -n 4 > line_numbers_I_want.txt

 10
 11
 4
 9

To print these line numbers, do the following. awk '{system("head myfile.txt -n " $0 " | tail -n 1")}' line_numbers_I_want.txt

What the above does is to head the n line then take the last line using tail

If you want your line numbers in order, sort ( is -n numeric sort) first then get the lines.

cat line_numbers_I_want.txt | sort -n | awk '{system("head myfile.txt -n " $0 " | tail -n 1")}'

 4  d
 9  i
10  j
11  k

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

PHP sessions that have already been started

If you want a new one, then do session_destroy() before starting it. To check if its set before starting it, call session_status() :

$status = session_status();
if($status == PHP_SESSION_NONE){
    //There is no active session
    session_start();
}else
if($status == PHP_SESSION_DISABLED){
    //Sessions are not available
}else
if($status == PHP_SESSION_ACTIVE){
    //Destroy current and start new one
    session_destroy();
    session_start();
}

I would avoid checking the global $_SESSION instead of I am calling the session_status() method since PHP implemented this function explicitly to:

Expose session status via new function, session_status This is for (PHP >=5.4.0)

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

Working with time DURATION, not time of day

You can easily do this with the normal "Time" data type - just change the format!

Excels time/date format is simply 1.0 equals 1 full day (starting on 1/1/1900). So 36 hours would be 1.5. If you change the format to [h]:mm, you'll see 36:00.

Therefore, if you want to work with durations, you can simply use subtraction, e.g.

A1: Start:           36:00 (=1.5)
A2: End:             60:00 (=2.5) 
A3: Duration: =A2-A1 24:00 (=1.0)

Batch - If, ElseIf, Else

batchfiles perform simple string substitution with variables. so, a simple

goto :language%language%
echo notfound
...

does this without any need for if.

How can I create a table with borders in Android?

I know this is an old question ... anyway ... if you want to keep your xml nice and simple you can extend TableLayout and override dispatchDraw to do some custom drawing.

Here is a quick and dirty implementation that draws a rectangle around the table view as well as horizontal and verticals bars:

public class TableLayoutEx extends TableLayout {
    private Paint linePaint = null;
    private Rect tableLayoutRect;

    public TableLayoutEx(Context context) {
        super(context);
    }

    public TableLayoutEx(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        float strokeWidth = this.getContext().getResources().getDisplayMetrics().scaledDensity * 1;
        linePaint = new Paint(0);
        linePaint.setColor(0xff555555);
        linePaint.setStrokeWidth(strokeWidth);
        linePaint.setStyle(Paint.Style.STROKE);

        Rect rect = new Rect();           
        int paddingTop= getPaddingTop();

        this.getDrawingRect(rect);
        tableLayoutRect = new Rect(rect.left, rect.top + paddingTop, rect.right, rect.bottom);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        Rect rect = new Rect();

        if (linePaint != null) {
            canvas.drawRect(tableLayoutRect, linePaint);
            float y = tableLayoutRect.top;
            for (int i = 0; i < getChildCount() - 1; i++) {
                if (getChildAt(i) instanceof TableRow) {
                    TableRow tableRow = (TableRow) getChildAt(i);
                    tableRow.getDrawingRect(rect);
                    y += rect.height();
                    canvas.drawLine(tableLayoutRect.left, y, tableLayoutRect.right, y, linePaint);
                    float x = tableLayoutRect.left;
                    for (int j = 0; j < tableRow.getChildCount() - 1; j++) {
                        View view = tableRow.getChildAt(j);
                        if (view != null) {
                            view.getDrawingRect(rect);
                            x += rect.width();
                            canvas.drawLine(x, tableLayoutRect.top, x, tableLayoutRect.bottom, linePaint);
                        }
                    }
                }
            }
        }
    }
}

xml example with the third column wrapping text:

<com.YOURPACKAGE.TableLayoutEx
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="2"
    android:paddingTop="6dp">

    <TableRow>
        <TextView
            android:text="@string/my_text_0_0"
            android:padding="@dimen/my_padding"/>
        <TextView
            android:text="@string/my_text_0_1"
            android:padding="@dimen/my_padding"/>
        <TextView                   
            android:text="@string/my_text_0_2_to_wrap"
            android:padding="@dimen/my_padding"/>
    </TableRow>

    <!--more table rows here-->

</com.YOURPACKAGE.TableLayoutEx>

How to convert AAR to JAR

Resource based .aar-projects

Finding the classes.jar file inside the .aar file is pretty trivial. However, that approach does not work, if the .aar-project defined some resources (example: R.layout.xyz)

  • Therefore deaar from CommonsGuy helped me to get a valid ADT-friendly project out of an .aar-file. In my case I converted subsampling-scale-image-view. It took me about an hour to set up ruby on my PC.

  • Another approach is using android-maven-plugin for Eclipse/ADT as CommonsGuy writes in his blog.

  • Yet another approach could be, just cloning the whole desired project as source from git and import it as "Existing Android project"

How to use executables from a package installed locally in node_modules?

Use npm-run.

From the readme:

npm-run

Find & run local executables from node_modules

Any executable available to an npm lifecycle script is available to npm-run.

Usage

$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable 

Installation

$ npm install -g npm-run

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

How to insert a new line in strings in Android

Try using System.getProperty("line.separator") to get a new line.

ASP.NET MVC Razor render without encoding

@(new HtmlString(myString))

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Try -

$("#column_select").change(function () {
    $("#layout_select").children('option').hide();
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})  

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

$(document).ready(function() {
    $("#layout_select").children('option:gt(0)').hide();
    $("#column_select").change(function() {
        $("#layout_select").children('option').hide();
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
    })
})

Demo - http://jsfiddle.net/Mxkfr/2

EDIT

I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"
        }
    })

    $("#column_select").change(function() {
        $("#layout_select").children('option').remove();
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {
                addoptarr.push(optarray[i].option);
            }
        }
        $("#layout_select").html(addoptarr.join(''))
    }).change();
})

Demo - http://jsfiddle.net/N7Xpb/1/

Checking if a variable is defined?

Leaving an incredibly simple example in case it helps.

When variable doesn't exist:

if defined? a then "hi" end
# => nil

When variable does exist:

a = 2
if defined? a then "hi" end
# => "hi"

Is it possible to display inline images from html in an Android TextView?

If you have a look at the documentation for Html.fromHtml(text) you'll see it says:

Any <img> tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.

If you don't want to do this replacement yourself you can use the other Html.fromHtml() method which takes an Html.TagHandler and an Html.ImageGetter as arguments as well as the text to parse.

In your case you could parse null as for the Html.TagHandler but you'd need to implement your own Html.ImageGetter as there isn't a default implementation.

However, the problem you're going to have is that the Html.ImageGetter needs to run synchronously and if you're downloading images from the web you'll probably want to do that asynchronously. If you can add any images you want to display as resources in your application the your ImageGetter implementation becomes a lot simpler. You could get away with something like:

private class ImageGetter implements Html.ImageGetter {

    public Drawable getDrawable(String source) {
        int id;

        if (source.equals("stack.jpg")) {
            id = R.drawable.stack;
        }
        else if (source.equals("overflow.jpg")) {
            id = R.drawable.overflow;
        }
        else {
            return null;
        }

        Drawable d = getResources().getDrawable(id);
        d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
        return d;
    }
};

You'd probably want to figure out something smarter for mapping source strings to resource IDs though.

What is the default text size on Android?

In general:

Three "default" textSize values:

 - 14sp
 - 18sp
 - 22sp

These values are defined within the following TextAppearances:

 - TextAppearance.Small
 - TextAppearance.Medium
 - TextAppearance.Large

More information about Typography can be found in the design guidelines

Related to your question:

If you don't set a custom textSize or textAppearance, TextAppearance.Small will be used.


Update: Material design:

New guidelines related to font and typefaces. The standard rule of 14sp remains (body).

Examples how to set textappearances

AppCompat version:

android:textAppearance="@style/TextAppearance.AppCompat.Body"

Lollipop and up version:

android:textAppearance="@android:style/TextAppearance.Material.Body"

SQL - HAVING vs. WHERE

Didn't see an example of both in one query. So this example might help.

  /**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/

SELECT country, city, sum(total) totalCityOrders 
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC

This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.

Maven2: Missing artifact but jars are in place

Just in order to provide one more possible solution: In my case, I removed "central" from .m2/jdom/jdom/1.0 settings, and did everything else, without results.

So I discovered my settings.xml in ./m2 folder was stuck by a failed process. As I didn't found the process in the system task manager, I restarted the computer and it worked.