Programs & Examples On #Qabstractitemmodel

QAbstractItemModel is a class in the Qt framework. It provides the abstract interface for item model classes.

How do I use FileSystemObject in VBA?

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...
Loop

fsoStream.Close
Set FSO = Nothing

Hope it help!

Best regards

Fabio

add allow_url_fopen to my php.ini using .htaccess

Try this, but I don't think it will work because you're not supposed to be able to change this

Put this line in an htaccess file in the directory you want the setting to be enabled:

php_value allow_url_fopen On

Note that this setting will only apply to PHP file's in the same directory as the htaccess file.

As an alternative to using url_fopen, try using curl.

Understanding PIVOT function in T-SQL

A PIVOT used to rotate the data from one column into multiple columns.

For your example here is a STATIC Pivot meaning you hard code the columns that you want to rotate:

create table temp
(
  id int,
  teamid int,
  userid int,
  elementid int,
  phaseid int,
  effort decimal(10, 5)
)

insert into temp values (1,1,1,3,5,6.74)
insert into temp values (2,1,1,3,6,8.25)
insert into temp values (3,1,1,4,1,2.23)
insert into temp values (4,1,1,4,5,6.8)
insert into temp values (5,1,1,4,6,1.5)

select elementid
  , [1] as phaseid1
  , [5] as phaseid5
  , [6] as phaseid6
from
(
  select elementid, phaseid, effort
  from temp
) x
pivot
(
  max(effort)
  for phaseid in([1], [5], [6])
)p

Here is a SQL Demo with a working version.

This can also be done through a dynamic PIVOT where you create the list of columns dynamically and perform the PIVOT.

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.phaseid) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT elementid, ' + @cols + ' from 
            (
                select elementid, phaseid, effort
                from temp
           ) x
            pivot 
            (
                 max(effort)
                for phaseid in (' + @cols + ')
            ) p '


execute(@query)

The results for both:

ELEMENTID   PHASEID1    PHASEID5    PHASEID6
3           Null        6.74        8.25
4           2.23        6.8         1.5

Google Maps API: open url by clicking on marker

url isn't an object on the Marker class. But there's nothing stopping you adding that as a property to that class. I'm guessing whatever example you were looking at did that too. Do you want a different URL for each marker? What happens when you do:

for (var i = 0; i < locations.length; i++) 
{
    var flag = new google.maps.MarkerImage('markers/' + (i + 1) + '.png',
      new google.maps.Size(17, 19),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 19));
    var place = locations[i];
    var myLatLng = new google.maps.LatLng(place[1], place[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: flag,
        shape: shape,
        title: place[0],
        zIndex: place[3],
        url: "/your/url/"
    });

    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
}

jQuery pass more parameters into callback

actually, your code is not working because when you write:

$.post("someurl.php",someData,doSomething(data, myDiv),"json"); 

you place a function call as the third parameter rather than a function reference.

avrdude: stk500v2_ReceiveMessage(): timeout

I had the same problem, and in my case, the solution was updating the usb-serial driver using windows update on windows 10 device's manager. There was no need to download a especific driver, I just let windows update find a suitable driver.

Twitter Bootstrap date picker

I was also facing the same problem for twitter-bootstrap.

As eternicode/bootstrap-datepicker is incompatible with jQuery UI.

But twitter-bootstrap is working fine for vitalets/bootstrap-datepicker even with jQuery UI.

How to stop mysqld

There is an alternative way of just killing the daemon process by calling

kill -TERM PID

where PID is the value stored in the file mysqld.pid or the mysqld process id which can be obtained by issuing the command ps -a | grep mysqld.

Python regular expressions return true/false

You can use re.match() or re.search(). Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default). refer this

Entity Framework change connection at runtime

Jim Tollan's answer works great, but I got the Error: Keyword not supported 'data source'. To solve this problem I had to change this part of his code:

// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
    (System.Configuration.ConfigurationManager
            .ConnectionStrings[configNameEf].ConnectionString);

to this:

// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
{
    ProviderConnectionString = new  SqlConnectionStringBuilder(System.Configuration.ConfigurationManager
               .ConnectionStrings[configNameEf].ConnectionString).ConnectionString
};

I'm really sorry. I know that I should't use answers to respond to other answers, but my answer is too long for a comment :(

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

The first error you're getting - permissions - is the most indicative. Bump wp-content and wp-admin to 777 and try it, and if it works, then change them both back to 755 and see if it still works. What are you using to change folder permissions? An FTP client?

How to use setArguments() and getArguments() methods in Fragments?

for those like me who are looking to send objects other than primitives, since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.

View JSON file in Browser

Well I was searching view json file in WebBrowser in my Desktop app, when I try in IE still same problem IE was also prompt to download the file. Luckily after too much search I find the solution for it.

You need to : Open Notepad and paste the following:

    [HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
    "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
    "Encoding"=hex:08,00,00,00
    
Save document as Json.reg and then right click on file and run as administrator.

After this You can view json file in IE and you Desktop WebBrowser enjoy :)

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

CSS get height of screen resolution

Adding to @Hendrik Eichler Answer, the n vh uses n% of the viewport's initial containing block.

.element{
    height: 50vh; /* Would mean 50% of Viewport height */
    width:  75vw; /* Would mean 75% of Viewport width*/
}

Also, the viewport height is for devices of any resolution, the view port height, width is one of the best ways (similar to css design using % values but basing it on the device's view port height and width)

vh
Equal to 1% of the height of the viewport's initial containing block.

vw
Equal to 1% of the width of the viewport's initial containing block.

vi
Equal to 1% of the size of the initial containing block, in the direction of the root element’s inline axis.

vb
Equal to 1% of the size of the initial containing block, in the direction of the root element’s block axis.

vmin
Equal to the smaller of vw and vh.

vmax
Equal to the larger of vw and vh.

Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths

How do I display todays date on SSRS report?

to display date and time, try this:

=Format(Now(), "dd/MM/yyyy hh:mm tt")

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

No Main class found in NetBeans

The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)

enter image description here

Swift addsubview and remove it

You have to use the viewWithTag function to find the view with the given tag.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject() as UITouch
    let point = touch.locationInView(self.view)

    if let viewWithTag = self.view.viewWithTag(100) {
        print("Tag 100")
        viewWithTag.removeFromSuperview()
    } else {
        print("tag not found")
    }
}

Using python map and other functional tools

How about this:

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest(foo, bar):
    print foo, bar

map(maptest, foos, [bars]*len(foos))

Apache VirtualHost 403 Forbidden

This works on Linux Fedora for VirtualHost : ( Lampp/Xampp )

Go to : /opt/lampp/etc/extra

Open : httpd-vhosts.conf

Insert this in httpd-vhosts.conf

<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "/opt/lampp/APPS/My_App"
ServerName votemo.test
ServerAlias www.votemo.test
ErrorLog "logs/votemo.test-error_log"
CustomLog "logs/votemo.test-access_log" common
<Directory "/opt/lampp/APPS/My_App">
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

p.s. : Don't forget to comment the previous exemple already present in httpd-vhosts.conf

Set your hosts system file :

Go to : /etc/ folder find hosts file ( /etc/hosts )

I insert this : (but not sure to 100% if this good)

127.0.0.1       votemo.test

::1         votemo.test

-> Open or Restart Apache.

Open a console and paste this command for open a XAMPP graphic interface :

sudo /opt/lampp/manager-linux-x64.run

Note : Adjust path how you want to your app folder

ex: DocumentRoot "/home/USER/Desktop/My_Project"

and set directory path too :

ex : ... <Directory "/home/USER/Desktop/My_Project"> ...

But this should be tested, comment if this work ...

Additionnal notes :

  • Localisation Lampp folder : (Path) /opt/lampp

  • Start Lampp : sudo /opt/lampp/lampp start

  • Adjust rights if needed : sudo chmod o+w /opt/lampp/manager-linux-x64.run

  • Path to hosts file : /etc/hosts

"’" showing on page instead of " ' "

I have some documents where was showing as … and ê was showing as ê. This is how it got there (python code):

# Adam edits original file using windows-1252
windows = '\x85\xea' 
# that is HORIZONTAL ELLIPSIS, LATIN SMALL LETTER E WITH CIRCUMFLEX

# Beth reads it correctly as windows-1252 and writes it as utf-8
utf8 = windows.decode("windows-1252").encode("utf-8")
print(utf8)

# Charlie reads it *incorrectly* as windows-1252 writes a twingled utf-8 version
twingled = utf8.decode("windows-1252").encode("utf-8")
print(twingled)

# detwingle by reading as utf-8 and writing as windows-1252 (it's really utf-8)
detwingled = twingled.decode("utf-8").encode("windows-1252")

assert utf8==detwingled

To fix the problem, I used python code like this:

with open("dirty.html","rb") as f:
    dt = f.read()
ct = dt.decode("utf8").encode("windows-1252")
with open("clean.html","wb") as g:
    g.write(ct)

(Because someone had inserted the twingled version into a correct UTF-8 document, I actually had to extract only the twingled part, detwingle it and insert it back in. I used BeautifulSoup for this.)

It is far more likely that you have a Charlie in content creation than that the web server configuration is wrong. You can also force your web browser to twingle the page by selecting windows-1252 encoding for a utf-8 document. Your web browser cannot detwingle the document that Charlie saved.

Note: the same problem can happen with any other single-byte code page (e.g. latin-1) instead of windows-1252.

How to convert minutes to Hours and minutes (hh:mm) in java

If your time is in a variable called t

int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);

It couldn't get easier

Origin <origin> is not allowed by Access-Control-Allow-Origin

I finally got the answer for apache Tomcat8

You have to edit the tomcat web.xml file.

probabily it will be inside webapps folder,

sudo gedit /opt/tomcat/webapps/your_directory/WEB-INF/web.xml

find it and edit it

<web-app>


<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>


<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>



</web-app>

This will allow Access-Control-Allow-Origin all hosts. If you need to change it from all hosts to only your host you can edit the

<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>

above code from * to your http://your_public_IP or http://www.example.com

you can refer here Tomcat filter documentation

Thanks

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

Relationship between hashCode and equals method in Java

The contract is that if obj1.equals(obj2) then obj1.hashCode() == obj2.hashCode() , it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

Difference between string and text in rails?

If the attribute is matching f.text_field in form use string, if it is matching f.text_area use text.

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

=> reads only one character from the standard input

Console.ReadLine()

=> reads all characters in the line from the standard input

How can I add new item to the String array?

String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:

<p></p>

Pressing [enter] then further expands it to:

<p>

</p>

With the cursor indented and on the line between the tags. Meaning that typing text results in:

<p>
    Hello, world!
</p>

JavaScript null check

I think, testing variables for values you do not expect is not a good idea in general. Because the test as your you can consider as writing a blacklist of forbidden values. But what if you forget to list all the forbidden values? Someone, even you, can crack your code with passing an unexpected value. So a more appropriate approach is something like whitelisting - testing variables only for the expected values, not unexpected. For example, if you expect the data value to be a string, instead of this:

function (data) {
  if (data != null && data !== undefined) {
    // some code here
    // but what if data === false?
    // or data === '' - empty string?
  }
}

do something like this:

function (data) {
  if (typeof data === 'string' && data.length) {
    // consume string here, it is here for sure
    // cleaner, it is obvious what type you expect
    // safer, less error prone due to implicit coercion
  } 
}

Regex to replace everything except numbers and a decimal point

Try this:

document.getElementById(target).value = newVal.replace(/^\d+(\.\d{0,2})?$/, "");

SSH to Elastic Beanstalk instance

I found it to be a 2-step process. This assumes that you've already set up a keypair to access EC2 instances in the relevant region.

Configure Security Group

  1. In the AWS console, open the EC2 tab.

  2. Select the relevant region and click on Security Group.

  3. You should have an elasticbeanstalk-default security group if you have launched an Elastic Beanstalk instance in that region.

  4. Edit the security group to add a rule for SSH access. The below will lock it down to only allow ingress from a specific IP address.

    SSH | tcp | 22 | 22 | 192.168.1.1/32
    

Configure the environment of your Elastic Beanstalk Application

  1. If you haven't made a key pair yet, make one by clicking Key Pairs below Security Group in the ec2 tab.
  2. In the AWS console, open the Elastic Beanstalk tab.
  3. Select the relevant region.
  4. Select relevant Environment
  5. Select Configurations in left pane.
  6. Select Security.
  7. Under "EC2 key pair:", select the name of your keypair in the Existing Key Pair field.

If after these steps you see that the Health is set Degraded

enter image description here

that's normal and it just means that the EC2 instance is being updated. Just wait on a few seconds it'll be Ok again

enter image description here

Once the instance has relaunched, you need to get the host name from the AWS Console EC2 instances tab, or via the API. You should then be able to ssh onto the server.

$ ssh -i path/to/keypair.pub [email protected]

Note: For adding a keypair to the environment configuration, the instances' termination protection must be off as Beanstalk would try to terminate the current instances and start new instances with the KeyPair.

Note: If something is not working, check the "Events" tab in the Beanstalk application / environments and find out what went wrong.

HorizontalScrollView within ScrollView Touch Handling

Thanks to Neevek his answer worked for me but it doesn't lock the vertical scrolling when user has started scrolling the horizontal view(ViewPager) in horizontal direction and then without lifting the finger scroll vertically it starts to scroll the underlying container view(ScrollView). I fixed it by making a slight change in Neevak's code:

private float xDistance, yDistance, lastX, lastY;

int lastEvent=-1;

boolean isLastEventIntercepted=false;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            xDistance = yDistance = 0f;
            lastX = ev.getX();
            lastY = ev.getY();


            break;

        case MotionEvent.ACTION_MOVE:
            final float curX = ev.getX();
            final float curY = ev.getY();
            xDistance += Math.abs(curX - lastX);
            yDistance += Math.abs(curY - lastY);
            lastX = curX;
            lastY = curY;

            if(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
                return false;
            }

            if(xDistance > yDistance )
                {

                isLastEventIntercepted=true;
                lastEvent = MotionEvent.ACTION_MOVE;
                return false;
                }


    }

    lastEvent=ev.getAction();

    isLastEventIntercepted=false;
    return super.onInterceptTouchEvent(ev);

}

Execute php file from another php

It's trying to run it as a shell script, which interprets your <?php token as bash, which is a syntax error. Just use include() or one of its friends:

For example, in a.php put:

<?php
print "one";
include 'b.php';
print "three";
?>

In b.php put:

<?php
print "two";
?>

Prints:

eric@dev ~ $ php a.php
onetwothree

Submit form without page reloading

Here is some jQuery for posting to a php page and getting html back:

$('form').submit(function() {
    $.post('tip.php', function(html) {
       // do what you need in your success callback
    }
    return false;
});

Index (zero based) must be greater than or equal to zero

String.Format must start with zero index "{0}" like this:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Foreign key referring to primary keys across multiple tables?

Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:

Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".

Then you translate this higher-level description to three tables: employees, employees_ce and employees_sn:

  • employees(id, name)
  • employees_ce(id, ce-specific stuff)
  • employees_sn(id, sn-specific stuff)

Since all employees are employees (duh!), every employee will have a row in the employees table. "ce" employees also have a row in the employees_ce table, and "sn" employees also have a row in the employees_sn table. employees_ce.id is a foreign key to employees.id, just as employees_sn.id is.

To refer to an employee of any kind (ce or sn), refer to the employees table. That is, the foreign key you had trouble with should refer to that table!

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

Cycles in family tree software

Here's the problem with family trees: they are not trees. They are directed acyclic graphs or DAGs. If I understand the principles of the biology of human reproduction correctly, there will not be any cycles.

As far as I know, even the Christians accept marriages (and thus children) between cousins, which will turn the family tree into a family DAG.

The moral of the story is: choose the right data structures.

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Resizing an Image without losing any quality

I believe what you're looking to do is "Resize/Resample" your images. Here is a good site that gives instructions and provides a utility class(That I also happen to use):

http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx

how to check the version of jar file?

Just to complete the above answer.

Manifest file is located inside jar at META-INF\MANIFEST.MF path.

You can examine jar's contents in any archiver that supports zip.

How do I hide the status bar in a Swift iOS app?

Go to your Info.plist and add two Keys:

Go to your Info.plist and add two Keys:

Only local connections are allowed Chrome and Selenium webdriver

I was able to resolve the problem by following steps: a. upgrade to the latest chrome version, clear the cache and close the chrome browser b. Download latest Selenium 3.0

Update my gradle dependencies in eclipse

You have to make sure that "Dependency Management" is enabled. To do so, right click on the project name, go to the "Gradle" sub-menu and click on "Enable Dependency Management". Once you do that, Gradle should load all the dependencies for you.

open existing java project in eclipse

If this is a simple Java project, You essentially create a new project and give the location of the existing code. The project wizard will tell you that it will use existing sources.

Also, Eclipse 3.3.2 is ancient history, you guys should really upgrade. This is like using Visual Studio 5.

How can I specify a display?

When you are connecting to another machine over SSH, you can enable X-Forwarding in SSH, so that X windows are forwarded encrypted through the SSH tunnel back to your machine. You can enable X forwarding by appending -X to the ssh command line or setting ForwardX11 yes in your SSH config file.

To check if the X-Forwarding was set up successfully (the server might not allow it), just try if echo $DISPLAY outputs something like localhost:10.0.

Java error: Only a type can be imported. XYZ resolves to a package

I resolved it by adding the jar file containing the imported classes into WEB-INF/Lib.

Can I prevent text in a div block from overflowing?

You can try:

<div id="myDiv">
    stuff 
</div>

#myDiv {
    overflow:hidden;
}

Check out the docs for the overflow property for more information.

Reverse colormap in matplotlib

The solution is pretty straightforward. Suppose you want to use the "autumn" colormap scheme. The standard version:

cmap = matplotlib.cm.autumn

To reverse the colormap color spectrum, use get_cmap() function and append '_r' to the colormap title like this:

cmap_reversed = matplotlib.cm.get_cmap('autumn_r')

Append TimeStamp to a File Name

For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Write file containing the date with BIN extension
        //
        string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
            DateTime.Now);
        File.WriteAllText(n, "abc");
    }
}

Output :

C:\Users\Fez\Documents\text-2020-01-08_05-23-13-PM.bin

"text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"

text- The first part of the output required Files will all start with text-

{0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here

yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem

MM- Prints the month in two digits

dd_ Prints the day in two digits followed by an underscore

hh- Prints the hour in two digits

mm- Prints the minute, also in two digits

ss- As expected, it prints the seconds

tt Prints AM or PM depending on the time of day

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

I was debugging the problem for the better part of the day and when I was close to burning the building I discovered the Process Monitor tool from Sysinternals.

Set it to monitor w3wp.exe and check last events before it exits after you fire a request in the browser. Hope that helps further readers.

How to get the background color of an HTML element?

It depends which style from the div you need. Is this a background style which was defined in CSS or background style which was added through javascript(inline) to the current node?

In case of CSS style, you should use computed style. Like you do in getStyle().

With inline style you should use node.style reference: x.style.backgroundColor;

Also notice, that you pick the style by using camelCase/non hyphen reference, so not background-color, but backgroundColor;

Adding Google Play services version to your app's manifest?

I got the solution.

  • Step 1: Right click on your project at Package explorer(left side in eclipse)
  • Step 2: goto Android.
  • Step 3: In Library section Add Library...(google-play-services_lib)
    see below buttes

    • Copy the library project at

    <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/

    • to the location where you maintain your Android app projects. If you are using Eclipse, import the library project into your workspace. Click File > Import, select Android > Existing Android Code into Workspace, and browse to the copy of the library project to import it.
    • Click Here For more.
  • Step 4: Click Apply
  • Step 5: Click ok
  • Step 6: Refresh you app from package Explorer.
  • Step 7: you will see error is gone.

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

POST request with a simple string in body with Alamofire

You can do this:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = HTTPMethod.post.rawValue
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let pjson = attendences.toJSONString(prettyPrint: false)
    let data = (pjson?.data(using: .utf8))! as Data
    
    request.httpBody = data
    
    Alamofire.request(request).responseJSON { (response) in
    
    
        print(response)
    
    }
    

How to compare values which may both be null in T-SQL

You create a primary key on your fields and let the engine enforce the uniqueness. Doing IF EXISTS logic is incorrect anyway as is flawed with race conditions.

How to set Google Chrome in WebDriver

It was giving Illegal Exception.

My workaround with code:

public void dofirst(){
    System.setProperty("webdriver.chrome.driver","D:\\Softwares\\selenium\\chromedriver_win32\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.facebook.com");
}

How can I de-install a Perl module installed via `cpan`?

  1. Install App::cpanminus from CPAN (use: cpan App::cpanminus for this).
  2. Type cpanm --uninstall Module::Name (note the "m") to uninstall the module with cpanminus.

This should work.

Installing Google Protocol Buffers on mac

For v3 users.

http://google.github.io/proto-lens/installing-protoc.html

PROTOC_ZIP=protoc-3.7.1-osx-x86_64.zip
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/$PROTOC_ZIP
sudo unzip -o $PROTOC_ZIP -d /usr/local bin/protoc
sudo unzip -o $PROTOC_ZIP -d /usr/local 'include/*'
rm -f $PROTOC_ZIP

How to add Android Support Repository to Android Studio?

I used to get similar issues. Even after installing the support repository, the build used to fail.

Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.

For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"

On removing "+" the build was sucessful!!

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

https://reactjs.org/docs/react-component.html#componentdidmount

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

Adding n hours to a date in Java?

To simplify @Christopher's example.

Say you have a constant

public static final long HOUR = 3600*1000; // in milli-seconds.

You can write.

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

If you use long to store date/time instead of the Date object you can do

long newDate = oldDate + 2 * HOUR;

How exactly does <script defer="defer"> work?

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

How to add an extra column to a NumPy array

np.insert also serves the purpose.

matA = np.array([[1,2,3], 
                 [2,3,4]])
idx = 3
new_col = np.array([0, 0])
np.insert(matA, idx, new_col, axis=1)

array([[1, 2, 3, 0],
       [2, 3, 4, 0]])

It inserts values, here new_col, before a given index, here idx along one axis. In other words, the newly inserted values will occupy the idx column and move what were originally there at and after idx backward.

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

Nullable DateTime conversion

Make sure those two types are nullable DateTime

var lastPostDate = reader[3] == DBNull.Value ?
                                        null : 
                                   (DateTime?) Convert.ToDateTime(reader[3]);
  • Usage of DateTime? instead of Nullable<DateTime> is a time saver...
  • Use better indent of the ? expression like I did.

I have found this excellent explanations in Eric Lippert blog:

The specification for the ?: operator states the following:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

  • If X and Y are the same type, then this is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

  • Otherwise, if an implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, no expression type can be determined, and a compile-time error occurs.

The compiler doesn't check what is the type that can "hold" those two types.

In this case:

  • null and DateTime aren't the same type.
  • null doesn't have an implicit conversion to DateTime
  • DateTime doesn't have an implicit conversion to null

So we end up with a compile-time error.

Converting a date string to a DateTime object using Joda Time library

DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");

NSURLSession/NSURLConnection HTTP load failed on iOS 9

If you're having this problem with Amazon S3 as me, try to paste this on your info.plist as a direct child of your top level tag

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>amazonaws.com</key>
        <dict>
              <key>NSThirdPartyExceptionMinimumTLSVersion</key>
              <string>TLSv1.0</string>
              <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
              <false/>
              <key>NSIncludesSubdomains</key>
              <true/>
        </dict>
        <key>amazonaws.com.cn</key>
        <dict>
              <key>NSThirdPartyExceptionMinimumTLSVersion</key>
              <string>TLSv1.0</string>
              <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
              <false/>
              <key>NSIncludesSubdomains</key>
              <true/>
        </dict>
    </dict>
</dict>

You can find more info at:

http://docs.aws.amazon.com/mobile/sdkforios/developerguide/ats.html#resolving-the-issue

Signed versus Unsigned Integers

Unsigned can hold a larger positive value and no negative value.

Yes.

Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative.

There are different ways of representing signed integers. The easiest to visualise is to use the leftmost bit as a flag (sign and magnitude), but more common is two's complement. Both are in use in most modern microprocessors — floating point uses sign and magnitude, while integer arithmetic uses two's complement.

Signed integers can hold both positive and negative numbers.

Yes.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to declare a global variable in React?

The best way I have found so far is to use React Context but to isolate it inside a high order provider component.

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

My simple solution is to style hr with css to have zero top & bottom margins, zero border, 1 pixel height and contrasting background color. This can be done by setting the style directly or by defining a class, for example, like:

.thin_hr {
margin-top:0;
margin-bottom:0;
border:0;
height:1px;
background-color:black;
}

Is there a JSON equivalent of XQuery/XPath?

Yup, it's called JSONPath:

It's also integrated into DOJO.

What is the use of a private static variable in Java?

private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.

public class PrivateStatic {

private static int var = 10;
public void setVar(int newVal) {
    var = newVal;
}

public int getVar() {
    return var;
}

public static void main(String... args) {
    PrivateStatic p1 = new Sub1();
    System.out.println(PrivateStatic.var);
    p1.setVar(200);

    PrivateStatic p2 = new Sub2();
    System.out.println(p2.getVar());
}
}


class Sub1 extends PrivateStatic {

}

class Sub2 extends PrivateStatic {
}

Checking if a string can be converted to float in Python

If you cared about performance (and I'm not suggesting you should), the try-based approach is the clear winner (compared with your partition-based approach or the regexp approach), as long as you don't expect a lot of invalid strings, in which case it's potentially slower (presumably due to the cost of exception handling).

Again, I'm not suggesting you care about performance, just giving you the data in case you're doing this 10 billion times a second, or something. Also, the partition-based code doesn't handle at least one valid string.

$ ./floatstr.py
F..
partition sad: 3.1102449894
partition happy: 2.09208488464
..
re sad: 7.76906108856
re happy: 7.09421992302
..
try sad: 12.1525540352
try happy: 1.44165301323
.
======================================================================
FAIL: test_partition (__main__.ConvertTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./floatstr.py", line 48, in test_partition
    self.failUnless(is_float_partition("20e2"))
AssertionError

----------------------------------------------------------------------
Ran 8 tests in 33.670s

FAILED (failures=1)

Here's the code (Python 2.6, regexp taken from John Gietzen's answer):

def is_float_try(str):
    try:
        float(str)
        return True
    except ValueError:
        return False

import re
_float_regexp = re.compile(r"^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$")
def is_float_re(str):
    return re.match(_float_regexp, str)


def is_float_partition(element):
    partition=element.partition('.')
    if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and pa\
rtition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):
        return True

if __name__ == '__main__':
    import unittest
    import timeit

    class ConvertTests(unittest.TestCase):
        def test_re(self):
            self.failUnless(is_float_re("20e2"))

        def test_try(self):
            self.failUnless(is_float_try("20e2"))

        def test_re_perf(self):
            print
            print 're sad:', timeit.Timer('floatstr.is_float_re("12.2x")', "import floatstr").timeit()
            print 're happy:', timeit.Timer('floatstr.is_float_re("12.2")', "import floatstr").timeit()

        def test_try_perf(self):
            print
            print 'try sad:', timeit.Timer('floatstr.is_float_try("12.2x")', "import floatstr").timeit()
            print 'try happy:', timeit.Timer('floatstr.is_float_try("12.2")', "import floatstr").timeit()

        def test_partition_perf(self):
            print
            print 'partition sad:', timeit.Timer('floatstr.is_float_partition("12.2x")', "import floatstr").timeit()
            print 'partition happy:', timeit.Timer('floatstr.is_float_partition("12.2")', "import floatstr").timeit()

        def test_partition(self):
            self.failUnless(is_float_partition("20e2"))

        def test_partition2(self):
            self.failUnless(is_float_partition(".2"))

        def test_partition3(self):
            self.failIf(is_float_partition("1234x.2"))

    unittest.main()

JSON formatter in C#?

This will put each item on a new line

VB.NET

mytext = responseFromServer.Replace("{", vbNewLine + "{")

C#

mytext = responseFromServer.Replace("{", Environment.NewLine + "{");

Convert line endings

Some options:

Using tr

tr -d '\15\32' < windows.txt > unix.txt

OR

tr -d '\r' < windows.txt > unix.txt 

Using perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

sed 's/^M$//' windows.txt > unix.txt

OR

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-V and then CTRL-M.

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

adding multiple event listeners to one element

_x000D_
_x000D_
document.getElementById('first').addEventListener('touchstart',myFunction);_x000D_
_x000D_
document.getElementById('first').addEventListener('click',myFunction);_x000D_
    _x000D_
function myFunction(e){_x000D_
  e.preventDefault();e.stopPropagation()_x000D_
  do_something();_x000D_
}    
_x000D_
_x000D_
_x000D_

You should be using e.stopPropagation() because if not, your function will fired twice on mobile

Google Maps shows "For development purposes only"

try this code it doesn't show “For development purposes only”

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

CMake link to external library

Set libraries search path first:

LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)

And then just do

TARGET_LINK_LIBRARIES(GLBall mylib)

DateTime.MinValue and SqlDateTime overflow

From MSDN:

Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds. Stored as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system's reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. Seconds have a valid range of 0–59.

SQL uses a different system than C# for DateTime values.

You can use your MinValue as a sentinel value - and if it is MinValue - pass null into your object (and store the date as nullable in the DB).

if(date == dateTime.Minvalue)
    objinfo.BirthDate = null;

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

Unless there is a reason that you want to keep that private/public key pair (id_rsa/id_rsa.pub), or enjoy banging your head on the wall, I'd recommend just recreating them and updating your public key on github.

Start by making a backup copy of your ~/.ssh directory.

Enter the following and respond "y" to whether you want to over write the existing files.

ssh-keygen -t rsa

Copy the contents of the public key to your clipboard. (Below is how you should do it on a Mac).

cat ~/.ssh/id_rsa.pub | pbcopy

Go to your account on github and add this key.

Name: My new public key
Key: <PASTE>

Exit from your terminal and restart a new one.

If you get senseless error messages like "Enter your password" for your public key when you never entered one, consider this start over technique. As you see above, it's not complicated.

Returning value from Thread

With small modifications to your code, you can achieve it in a more generic way.

 final Handler responseHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Result from UIHandlerThread:"+(int)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };

        HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
            public void run(){
                Integer a = 2;
                Message msg = new Message();
                msg.obj = a;
                responseHandler.sendMessage(msg);
                System.out.println(a);
            }
        };
        handlerThread.start();

Solution :

  1. Create a Handler in UI Thread,which is called as responseHandler
  2. Initialize this Handler from Looper of UI Thread.
  3. In HandlerThread, post message on this responseHandler
  4. handleMessgae shows a Toast with value received from message. This Message object is generic and you can send different type of attributes.

With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable objects on this HandlerThread and each Runnable can set value in Message object, which can be received by UI Thread.

CSS media queries for screen sizes

For all smartphones and large screens use this format of media query

/* Smartphones (portrait and landscape) ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */

@media only screen and (min-width : 321px) {
/* Styles */
}



/* Smartphones (portrait) ----------- */

@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}

/**********
iPad 3
**********/

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* Desktops and laptops ----------- */

@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

/* iPhone 5 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6 ----------- */

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* iPhone 6+ ----------- */

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S3 ----------- */

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 2){
/* Styles */
}

/* Samsung Galaxy S4 ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

/* Samsung Galaxy S5 ----------- */

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : landscape) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation : portrait) and (-webkit-device-pixel-ratio: 3){
/* Styles */
}

Is there an alternative sleep function in C to milliseconds?

You can use this cross-platform function:

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#else
#include <unistd.h> // for usleep
#endif

void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
    Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
#else
    if (milliseconds >= 1000)
      sleep(milliseconds / 1000);
    usleep((milliseconds % 1000) * 1000);
#endif
}

Batch file to map a drive when the folder name contains spaces

whenever you deal with spaces in filenames, use quotes

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

PPT to PNG with transparent background

I just tried to make a transparent image with powerpoint after failing miserably with other online systems. I was successful. Amazing.

First I used word art to give me typefaces which convert well to PNG or JPEG. The ordinary text in powerpoint does not convert well. It gets fuzzy. Anyway, I typed in my words in white (my choice of colour as i wanted it against a navy blue background), arranged it how i wanted, then right clicked and selected format shape to remove lines, then shadow to set the transparency.

I took the transparency to 100%. It came out fine. i then right clicked to save as png. Opened the image with MS Picture manager and resized the image to my suiting. It did not come out with the powerpoint white background at all. Once resized, i dropped the image against my navy blue background and it was like magic.

Find out a Git branch creator

A branch is nothing but a commit pointer. As such, it doesn't track metadata like "who created me." See for yourself. Try cat .git/refs/heads/<branch> in your repository.

That written, if you're really into tracking this information in your repository, check out branch descriptions. They allow you to attach arbitrary metadata to branches, locally at least.

Also DarVar's answer below is a very clever way to get at this information.

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

Getting distance between two points based on latitude/longitude

I arrived at a much simpler and robust solution which is using geodesic from geopy package since you'll be highly likely using it in your project anyways so no extra package installation needed.

Here is my solution:

from geopy.distance import geodesic


origin = (30.172705, 31.526725)  # (latitude, longitude) don't confuse
dist = (30.288281, 31.732326)

print(geodesic(origin, dist).meters)  # 23576.805481751613
print(geodesic(origin, dist).kilometers)  # 23.576805481751613
print(geodesic(origin, dist).miles)  # 14.64994773134371

geopy

Uncaught SyntaxError: Unexpected token :

When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).

According to MooTools docs:

Responses with javascript content-type will be evaluated automatically.

In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:

{"votes":47,"totalvotes":90}

as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following "code":

"votes":47,"totalvotes":90

As you can see, : is totally unexpected there.

The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.

Print the address or pointer for value in C

Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:

char **a;
char *b;
char c = 'H';

b = &c;
a = &b;

You would be able to access the address of the double pointer a by doing:

printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);

ArrayBuffer to base64 encoded string

You can derive a normal array from the ArrayBuffer by using Array.prototype.slice. Use a function like Array.prototype.map to convert bytes in to characters and join them together to forma string.

function arrayBufferToBase64(ab){

    var dView = new Uint8Array(ab);   //Get a byte view        

    var arr = Array.prototype.slice.call(dView); //Create a normal array        

    var arr1 = arr.map(function(item){        
      return String.fromCharCode(item);    //Convert
    });

    return window.btoa(arr1.join(''));   //Form a string

}

This method is faster since there are no string concatenations running in it.

How can I see an the output of my C programs using Dev-C++?

Add this to your header file #include and then in the end add this line : getch();

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

When you declare

var a=[];

you are declaring a empty array.

But when you are declaring

var a={};

you are declaring a Object .

Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.

So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:

var a={name:"abc",age:"14"}; 

And can access values like

console.log(a.name);

Change image source with JavaScript

function changeImage(a) so there is no such thing as a.src => just use a.

demo here

Custom Date Format for Bootstrap-DatePicker

I solve it editing the file bootstrap-datapicker.js.

Look for the text bellow in the file and edit the variable "Format:"

var defaults = $.fn.datepicker.defaults = {
    assumeNearbyYear: false,
    autoclose: false,
    beforeShowDay: $.noop,
    beforeShowMonth: $.noop,
    beforeShowYear: $.noop,
    beforeShowDecade: $.noop,
    beforeShowCentury: $.noop,
    calendarWeeks: false,
    clearBtn: false,
    toggleActive: false,
    daysOfWeekDisabled: [],
    daysOfWeekHighlighted: [],
    datesDisabled: [],
    endDate: Infinity,
    forceParse: true,
    format: 'dd/mm/yyyy',
    keyboardNavigation: true,
    language: 'en',
    minViewMode: 0,
    maxViewMode: 4,
    multidate: false,
    multidateSeparator: ',',
    orientation: "auto",
    rtl: false,
    startDate: -Infinity,
    startView: 0,
    todayBtn: false,
    todayHighlight: false,
    weekStart: 0,
    disableTouchKeyboard: false,
    enableOnReadonly: true,
    showOnFocus: true,
    zIndexOffset: 10,
    container: 'body',
    immediateUpdates: false,
    title: '',
    templates: {
        leftArrow: '&laquo;',
        rightArrow: '&raquo;'
    }
};

form_for but to post to a different action

Alternatively the same can be reached using form_tag with the syntax:

form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'

As described in http://guides.rubyonrails.org/form_helpers.html#multiple-hashes-in-form-helper-calls

Directory.GetFiles of certain extension

If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> { "jpg", "gif", "png" };
var myFiles = Directory
    .EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
    .Where(s => ext.Contains(Path.GetExtension(s).TrimStart(".").ToLowerInvariant()));

Now ext contains a list of allowed extensions; you can add or remove items from it as necessary for flexible filtering.

Detecting superfluous #includes in C/C++?

The problem with detecting superfluous includes is that it can't be just a type dependency checker. A superfluous include is a file which provides nothing of value to the compilation and does not alter another item which other files depend. There are many ways a header file can alter a compile, say by defining a constant, redefining and/or deleting a used macro, adding a namespace which alters the lookup of a name some way down the line. In order to detect items like the namespace you need much more than a preprocessor, you in fact almost need a full compiler.

Lint is more of a style checker and certainly won't have this full capability.

I think you'll find the only way to detect a superfluous include is to remove, compile and run suites.

How to update the value stored in Dictionary in C#?

Use LINQ: Access to dictionary for the key and change the value

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

How to create a Multidimensional ArrayList in Java?

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

Depending on your requirements, you might use a Generic class like the one below to make access easier:

import java.util.ArrayList;

class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
    public void addToInnerArray(int index, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }
        this.get(index).add(element);
    }

    public void addToInnerArray(int index, int index2, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }

        ArrayList<T> inner = this.get(index);
        while (index2 >= inner.size()) {
            inner.add(null);
        }

        inner.set(index2, element);
    }
}

How can I see function arguments in IPython Notebook Server 3?

Adding screen shots(examples) and some more context for the answer of @Thomas G.

if its not working please make sure if you have executed code properly. In this case make sure import pandas as pd is ran properly before checking below shortcut.

Place the cursor in middle of parenthesis () before you use shortcut.

shift + tab

Display short document and few params

enter image description here

shift + tab + tab

Expands document with scroll bar

enter image description here

shift + tab + tab + tab

Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.

enter image description here

shift + tab + tab + tab + tab

It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.

enter image description here

pandas three-way joining multiple dataframes on columns

One does not need a multiindex to perform join operations. One just need to set correctly the index column on which to perform the join operations (which command df.set_index('Name') for example)

The join operation is by default performed on index. In your case, you just have to specify that the Name column corresponds to your index. Below is an example

A tutorial may be useful.

# Simple example where dataframes index are the name on which to perform
# the join operations
import pandas as pd
import numpy as np
name = ['Sophia' ,'Emma' ,'Isabella' ,'Olivia' ,'Ava' ,'Emily' ,'Abigail' ,'Mia']
df1 = pd.DataFrame(np.random.randn(8, 3), columns=['A','B','C'], index=name)
df2 = pd.DataFrame(np.random.randn(8, 1), columns=['D'],         index=name)
df3 = pd.DataFrame(np.random.randn(8, 2), columns=['E','F'],     index=name)
df = df1.join(df2)
df = df.join(df3)

# If you have a 'Name' column that is not the index of your dataframe,
# one can set this column to be the index
# 1) Create a column 'Name' based on the previous index
df1['Name'] = df1.index
# 1) Select the index from column 'Name'
df1 = df1.set_index('Name')

# If indexes are different, one may have to play with parameter how
gf1 = pd.DataFrame(np.random.randn(8, 3), columns=['A','B','C'], index=range(8))
gf2 = pd.DataFrame(np.random.randn(8, 1), columns=['D'], index=range(2,10))
gf3 = pd.DataFrame(np.random.randn(8, 2), columns=['E','F'], index=range(4,12))

gf = gf1.join(gf2, how='outer')
gf = gf.join(gf3, how='outer')

What is the difference between buffer and cache memory in Linux?

buffer and cache.

A buffer is something that has yet to be "written" to disk.

A cache is something that has been "read" from the disk and stored for later use.

Casting an int to a string in Python

x = 1
y = "foo" + str(x)

Please see the Python documentation: https://docs.python.org/2/library/functions.html#str

How do you create a UIImage View Programmatically - Swift

Swift 4:

First create an outlet for your UIImageView

@IBOutlet var infoImage: UIImageView!

Then use the image property in UIImageView

infoImage.image = UIImage(named: "icons8-info-white")

How can I remove Nan from list Python/NumPy

if you check for the element type

type(countries[1])

the result will be <class float> so you can use the following code:

[i for i in countries if type(i) is not float]

remove inner shadow of text input

here is a small snippet that might be cool to try out:

input {
border-radius: 10px;
border-color: violet;
border-style: solid;
}

note that: border-style removes the inner shadow.

_x000D_
_x000D_
input {_x000D_
    border-radius: 10px;_x000D_
    border-color: violet;_x000D_
    border-style: solid;_x000D_
  }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Convert Float to Int in Swift

There are lots of ways to round number with precision. You should eventually use swift's standard library method rounded() to round float number with desired precision.

To round up use .up rule:

let f: Float = 2.2
let i = Int(f.rounded(.up)) // 3

To round down use .down rule:

let f: Float = 2.2
let i = Int(f.rounded(.down)) // 2

To round to the nearest integer use .toNearestOrEven rule:

let f: Float = 2.2
let i = Int(f.rounded(.toNearestOrEven)) // 2

Be aware of the following example:

let f: Float = 2.5
let i = Int(roundf(f)) // 3
let j = Int(f.rounded(.toNearestOrEven)) // 2

Rounded corner for textview in android

  1. Right Click on Drawable Folder and Create new File
  2. Name the file according to you and add the extension as .xml.
  3. Add the following code in the file
  <?xml version="1.0" encoding="utf-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:shape="rectangle">
      <corners android:radius="5dp" />
      <stroke android:width="1dp"  />
      <solid android:color="#1e90ff" />
  </shape>
  1. Add the line where you want the rounded edge android:background="@drawable/corner"

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

PHP __get and __set magic methods

It's because $bar is a public property.

$foo->bar = 'test';

There is no need to call the magic method when running the above.

Deleting public $bar; from your class should correct this.

'Incorrect SET Options' Error When Building Database Project

For me, just setting the compatibility level to higher level works fine. To see C.Level :

select compatibility_level from sys.databases where name = [your_database]

How to get selected value of a html select with asp.net

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">    
<head>
    <title> HtmlSelect Example </title>
    <script runat="server">
      void Button_Click (Object sender, EventArgs e)
      {
         Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
                       + ", value: " + Select1.Value;    
      }    
   </script>    
</head>    
<body>    
   <form id="form1" runat="server">

      Select an item: 

      <select id="Select1" runat="server">    
         <option value="Text for Item 1" selected="selected"> Item 1 </option>
         <option value="Text for Item 2"> Item 2 </option>
         <option value="Text for Item 3"> Item 3 </option>
         <option value="Text for Item 4"> Item 4 </option>
      </select>

      <button onserverclick="Button_Click" runat="server" Text="Submit"/>

      <asp:Label id="Label1" runat="server"/>    
   </form>
</body>
</html>

Source from Microsoft. Hope this is helpful!

Java ArrayList how to add elements at the beginning

List has the method add(int, E), so you can use:

list.add(0, yourObject);

Afterwards you can delete the last element with:

if(list.size() > 10)
    list.remove(list.size() - 1);

However, you might want to rethink your requirements or use a different data structure, like a Queue

EDIT

Maybe have a look at Apache's CircularFifoQueue:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

Just initialize it with you maximum size:

CircularFifoQueue queue = new CircularFifoQueue(10);

Mergesort with Python

Code from MIT course. (with generic cooperator )

import operator


def merge(left, right, compare):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if compare(left[i], right[j]):
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    while i < len(left):
        result.append(left[i])
        i += 1
    while j < len(right):
        result.append(right[j])
        j += 1
    return result


def mergeSort(L, compare=operator.lt):
    if len(L) < 2:
        return L[:]
    else:
        middle = int(len(L) / 2)
        left = mergeSort(L[:middle], compare)
        right = mergeSort(L[middle:], compare)
        return merge(left, right, compare)

How to run Spring Boot web application in Eclipse itself?

Just run the main method which is in the class SampleWebJspApplication. Spring Boot will take care of all the rest (starting the embedded tomcat which will host your sample application).

Sorting table rows according to table header column using javascript or jquery

I think this might help you:
Here is the JSFiddle demo:

And here is the code:

_x000D_
_x000D_
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
  init: function() {_x000D_
    if (arguments.callee.done) return;_x000D_
    arguments.callee.done = true;_x000D_
    if (_timer) clearInterval(_timer);_x000D_
    if (!document.createElement || !document.getElementsByTagName) return;_x000D_
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
    forEach(document.getElementsByTagName('table'), function(table) {_x000D_
      if (table.className.search(/\bsortable\b/) != -1) {_x000D_
        sorttable.makeSortable(table);_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
  makeSortable: function(table) {_x000D_
    if (table.getElementsByTagName('thead').length == 0) {_x000D_
      the = document.createElement('thead');_x000D_
      the.appendChild(table.rows[0]);_x000D_
      table.insertBefore(the, table.firstChild);_x000D_
    }_x000D_
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
    if (table.tHead.rows.length != 1) return;_x000D_
    sortbottomrows = [];_x000D_
    for (var i = 0; i < table.rows.length; i++) {_x000D_
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
        sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
      }_x000D_
    }_x000D_
    if (sortbottomrows) {_x000D_
      if (table.tFoot == null) {_x000D_
        tfo = document.createElement('tfoot');_x000D_
        table.appendChild(tfo);_x000D_
      }_x000D_
      for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
        tfo.appendChild(sortbottomrows[i]);_x000D_
      }_x000D_
      delete sortbottomrows;_x000D_
    }_x000D_
    headrow = table.tHead.rows[0].cells;_x000D_
    for (var i = 0; i < headrow.length; i++) {_x000D_
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
        if (mtch) {_x000D_
          override = mtch[1];_x000D_
        }_x000D_
        if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
          headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
        } else {_x000D_
          headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
        }_x000D_
        headrow[i].sorttable_columnindex = i;_x000D_
        headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
        dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
          if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted',_x000D_
              'sorttable_sorted_reverse');_x000D_
            this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
            sortrevind = document.createElement('span');_x000D_
            sortrevind.id = "sorttable_sortrevind";_x000D_
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';_x000D_
            this.appendChild(sortrevind);_x000D_
            return;_x000D_
          }_x000D_
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
              'sorttable_sorted');_x000D_
            this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
            sortfwdind = document.createElement('span');_x000D_
            sortfwdind.id = "sorttable_sortfwdind";_x000D_
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
            this.appendChild(sortfwdind);_x000D_
            return;_x000D_
          }_x000D_
          theadrow = this.parentNode;_x000D_
          forEach(theadrow.childNodes, function(cell) {_x000D_
            if (cell.nodeType == 1) {_x000D_
              cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
              cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
            }_x000D_
          });_x000D_
          sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
          if (sortfwdind) {_x000D_
            sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
          }_x000D_
          sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
          if (sortrevind) {_x000D_
            sortrevind.parentNode.removeChild(sortrevind);_x000D_
          }_x000D_
_x000D_
          this.className += ' sorttable_sorted';_x000D_
          sortfwdind = document.createElement('span');_x000D_
          sortfwdind.id = "sorttable_sortfwdind";_x000D_
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
          this.appendChild(sortfwdind);_x000D_
          row_array = [];_x000D_
          col = this.sorttable_columnindex;_x000D_
          rows = this.sorttable_tbody.rows;_x000D_
          for (var j = 0; j < rows.length; j++) {_x000D_
            row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
          }_x000D_
          row_array.sort(this.sorttable_sortfunction);_x000D_
          tb = this.sorttable_tbody;_x000D_
          for (var j = 0; j < row_array.length; j++) {_x000D_
            tb.appendChild(row_array[j][1]);_x000D_
          }_x000D_
          delete row_array;_x000D_
        });_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
_x000D_
  guessType: function(table, column) {_x000D_
    sortfn = sorttable.sort_alpha;_x000D_
    for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
      if (text != '') {_x000D_
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
          return sorttable.sort_numeric;_x000D_
        }_x000D_
        possdate = text.match(sorttable.DATE_RE)_x000D_
        if (possdate) {_x000D_
          first = parseInt(possdate[1]);_x000D_
          second = parseInt(possdate[2]);_x000D_
          if (first > 12) {_x000D_
            return sorttable.sort_ddmm;_x000D_
          } else if (second > 12) {_x000D_
            return sorttable.sort_mmdd;_x000D_
          } else {_x000D_
            sortfn = sorttable.sort_ddmm;_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return sortfn;_x000D_
  },_x000D_
  getInnerText: function(node) {_x000D_
    if (!node) return "";_x000D_
    hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
      node.getElementsByTagName('input').length;_x000D_
    if (node.getAttribute("sorttable_customkey") != null) {_x000D_
      return node.getAttribute("sorttable_customkey");_x000D_
    } else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
      return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
      return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
      return node.text.replace(/^\s+|\s+$/g, '');_x000D_
    } else {_x000D_
      switch (node.nodeType) {_x000D_
        case 3:_x000D_
          if (node.nodeName.toLowerCase() == 'input') {_x000D_
            return node.value.replace(/^\s+|\s+$/g, '');_x000D_
          }_x000D_
        case 4:_x000D_
          return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        case 1:_x000D_
        case 11:_x000D_
          var innerText = '';_x000D_
          for (var i = 0; i < node.childNodes.length; i++) {_x000D_
            innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
          }_x000D_
          return innerText.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        default:_x000D_
          return '';_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
  reverse: function(tbody) {_x000D_
    // reverse the rows in a tbody_x000D_
    newrows = [];_x000D_
    for (var i = 0; i < tbody.rows.length; i++) {_x000D_
      newrows[newrows.length] = tbody.rows[i];_x000D_
    }_x000D_
    for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
      tbody.appendChild(newrows[i]);_x000D_
    }_x000D_
    delete newrows;_x000D_
  },_x000D_
  sort_numeric: function(a, b) {_x000D_
    aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(aa)) aa = 0;_x000D_
    bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(bb)) bb = 0;_x000D_
    return aa - bb;_x000D_
  },_x000D_
  sort_alpha: function(a, b) {_x000D_
    if (a[0] == b[0]) return 0;_x000D_
    if (a[0] < b[0]) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_ddmm: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_mmdd: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  shaker_sort: function(list, comp_func) {_x000D_
    var b = 0;_x000D_
    var t = list.length - 1;_x000D_
    var swap = true;_x000D_
    while (swap) {_x000D_
      swap = false;_x000D_
      for (var i = b; i < t; ++i) {_x000D_
        if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i + 1];_x000D_
          list[i + 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      t--;_x000D_
_x000D_
      if (!swap) break;_x000D_
_x000D_
      for (var i = t; i > b; --i) {_x000D_
        if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i - 1];_x000D_
          list[i - 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      b++;_x000D_
_x000D_
    }_x000D_
  }_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
    var script = document.getElementById("__ie_onload");_x000D_
    script.onreadystatechange = function() {_x000D_
        if (this.readyState == "complete") {_x000D_
            sorttable.init(); // call the onload handler_x000D_
        }_x000D_
    };_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
  var _timer = setInterval(function() {_x000D_
    if (/loaded|complete/.test(document.readyState)) {_x000D_
      sorttable.init(); // call the onload handler_x000D_
    }_x000D_
  }, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
  if (element.addEventListener) {_x000D_
    element.addEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
    if (!element.events) element.events = {};_x000D_
    var handlers = element.events[type];_x000D_
    if (!handlers) {_x000D_
      handlers = element.events[type] = {};_x000D_
      if (element["on" + type]) {_x000D_
        handlers[0] = element["on" + type];_x000D_
      }_x000D_
    }_x000D_
    handlers[handler.$$guid] = handler;_x000D_
    element["on" + type] = handleEvent;_x000D_
  }_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
  if (element.removeEventListener) {_x000D_
    element.removeEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (element.events && element.events[type]) {_x000D_
      delete element.events[type][handler.$$guid];_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
  var returnValue = true;_x000D_
  event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
  var handlers = this.events[event.type];_x000D_
  for (var i in handlers) {_x000D_
    this.$$handleEvent = handlers[i];_x000D_
    if (this.$$handleEvent(event) === false) {_x000D_
      returnValue = false;_x000D_
    }_x000D_
  }_x000D_
  return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
  event.preventDefault = fixEvent.preventDefault;_x000D_
  event.stopPropagation = fixEvent.stopPropagation;_x000D_
  return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
  this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
  this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
  Array.forEach = function(array, block, context) {_x000D_
    for (var i = 0; i < array.length; i++) {_x000D_
      block.call(context, array[i], i, array);_x000D_
    }_x000D_
  };_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
  for (var key in object) {_x000D_
    if (typeof this.prototype[key] == "undefined") {_x000D_
      block.call(context, object[key], key, object);_x000D_
    }_x000D_
  }_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
  Array.forEach(string.split(""), function(chr, index) {_x000D_
    block.call(context, chr, index, string);_x000D_
  });_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
  if (object) {_x000D_
    var resolve = Object;_x000D_
    if (object instanceof Function) {_x000D_
      resolve = Function;_x000D_
    } else if (object.forEach instanceof Function) {_x000D_
      object.forEach(block, context);_x000D_
      return;_x000D_
    } else if (typeof object == "string") {_x000D_
      resolve = String;_x000D_
    } else if (typeof object.length == "number") {_x000D_
      resolve = Array;_x000D_
    }_x000D_
    resolve.forEach(object, block, context);_x000D_
  }_x000D_
}
_x000D_
table.sortable thead {_x000D_
  background-color: #eee;_x000D_
  color: #666666;_x000D_
  font-weight: bold;_x000D_
  cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>S.L.</th>_x000D_
      <th>name</th>_x000D_
      <th>Goal</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>Ronaldo</td>_x000D_
      <td>120</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2</td>_x000D_
      <td>Messi</td>_x000D_
      <td>66</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3</td>_x000D_
      <td>Ribery</td>_x000D_
      <td>10</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>Bale</td>_x000D_
      <td>22</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS is used here without any other JQuery Plugin.

jQuery disable a link

I always use this in jQuery for disabling links

$("form a").attr("disabled", "disabled");

How to install a Mac application using Terminal

To disable inputting password:

sudo visudo

Then add a new line like below and save then:

# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer

Then you run installer without password:

sudo installer -pkg ...

PHP + curl, HTTP POST sample code?

It's can be easily reached with:

<?php

$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);

How to apply bold text style for an entire row using Apache POI?

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    XSSFFont font= wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Arial");
    font.setColor(IndexedColors.WHITE.getIndex());
    font.setBold(true);
    font.setItalic(false);

    style=row.getRowStyle();
    style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font);

If you do not create defaultFont all your workbook will be using the other one as default.

Best way to verify string is empty or null

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I am trying to avoid using VBA. But if has to be, then it has to be:)

There is quite simple UDF for you:

Function myCountIf(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
    Next ws
End Function

and call it like this: =myCountIf(I:I,A13)


P.S. if you'd like to exclude some sheets, you can add If statement:

Function myCountIf(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.name <> "Sheet1" And ws.name <> "Sheet2" Then
            myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
        End If
    Next ws
End Function

UPD:

I have four "reference" sheets that I need to exclude from being scanned/searched. They are currently the last four in the workbook

Function myCountIf(rng As Range, criteria) As Long
    Dim i As Integer

    For i = 1 To ThisWorkbook.Worksheets.Count - 4
        myCountIf = myCountIf + WorksheetFunction.CountIf(ThisWorkbook.Worksheets(i).Range(rng.Address), criteria)
    Next i
End Function

Can't build create-react-app project with custom PUBLIC_URL

Not sure why you aren't able to set it. In the source, PUBLIC_URL takes precedence over homepage

const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
  envPublicUrl || require(appPackageJson).homepage;

You can try setting breakpoints in their code to see what logic is overriding your environment variable.

How to iterate a loop with index and element in Swift

Starting with Swift 3, it is

for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}

Add x and y labels to a pandas plot

You can use do it like this:

import matplotlib.pyplot as plt 
import pandas as pd

plt.figure()
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
         title='Video streaming dropout by category')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()

Obviously you have to replace the strings 'xlabel' and 'ylabel' with what you want them to be.

How can I hash a password in Java?

In addition to bcrypt and PBKDF2 mentioned in other answers, I would recommend looking at scrypt

MD5 and SHA-1 are not recommended as they are relatively fast thus using "rent per hour" distributed computing (e.g. EC2) or a modern high end GPU one can "crack" passwords using brute force / dictionary attacks in relatively low costs and reasonable time.

If you must use them, then at least iterate the algorithm a predefined significant amount of times (1000+).

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Returning a boolean from a Bash function

Why you should care what I say in spite of there being a 250+ upvote answer

It's not that 0 = true and 1 = false. It is: zero means no failure (success) and non-zero means failure (of type N).

While the selected answer is technically "true" please do not put return 1** in your code for false. It will have several unfortunate side effects.

  1. Experienced developers will spot you as an amateur (for the reason below).
  2. Experienced developers don't do this (for all the reasons below).
  3. It is error prone.
    • Even experienced developers can mistake 0 and 1 as false and true respectively (for the reason above).
  4. It requires (or will encourage) extraneous and ridiculous comments.
  5. It's actually less helpful than implicit return statuses.

Learn some bash

The bash manual says (emphasis mine)

return [n]

Cause a shell function to stop executing and return the value n to its caller. If n is not supplied, the return value is the exit status of the last command executed in the function.

Therefore, we don't have to EVER use 0 and 1 to indicate True and False. The fact that they do so is essentially trivial knowledge useful only for debugging code, interview questions, and blowing the minds of newbies.

The bash manual also says

otherwise the function’s return status is the exit status of the last command executed

The bash manual also says

($?) Expands to the exit status of the most recently executed foreground pipeline.

Whoa, wait. Pipeline? Let's turn to the bash manual one more time.

A pipeline is a sequence of one or more commands separated by one of the control operators ‘|’ or ‘|&’.

Yes. They said 1 command is a pipeline. Therefore, all 3 of those quotes are saying the same thing.

  • $? tells you what happened last.
  • It bubbles up.

My answer

So, while @Kambus demonstrated that with such a simple function, no return is needed at all. I think was unrealistically simple compared to the needs of most people who will read this.

Why return?

If a function is going to return its last command's exit status, why use return at all? Because it causes a function to stop executing.

Stop execution under multiple conditions

01  function i_should(){
02      uname="$(uname -a)"
03
04      [[ "$uname" =~ Darwin ]] && return
05
06      if [[ "$uname" =~ Ubuntu ]]; then
07          release="$(lsb_release -a)"
08          [[ "$release" =~ LTS ]]
09          return
10      fi
11
12      false
13  }
14
15  function do_it(){
16      echo "Hello, old friend."
17  }
18
19  if i_should; then
20    do_it
21  fi

What we have here is...

Line 04 is an explicit[-ish] return true because the RHS of && only gets executed if the LHS was true

Line 09 returns either true or false matching the status of line 08

Line 13 returns false because of line 12

(Yes, this can be golfed down, but the entire example is contrived.)

Another common pattern

# Instead of doing this...
some_command
if [[ $? -eq 1 ]]; then
    echo "some_command failed"
fi

# Do this...
some_command
status=$?
if ! $(exit $status); then
    echo "some_command failed"
fi

Notice how setting a status variable demystifies the meaning of $?. (Of course you know what $? means, but someone less knowledgeable than you will have to Google it some day. Unless your code is doing high frequency trading, show some love, set the variable.) But the real take-away is that "if not exist status" or conversely "if exit status" can be read out loud and explain their meaning. However, that last one may be a bit too ambitious because seeing the word exit might make you think it is exiting the script, when in reality it is exiting the $(...) subshell.


** If you absolutely insist on using return 1 for false, I suggest you at least use return 255 instead. This will cause your future self, or any other developer who must maintain your code to question "why is that 255?" Then they will at least be paying attention and have a better chance of avoiding a mistake.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Eclipse does not start when I run the exe?

I have fixed it by deleting the .metadata/.lock file.

Can I disable a CSS :hover effect via JavaScript?

There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.

HTML

<body class="nojQuery">

CSS

/* Limit the hover styles in your CSS so that they only apply when the nojQuery 
class is present */

body.nojQuery ul#mainFilter a:hover {
    /* CSS-only hover styles go here */
}

JavaScript

// When jQuery kicks in, remove the nojQuery class from the <body> element, thus
// making the CSS hover styles disappear.

$(function(){}
    $('body').removeClass('nojQuery');
)

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A and then Ctrl+D. Doing this will detach you from the screen session which you can later resume by doing screen -r.

  • You can also do: Ctrl+A then type :. This will put you in screen command mode. Type the command detach to be detached from the running screen session.

How to kill all processes with a given partial name?

You can use the following command to:

ps -ef | grep -i myprocess | awk {'print $2'} | xargs kill -9

or

ps -aux | grep -i myprocess | awk {'print $2'} | xargs kill -9

It works for me.

Converting a list to a set changes element order

In case you have a small number of elements in your two initial lists on which you want to do set difference operation, instead of using collections.OrderedDict which complicates the implementation and makes it less readable, you can use:

# initial lists on which you want to do set difference
>>> nums = [1,2,2,3,3,4,4,5]
>>> evens = [2,4,4,6]
>>> evens_set = set(evens)
>>> result = []
>>> for n in nums:
...   if not n in evens_set and not n in result:
...     result.append(n)
... 
>>> result
[1, 3, 5]

Its time complexity is not that good but it is neat and easy to read.

Return row of Data Frame based on value in a column - R

Use which.min:

df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]

> df[which.min(df$Amount),]
  Name Amount
2    B    120

From the help docs:

Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Turn a simple socket into an SSL socket

For others like me:

There was once an example in the SSL source in the directory demos/ssl/ with example code in C++. Now it's available only via the history: https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl

You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.

Certificates: .pem in demos/certs/apps/: https://github.com/openssl/openssl/tree/master/demos/certs/apps

jQuery count number of divs with a certain class?

You can use the jquery .length property

var numItems = $('.item').length;

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

Is there a way to get a collection of all the Models in your Rails app?

In just one line:

 ActiveRecord::Base.subclasses.map(&:name)

Switch statement: must default be the last case?

The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.

Good Example :-

switch(5) {
  case 1:
    echo "1";
    break;
  case 2:
  default:
    echo "2, default";
    break;
  case 3;
    echo "3";
    break;
}


Outputs '2,default'

very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

Why is a primary-foreign key relation required when we can join without it?

You need two columns of the same type, one on each table, to JOIN on. Whether they're primary and foreign keys or not doesn't matter.

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Get the system date and split day, month and year

You can do like follow:

 String date = DateTime.Now.Date.ToString();
    String Month = DateTime.Now.Month.ToString();
    String Year = DateTime.Now.Year.ToString();

On the place of datetime you can use your column..

How to compare data between two table in different databases using Sql Server 2008?

If both database on same server. You can check similar tables by using following query :

select 
      fdb.name, sdb.name 
from 
      FIRSTDBNAME.sys.tables fdb 
      join SECONDDBNAME.sys.tables sdb
      on fdb.name = sdb.name -- compare same name tables
order by 
      1     

By listing out similar table you can compare columns schema using sys.columns view.

Hope this helps you.

How to pass a callback as a parameter into another function

Also, could be simple as:

if( typeof foo == "function" )
    foo();

What is the difference between Tomcat, JBoss and Glassfish?

Tomcat is merely an HTTP server and Java servlet container. JBoss and GlassFish are full-blown Java EE application servers, including an EJB container and all the other features of that stack. On the other hand, Tomcat has a lighter memory footprint (~60-70 MB), while those Java EE servers weigh in at hundreds of megs. Tomcat is very popular for simple web applications, or applications using frameworks such as Spring that do not require a full Java EE server. Administration of a Tomcat server is arguably easier, as there are fewer moving parts.

However, for applications that do require a full Java EE stack (or at least more pieces that could easily be bolted-on to Tomcat)... JBoss and GlassFish are two of the most popular open source offerings (the third one is Apache Geronimo, upon which the free version of IBM WebSphere is built). JBoss has a larger and deeper user community, and a more mature codebase. However, JBoss lags significantly behind GlassFish in implementing the current Java EE specs. Also, for those who prefer a GUI-based admin system... GlassFish's admin console is extremely slick, whereas most administration in JBoss is done with a command-line and text editor. GlassFish comes straight from Sun/Oracle, with all the advantages that can offer. JBoss is NOT under the control of Sun/Oracle, with all the advantages THAT can offer.

Is JavaScript's "new" keyword considered harmful?

I agree with pez and some here.

It seems obvious to me that "new" is self descriptive object creation, where the YUI pattern Greg Dean describes is completely obscured.

The possibility someone could write var bar = foo; or var bar = baz(); where baz isn't an object creating method seems far more dangerous.

Converting a string to a date in a cell

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

Change the Bootstrap Modal effect

 body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}

    <div class="container">
    <form class="form-inline" style="position:absolute; top:40%; left:50%; transform:translateX(-50%);">
        <div class="form-group">
        <label>Entrances</label>
          <select class="form-control" id="entrance">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Entrances">
              <option value="bounceIn" selected>bounceIn</option>
              <option value="bounceInDown">bounceInDown</option>
              <option value="bounceInLeft">bounceInLeft</option>
              <option value="bounceInRight">bounceInRight</option>
              <option value="bounceInUp">bounceInUp</option>
            </optgroup>
            <optgroup label="Fading Entrances">
              <option value="fadeIn">fadeIn</option>
              <option value="fadeInDown">fadeInDown</option>
              <option value="fadeInDownBig">fadeInDownBig</option>
              <option value="fadeInLeft">fadeInLeft</option>
              <option value="fadeInLeftBig">fadeInLeftBig</option>
              <option value="fadeInRight">fadeInRight</option>
              <option value="fadeInRightBig">fadeInRightBig</option>
              <option value="fadeInUp">fadeInUp</option>
              <option value="fadeInUpBig">fadeInUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipInX">flipInX</option>
              <option value="flipInY">flipInY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedIn">lightSpeedIn</option>
            </optgroup>
            <optgroup label="Rotating Entrances">
              <option value="rotateIn">rotateIn</option>
              <option value="rotateInDownLeft">rotateInDownLeft</option>
              <option value="rotateInDownRight">rotateInDownRight</option>
              <option value="rotateInUpLeft">rotateInUpLeft</option>
              <option value="rotateInUpRight">rotateInUpRight</option>
            </optgroup>
            <optgroup label="Sliding Entrances">
              <option value="slideInUp">slideInUp</option>
              <option value="slideInDown">slideInDown</option>
              <option value="slideInLeft">slideInLeft</option>
              <option value="slideInRight">slideInRight</option>
            </optgroup>
            <optgroup label="Zoom Entrances">
              <option value="zoomIn">zoomIn</option>
              <option value="zoomInDown">zoomInDown</option>
              <option value="zoomInLeft">zoomInLeft</option>
              <option value="zoomInRight">zoomInRight</option>
              <option value="zoomInUp">zoomInUp</option>
            </optgroup>

            <optgroup label="Specials">
              <option value="rollIn">rollIn</option>
            </optgroup>
          </select>
       </div>
        <div class="form-group">
        <label>Exits</label>
          <select class="form-control" id="exit">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Exits">
              <option value="bounceOut">bounceOut</option>
              <option value="bounceOutDown">bounceOutDown</option>
              <option value="bounceOutLeft">bounceOutLeft</option>
              <option value="bounceOutRight">bounceOutRight</option>
              <option value="bounceOutUp">bounceOutUp</option>
            </optgroup>
            <optgroup label="Fading Exits">
              <option value="fadeOut">fadeOut</option>
              <option value="fadeOutDown">fadeOutDown</option>
              <option value="fadeOutDownBig">fadeOutDownBig</option>
              <option value="fadeOutLeft">fadeOutLeft</option>
              <option value="fadeOutLeftBig">fadeOutLeftBig</option>
              <option value="fadeOutRight">fadeOutRight</option>
              <option value="fadeOutRightBig">fadeOutRightBig</option>
              <option value="fadeOutUp">fadeOutUp</option>
              <option value="fadeOutUpBig">fadeOutUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipOutX" selected>flipOutX</option>
              <option value="flipOutY">flipOutY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedOut">lightSpeedOut</option>
            </optgroup>
            <optgroup label="Rotating Exits">
              <option value="rotateOut">rotateOut</option>
              <option value="rotateOutDownLeft">rotateOutDownLeft</option>
              <option value="rotateOutDownRight">rotateOutDownRight</option>
              <option value="rotateOutUpLeft">rotateOutUpLeft</option>
              <option value="rotateOutUpRight">rotateOutUpRight</option>
            </optgroup>
            <optgroup label="Sliding Exits">
              <option value="slideOutUp">slideOutUp</option>
              <option value="slideOutDown">slideOutDown</option>
              <option value="slideOutLeft">slideOutLeft</option>
              <option value="slideOutRight">slideOutRight</option>
            </optgroup>        
            <optgroup label="Zoom Exits">
              <option value="zoomOut">zoomOut</option>
              <option value="zoomOutDown">zoomOutDown</option>
              <option value="zoomOutLeft">zoomOutLeft</option>
              <option value="zoomOutRight">zoomOutRight</option>
              <option value="zoomOutUp">zoomOutUp</option>
            </optgroup>
            <optgroup label="Specials">
              <option value="rollOut">rollOut</option>
            </optgroup>

          </select>
       </div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>
    </form>

      <a class="btn btn-black " href="http://demo.nhembram.com/bootstrap-modal-animation-with-animate-css/index.html" target="_blank">View FullPage</a>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>

    <script>
    function testAnim(x) {
        $('.modal .modal-dialog').attr('class', 'modal-dialog  ' + x + '  animated');
    };
    $('#myModal').on('show.bs.modal', function (e) {
      var anim = $('#entrance').val();
          testAnim(anim);
    });
    $('#myModal').on('hide.bs.modal', function (e) {
      var anim = $('#exit').val();
          testAnim(anim);
    });
    </script>

<style>
body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}
</style>

How to have jQuery restrict file types on upload?

    $("input[name='btnsubmit']").attr('disabled', true);
    $('input[name="filphoto"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) 
    {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'bmp':
        $("input[name='btnsubmit']").attr('disabled', false);
    break;
    default:
        alert('This is not an allowed file type.');
        $("input[name='btnsubmit']").attr('disabled', true);
        this.value = '';

What is the difference between String and string in C#?

C# is a language which is used together with the CLR.

string is a type in C#.

System.String is a type in the CLR.

When you use C# together with the CLR string will be mapped to System.String.

Theoretically, you could implement a C#-compiler that generated Java bytecode. A sensible implementation of this compiler would probably map string to java.lang.String in order to interoperate with the Java runtime library.

How do I install Python libraries in wheel format?

Have you checked this http://docs.python.org/2/install/ ?

  1. First you have to install the module

    $ pip install requests

  2. Then, before using it you must import it from your program.

    from requests import requests

    Note that your modules must be in the same directory.

  3. Then you can use it.

    For this part you have to check for the documentation.

How to Exit a Method without Exiting the Program?

In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;

will always return at that point. However:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return;
}

will only return if it goes into that if statement.

Conda version pip install -r requirements.txt --target ./lib

A quick search on the conda official docs will help you to find what each flag does.

So far:

  • -y: Do not ask for confirmation.
  • -f: I think it should be --file, so it read package versions from the given file.
  • -q: Do not display progress bar.
  • -c: Additional channel to search for packages. These are URLs searched in the order

How do I define a method in Razor?

It's very simple to define a function inside razor.

@functions {

    public static HtmlString OrderedList(IEnumerable<string> items)
    { }
}

So you can call a the function anywhere. Like

@Functions.OrderedList(new[] { "Blue", "Red", "Green" })

However, this same work can be done through helper too. As an example

@helper OrderedList(IEnumerable<string> items){
    <ol>
        @foreach(var item in items){
            <li>@item</li>
        }
    </ol>
}

So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.

Windows service on Local Computer started and then stopped error

I have found it very handy to convert your existing windows service to a console by simply changing your program with the following. With this change you can run the program by debugging in visual studio or running the executable normally. But it will also work as a windows service. I also made a blog post about it

program.cs

class Program
{
    static void Main()
    {
        var program = new YOUR_PROGRAM();
        if (Environment.UserInteractive)
        {
            program.Start();
        }
        else
        {
            ServiceBase.Run(new ServiceBase[]
            {
                program
            });
        }
    }
}

YOUR_PROGRAM.cs

[RunInstallerAttribute(true)]
public class YOUR_PROGRAM : ServiceBase
{
    public YOUR_PROGRAM()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Start();
    }

    protected override void OnStop()
    {
        //Stop Logic Here
    }

    public void Start()
    {
        //Start Logic here
    }
}

Compare two columns using pandas

Wrap each individual condition in parentheses, and then use the & operator to combine the conditions:

df.loc[(df['one'] >= df['two']) & (df['one'] <= df['three']), 'que'] = df['one']

You can fill the non-matching rows by just using ~ (the "not" operator) to invert the match:

df.loc[~ ((df['one'] >= df['two']) & (df['one'] <= df['three'])), 'que'] = ''

You need to use & and ~ rather than and and not because the & and ~ operators work element-by-element.

The final result:

df
Out[8]: 
  one  two three que
0  10  1.2   4.2  10
1  15   70  0.03    
2   8    5     0  

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.

I'd prefer to use OneJar for this issue.

Add up a column of numbers at the Unix shell

cat will not work if there are spaces in filenames. here is a perl one-liner instead.

perl -nle 'chomp; $x+=(stat($_))[7]; END{print $x}' files.txt

Android Studio - Unable to find valid certification path to requested target

I'm in an enterprise environment with a proxy/firewall/virus-scanner combination adding the company own SSL root certificate (self signed) to the trustpath of every SSL connection to investigate also into SSL connections. That was exactly the problem. If you are in the same situation this solution could help:

  1. Open https://jcenter.bintray.com in the browser (I prefer Firefox)
  2. Click on the padlock symbold to check the certificated trustpath. If the top/root certificate in the tree is a certficate signed by your company export it to your harddisk.
  3. To be safe export also every certificate in between
  4. Open the truststore of Android Studio in path JDKPATH/jre/lib/security/cacerts with the Keystore Explorer tool Keystore Exlorer with password "changeit"
  5. Import the exported certs into the trusstore starting with the root certificate of you company and go the step 6. In the most cases this will do the trick. If not, import the other certs as well step by step.
  6. Save the truststore
  7. Exit Android Studio with "File -> Invalidate Caches/Restart"

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

First of all: Don't put secrets in clear text unless you know why it is a safe thing to do (i.e. you have assessed what damage can be done by an attacker knowing the secret).

If you are ok with putting secrets in your script, you could ship an ssh key with it and execute in an ssh-agent shell:

#!/usr/bin/env ssh-agent /usr/bin/env bash
KEYFILE=`mktemp`
cat << EOF > ${KEYFILE}
-----BEGIN RSA PRIVATE KEY-----
[.......]
EOF
ssh-add ${KEYFILE}

# do your ssh things here...

# Remove the key file.
rm -f ${KEYFILE}

A benefit of using ssh keys is that you can easily use forced commands to limit what the keyholder can do on the server.

A more secure approach would be to let the script run ssh-keygen -f ~/.ssh/my-script-key to create a private key specific for this purpose, but then you would also need a routine for adding the public key to the server.

C# go to next item in list based on if statement in foreach

Use continue; instead of break; to enter the next iteration of the loop without executing any more of the contained code.

foreach (Item item in myItemsList)
{
   if (item.Name == string.Empty)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
      continue;
   }

   if (item.Weight > 100)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
      continue;
   }
}

Official docs are here, but they don't add very much color.

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1' 
        // Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

How to get current memory usage in android?

you can also use DDMS tool which is part of android SDK it self. it helps in getting memory allocations of java code and native c/c++ code as well.

Copying an array of objects into another array in javascript

If you want to keep reference:

Array.prototype.push.apply(destinationArray, sourceArray);

Is there a Sleep/Pause/Wait function in JavaScript?

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

How to view the roles and permissions granted to any database user in Azure SQL server instance?

To view database roles assigned to users, you can use sys.database_role_members

The following query returns the members of the database roles.

SELECT DP1.name AS DatabaseRoleName,   
    isnull (DP2.name, 'No members') AS DatabaseUserName   
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
ORDER BY DP1.name;  

In DB2 Display a table's definition

Describe table syntax

describe table schemaName.TableName

Getting current directory in VBScript

Your line

Directory = CurrentDirectory\attribute.exe

does not match any feature I have encountered in a vbscript instruction manual. The following works for me, tho not sure what/where you expect "attribute.exe" to reside.

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run curDir & "\testme.bat", 1
set WinScriptHost = nothing

How to move div vertically down using CSS

I don't see any mention of flexbox in here, so I will illustrate:

HTML

 <div class="wrapper">
   <div class="main">top</div>
   <div class="footer">bottom</div>
 </div>

CSS

 .wrapper {
   display: flex;
   flex-direction: column;
   min-height: 100vh;
  }
 .main {
   flex: 1;
 }
 .footer {
  flex: 0;
 }

How to convert time milliseconds to hours, min, sec format in JavaScript?

This one returns time like youtube videos

    function getYoutubeLikeToDisplay(millisec) {
        var seconds = (millisec / 1000).toFixed(0);
        var minutes = Math.floor(seconds / 60);
        var hours = "";
        if (minutes > 59) {
            hours = Math.floor(minutes / 60);
            hours = (hours >= 10) ? hours : "0" + hours;
            minutes = minutes - (hours * 60);
            minutes = (minutes >= 10) ? minutes : "0" + minutes;
        }

        seconds = Math.floor(seconds % 60);
        seconds = (seconds >= 10) ? seconds : "0" + seconds;
        if (hours != "") {
            return hours + ":" + minutes + ":" + seconds;
        }
        return minutes + ":" + seconds;
    }

Output:

  • getYoutubeLikeToDisplay(129900) = "2:10"
  • getYoutubeLikeToDisplay(1229900) = "20:30"
  • getYoutubeLikeToDisplay(21229900) = "05:53:50"

Phone number formatting an EditText in Android

Follow the instructions in this Answer to format the EditText mask.

https://stackoverflow.com/a/34907607/1013929

And after that, you can catch the original numbers from the masked string with:

String phoneNumbers = maskedString.replaceAll("[^\\d]", "");

jQuery textbox change event

I have found that this works:

$(document).ready(function(){
    $('textarea').bind('input propertychange', function() {
        //do your update here
    }

})

Visual Studio 2012 Web Publish doesn't copy files

I've got into same problem. None of the above solutions worked for me.

So, I've excluded the files which failed to copy while publishing.

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Ready

function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}

Use like

ready(function(){
    //some code
});

For self invoking code

(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){

    //Some Code here
    //DOM is avaliable
    //var h1s = document.querySelector("h1");

});

Support: IE9+

Open Form2 from Form1, close Form1 from Form2

on the form2.buttonclick put

this.close();

form1 should have object of form2.

you need to subscribe Closing event of form2.

and in closing method put

this.close();

HTTP 404 when accessing .svc file in IIS

I see you've already solved your problem - but for posterity:

We had a similar problem, and the SVC handler was already correctly installed. Our problem was the ExtensionlessUrl handler processing requests before they reached the SVC handler.

To check this - in Handler Mappings in IIS Manager at the web server level, view the list of handlers in order (it's an option on the right-hand side). If the various ExtensionlessUrl handlers appear above the SVC handlers, then repeatedly move them down until they're at the bottom.

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.