Programs & Examples On #Browsercaps

get list of pandas dataframe columns based on data type

You can use boolean mask on the dtypes attribute:

In [11]: df = pd.DataFrame([[1, 2.3456, 'c']])

In [12]: df.dtypes
Out[12]: 
0      int64
1    float64
2     object
dtype: object

In [13]: msk = df.dtypes == np.float64  # or object, etc.

In [14]: msk
Out[14]: 
0    False
1     True
2    False
dtype: bool

You can look at just those columns with the desired dtype:

In [15]: df.loc[:, msk]
Out[15]: 
        1
0  2.3456

Now you can use round (or whatever) and assign it back:

In [16]: np.round(df.loc[:, msk], 2)
Out[16]: 
      1
0  2.35

In [17]: df.loc[:, msk] = np.round(df.loc[:, msk], 2)

In [18]: df
Out[18]: 
   0     1  2
0  1  2.35  c

Iterating through a list to render multiple widgets in Flutter?

It is now possible to achieve that in Flutter 1.5 and Dart 2.3 by using a for element in your collection.

var list = ["one", "two", "three", "four"]; 

child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
             for(var item in list ) Text(item)
          ],
        ),    

This will display four Text widgets containing the items in the list.
NB. No braces around the for loop and no return keyword.

Bash script and /bin/bash^M: bad interpreter: No such file or directory

This is caused by editing file in windows and importing and executing in unix.

dos2unix -k -o filename should do the trick.

How to escape the % (percent) sign in C's printf?

Nitpick:
You don't really escape the % in the string that specifies the format for the printf() (and scanf()) family of functions.

The %, in the printf() (and scanf()) family of functions, starts a conversion specification. One of the rules for conversion specification states that a % as a conversion specifier (immediately following the % that started the conversion specification) causes a '%' character to be written with no argument converted.

The string really has 2 '%' characters inside (as opposed to escaping characters: "a\bc" is a string with 3 non null characters; "a%%b" is a string with 4 non null characters).

How to view the contents of an Android APK file?

Actually the apk file is just a zip archive, so you can try to rename the file to theappname.apk.zip and extract it with any zip utility (e.g. 7zip).

The androidmanifest.xml file and the resources will be extracted and can be viewed whereas the source code is not in the package - just the compiled .dex file ("Dalvik Executable")

How can I fix "Design editor is unavailable until a successful build" error?

Edit you xml file in Notepad++ and build it again. It's work for me

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

How Do I Take a Screen Shot of a UIView?

CGImageRef UIGetScreenImage();

Apple now allows us to use it in a public application, even though it's a private API

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

My test assembly is 64-bit. From the menu bar at the top of visual studio 2012, I was able to select 'Test' -> 'Test Settings' -> 'Default Processor Architecture' -> 'X64'. After a 'Rebuild Solution' from the 'Build' menu, I was able to see all of my tests in test explorer. Hopefully this helps someone else in the future =D.

json_decode() expects parameter 1 to be string, array given

Ok I was running into the same issue. What I failed to notice is that I was using json_decode() instead of using json_encode() so for those who are going to come here please make sure you are using the right function, which is json_encode()

Note: Depends on what you are working on but make sure you are using the right function.

Change hover color on a button with Bootstrap customization

or can do this...
set all btn ( class name like : .btn- + $theme-colors: map-merge ) styles at one time :

@each $color, $value in $theme-colors {
  .btn-#{$color} {
    @include button-variant($value, $value,
    // modify
    $hover-background: lighten($value, 7.5%),
    $hover-border: lighten($value, 10%),
    $active-background: lighten($value, 10%),
    $active-border: lighten($value, 12.5%)
    // /modify
    );
  }
}

// code from "node_modules/bootstrap/scss/_buttons.scss"

should add into your customization scss file.

Disable vertical scroll bar on div overflow: auto

You should use only

overflow-y:hidden; - Use this for hiding the Vertical scroll

overflow-x:auto; - Use this to show Horizontal scroll

Luke has mentioned as both hidden. so I have given this separately.

How to force Selenium WebDriver to click on element which is not currently visible?

Sometimes this means there are multiple elements on a page that have the same property you're trying to search by and you're "talking to the wrong one".

If your element can't be uniquely identified by :id or :name (or :class), it could be tricky.

Sometimes searching for the element by the :xpath will help and in some cases even that is not practical.

In those cases, you may have to get all the elements that match your criteria and reference the right one by the index. It's dirty, but it works.

I'm using Selenium / Watir from Ruby on Rails app, so in my case the example would be:

browser = Watir::Browser.new(:firefox, :profile => "default")       
browser.goto("http://www.google.com/analytics")
# login
browser.divs(:text, "+ New Property").last.click

Hope this helps.

The remote certificate is invalid according to the validation procedure

Try put this before send e-mail

ServicePointManager.ServerCertificateValidationCallback = 
        delegate(object s, X509Certificate certificate, X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; };

Remenber to add the using libs!

Throwing multiple exceptions in a method of an interface in java

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

Then an interface would look like this

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Try Using DateTime::createFromFormat

$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');

Output

2012-04-24

EDIT:

If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.

$old_date = explode('/', '5/4/2010'); 
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];

OUTPUT:

2010-4-5

How to get my activity context?

The best and easy way to get the activity context is putting .this after the name of the Activity. For example: If your Activity's name is SecondActivity, its context will be SecondActivity.this

Extract part of a regex match

May I recommend you to Beautiful Soup. Soup is a very good lib to parse all of your html document.

soup = BeatifulSoup(html_doc)
titleName = soup.title.name

Get unique values from arraylist in java

When I was doing the same query, I had hard time adjusting the solutions to my case, though all the previous answers have good insights.

Here is a solution when one has to acquire a list of unique objects, NOT strings. Let's say, one has a list of Record object. Record class has only properties of type String, NO property of type int. Here implementing hashCode() becomes difficult as hashCode() needs to return an int.

The following is a sample Record Class.

public class Record{

    String employeeName;
    String employeeGroup;

    Record(String name, String group){  
        employeeName= name;
        employeeGroup = group;    
    }
    public String getEmployeeName(){
        return employeeName;
    }
    public String getEmployeeGroup(){
        return employeeGroup;
    }

  @Override
    public boolean equals(Object o){
         if(o instanceof Record){
            if (((Record) o).employeeGroup.equals(employeeGroup) &&
                  ((Record) o).employeeName.equals(employeeName)){
                return true;
            }
         }
         return false;
    }

    @Override
    public int hashCode() { //this should return a unique code
        int hash = 3; //this could be anything, but I would chose a prime(e.g. 5, 7, 11 )
        //again, the multiplier could be anything like 59,79,89, any prime
        hash = 89 * hash + Objects.hashCode(this.employeeGroup); 
        return hash;
    }

As suggested earlier by others, the class needs to override both the equals() and the hashCode() method to be able to use HashSet.

Now, let's say, the list of Records is allRecord(List<Record> allRecord).

Set<Record> distinctRecords = new HashSet<>();

for(Record rc: allRecord){
    distinctRecords.add(rc);
}

This will only add the distinct Records to the Hashset, distinctRecords.

Hope this helps.

How to get the date 7 days earlier date from current date in Java

Use the Calendar-API:

// get Calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());

// substract 7 days
// If we give 7 there it will give 8 days back
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-6);

// convert to date
Date myDate = cal.getTime();

Hope this helps. Have Fun!

setting request headers in selenium

I wanted something a bit slimmer for RSpec/Ruby so that the custom code only had to live in one place. Here's my solution:

/spec/support/selenium.rb
...
RSpec.configure do |config|
  config.after(:suite) do
    $custom_headers = nil
  end
end

module RequestWithExtraHeaders
  def headers
    $custom_headers.each do |key, value|
      self.set_header "HTTP_#{key}", value
    end if $custom_headers

    super
  end
end
class ActionDispatch::Request
  prepend RequestWithExtraHeaders
end

Then in my specs:

/specs/features/something_spec.rb
...
$custom_headers = {"Referer" => referer_string}

Sending mass email using PHP

You can use swiftmailer for it. By using batch process.

<?php
    $message = Swift_Message::newInstance()
      ->setSubject('Let\'s get together today.')
      ->setFrom(array('[email protected]' => 'From Me'))
      ->setBody('Here is the message itself')
      ->addPart('<b>Test message being sent!!</b>', 'text/html');

    $data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
    while($row = mysql_fetch_assoc($data))
    {
       $message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
    }

    $message->batchSend();
?>

What is the difference between sscanf or atoi to convert a string to an integer?

You have 3 choices:

  1. atoi

This is probably the fastest if you're using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in int, the behaviour is unspecified.

  1. sscanf

Some error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of char/short/int/long/long long/size_t/ptrdiff_t/intmax_t).

The return value is the number of conversions that succeed, so scanning for "%d" will return 0 if the string does not begin with an integer. You can use "%d%n" to store the index of the first character after the integer that's read in another variable, and thereby check to see if the entire string was converted or if there's junk afterwards. However, like atoi, behaviour on integer overflow is unspecified.

  1. strtol and family

Robust error reporting, provided you set errno to 0 before making the call. Return values are specified on overflow and errno will be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading 0x and 0 as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions of long/long long/intmax_t.

If you need a smaller type you can always store the result in a temporary long or unsigned long variable and check for overflow yourself.

Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.


Personally, I would recommend the strtol family for most purposes. If you're doing something quick-and-dirty, atoi might meet your needs.

As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it's pretty damn easy to roll your own for loop, eg.,

for (x=0; (unsigned)*s-'0'<10; s++) 
    x=10*x+(*s-'0');

Or you can use (for robustness):

if (isdigit(*s))
    x=strtol(s, &s, 10);
else /* error */ 

Android - get children inside a View?

Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

Storing query results into a variable and modifying it inside a Stored Procedure

Or you can use one SQL-command instead of create and call stored procedure

INSERT INTO [order_cart](orId,caId)
OUTPUT inserted.*
SELECT
   (SELECT MAX(orId) FROM [order]) as orId,
   (SELECT MAX(caId) FROM [cart]) as caId;

How to delete a cookie?

To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):

1.

    function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }
        document.cookie = key +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie(name, "", null , null , null, 1);
    }

Usage:

setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");

2

    function setCookie(params) {
        var name            = params.name,
            value           = params.value,
            expireDays      = params.days,
            expireHours     = params.hours,
            expireMinutes   = params.minutes,
            expireSeconds   = params.seconds;

        var expireDate = new Date();
        if (expireDays) {
            expireDate.setDate(expireDate.getDate() + expireDays);
        }
        if (expireHours) {
            expireDate.setHours(expireDate.getHours() + expireHours);
        }
        if (expireMinutes) {
            expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
        }
        if (expireSeconds) {
            expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
        }

        document.cookie = name +"="+ escape(value) +
            ";domain="+ window.location.hostname +
            ";path=/"+
            ";expires="+expireDate.toUTCString();
    }

    function deleteCookie(name) {
        setCookie({name: name, value: "", seconds: 1});
    }

Usage:

setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");

how to configure lombok in eclipse luna

For Integrattion with ECLIPSE LUNA in Windows 7 please foollow the below steps:

  • Download the jar -> lombok-1.14.6.jar.
  • Using command prompt go to java installed directory and type

    java -jar ${your_jar_path}\lombok-1.14.6.jar.
    

    Here ${your_jar_path} is your lombok-1.14.6.jar jar store directory.

  • After this it will prompt for Eclipse already installed in your system and you need to select where you want to integrate.
  • After this you need to open eclipse.ini file and make entry below

    -vmargs
    

    as

    -Xbootclasspath/a:lombok.jar
    -javaagent:lombok.jar
    
  • Start your eclipse now and create a Maven project and make entry in pom.xml as mentioned below:

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.14.6</version>
        <scope>provided</scope>
    </dependency>
    

After this your are ready to write your code and check it. Without @DATA annotation it looks like: enter image description here With @DATA annotation it looks like: enter image description here

An example i ran the command

C:\Program Files\Java\jdk1.7.0_75>java -jar C:\Users\Shareef-VM.m2\repository\o rg\projectlombok\lombok\1.14.8\lombok-1.14.8.jar

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

How to downgrade Node version

For windows 10,

  • Uninstalling the node from the "Add or remove programs"
  • Installing the required version from https://nodejs.org/en/

worked for me.

Numpy: Checking if a value is NaT

Very simple and surprisingly fast: (without numpy or pandas)

    str( myDate ) == 'NaT'            # True if myDate is NaT

Ok, it's a little nasty, but given the ambiguity surrounding 'NaT' it does the job nicely.

It's also useful when comparing two dates either of which might be NaT as follows:

   str( date1 ) == str( date1 )       # True
   str( date1 ) == str( NaT )         # False
   str( NaT )   == str( date1 )       # False

wait for it...

   str( NaT )   == str( Nat )         # True    (hooray!)

Convert an array into an ArrayList

This will give you a list.

List<Card> cardsList = Arrays.asList(hand);

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));

What's the -practical- difference between a Bare and non-Bare repository?

Non bare repository allows you to (into your working tree) capture changes by creating new commits.

Bare repositories are only changed by transporting changes from other repositories.

JavaScript dictionary with names

Try:

var myMappings = {
    "Name":     "10%",
    "Phone":    "10%",
    "Address":  "50%",
    "Zip":      "10%",
    "Comments": "20%"
}

// Access is like this
myMappings["Name"] // Returns "10%"
myMappings.Name // The same thing as above

// To loop through...
for(var title in myMappings) {
    // Do whatever with myMappings[title]
}

Creating a button in Android Toolbar

I was able to achieve that by wrapping Button with ConstraintLayout:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/top_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white_color">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/cancel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/cancel"
                    android:layout_marginStart="5dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <Button
                    android:id="@+id/btn_publish"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/publish"
                    android:background="@drawable/button_publish_rounded"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    android:layout_marginEnd="10dp"
                    app:layout_constraintLeft_toRightOf="@id/cancel"
                    tools:layout_editor_absoluteY="0dp" />

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

You may create a drawable resourcebutton_publish_rounded, define the button properties and assign this file to button's android:background property:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/green" />
    <corners android:radius="100dp" />
</shape>

jQuery - add additional parameters on submit (NOT ajax)

Similar answer, but I just wanted to make it available for an easy/quick test.

_x000D_
_x000D_
var input = $("<input>")_x000D_
               .attr("name", "mydata").val("go Rafa!");_x000D_
_x000D_
$('#easy_test').append(input);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<form id="easy_test">_x000D_
  _x000D_
</form>
_x000D_
_x000D_
_x000D_

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:

TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
List<[YourClass]> list = query.getResultList(); //no type warning

This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.

What is a predicate in c#?

The following code can help you to understand some real world use of predicates (Combined with named iterators).

namespace Predicate
{
    class Person
    {
        public int Age { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Person person in OlderThan(18))
            {
                Console.WriteLine(person.Age);
            }
        }

        static IEnumerable<Person> OlderThan(int age)
        {
            Predicate<Person> isOld = x => x.Age > age;
            Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };

            foreach (Person person in persons)
                if (isOld(person)) yield return person;
        }
    }
}

Find files containing a given text

find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'

Checking if a string can be converted to float in Python

This regex will check for scientific floating point numbers:

^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$

However, I believe that your best bet is to use the parser in a try.

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

Android, Java: HTTP POST Request

I used the following code to send HTTP POST from my android client app to C# desktop app on my server:

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

I worked on reading the request from a C# app on my server (something like a web server little application). I managed to read request posted data using the following code:

server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();

HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;

StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();

C++ "Access violation reading location" Error

You haven't posted the findvertex method, but Access Reading Violation with an offset like 0x00000048 means that the Vertex* f; in your getCost function is receiving null, and when trying to access the member adj in the null Vertex pointer (that is, in f), it is offsetting to adj (in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0 or null memory address.

Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex isn't returning null, or do a comparisong for null on f before using it to keep yourself sane (or use an assert):

assert( f != null ); // A good sanity check

EDIT:

If you have a map for doing something like a find, you can just use the map's find method to make sure the vertex exists:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

Just make sure you're still careful to handle the error case where it does return NULL. Otherwise, you'll keep getting this access violation.

Does C# support multiple inheritance?

Nope, use interfaces instead! ^.^

What does "#pragma comment" mean?

#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.

#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies

See #pragma comment on MSDN

How do I get the coordinate position after using jQuery drag and drop?

If you are listening to the dragstop or other events, the original position should be a ui parameter:

dragstop: function(event, ui) {
    var originalPosition = ui.originalPosition;
}

Otherwise, I believe the only way to get it is:

draggable.data("draggable").originalPosition

Where draggable is the object you are dragging. The second version is not guaranteed to work in future versions of jQuery.

javascript create empty array of a given size

1) To create new array which, you cannot iterate over, you can use array constructor:

Array(100) or new Array(100)


2) You can create new array, which can be iterated over like below:

a) All JavaScript versions

  • Array.apply: Array.apply(null, Array(100))

b) From ES6 JavaScript version

  • Destructuring operator: [...Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from({ length: 100 })

You can map over these arrays like below.

  • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i) [0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i) [0, 1, 2, 3]

Adding JPanel to JFrame

Your Test2 class is not a Component, it has a Component which is a difference.

Either you do something like

frame.add(test.getPanel() );

after you introduced a getter for the panel in your class, or you make sure your Test2 class becomes a Component (e.g. by extending a JPanel)

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

Can I use jQuery with Node.js?

First of all install it

npm install jquery -S

After installing it, you can use it as below

import $ from 'jquery';
window.jQuery = window.$ = $;
$(selector).hide();

You can check out a full tutorial that I wrote here: https://medium.com/fbdevclagos/how-to-use-jquery-on-node-df731bd6abc7

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

If you don't have to store more than 24 hours you can just store time, since SQL Server 2008 and later the mapping is

time (SQL Server) <-> TimeSpan(.NET)

No conversions needed if you only need to store 24 hours or less.

Source: http://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

But, if you want to store more than 24h, you are going to need to store it in ticks, retrieve the data and then convert to TimeSpan. For example

int timeData = yourContext.yourTable.FirstOrDefault();
TimeSpan ts = TimeSpan.FromMilliseconds(timeData);

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

The or and and python statements require truth-values. For pandas these are considered ambiguous so you should use "bitwise" | (or) or & (and) operations:

result = result[(result['var']>0.25) | (result['var']<-0.25)]

These are overloaded for these kind of datastructures to yield the element-wise or (or and).


Just to add some more explanation to this statement:

The exception is thrown when you want to get the bool of a pandas.Series:

>>> import pandas as pd
>>> x = pd.Series([1])
>>> bool(x)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What you hit was a place where the operator implicitly converted the operands to bool (you used or but it also happens for and, if and while):

>>> x or x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> x and x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> if x:
...     print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> while x:
...     print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Besides these 4 statements there are several python functions that hide some bool calls (like any, all, filter, ...) these are normally not problematic with pandas.Series but for completeness I wanted to mention these.


In your case the exception isn't really helpful, because it doesn't mention the right alternatives. For and and or you can use (if you want element-wise comparisons):

  • numpy.logical_or:

    >>> import numpy as np
    >>> np.logical_or(x, y)
    

    or simply the | operator:

    >>> x | y
    
  • numpy.logical_and:

    >>> np.logical_and(x, y)
    

    or simply the & operator:

    >>> x & y
    

If you're using the operators then make sure you set your parenthesis correctly because of the operator precedence.

There are several logical numpy functions which should work on pandas.Series.


The alternatives mentioned in the Exception are more suited if you encountered it when doing if or while. I'll shortly explain each of these:

  • If you want to check if your Series is empty:

    >>> x = pd.Series([])
    >>> x.empty
    True
    >>> x = pd.Series([1])
    >>> x.empty
    False
    

    Python normally interprets the length of containers (like list, tuple, ...) as truth-value if it has no explicit boolean interpretation. So if you want the python-like check, you could do: if x.size or if not x.empty instead of if x.

  • If your Series contains one and only one boolean value:

    >>> x = pd.Series([100])
    >>> (x > 50).bool()
    True
    >>> (x < 50).bool()
    False
    
  • If you want to check the first and only item of your Series (like .bool() but works even for not boolean contents):

    >>> x = pd.Series([100])
    >>> x.item()
    100
    
  • If you want to check if all or any item is not-zero, not-empty or not-False:

    >>> x = pd.Series([0, 1, 2])
    >>> x.all()   # because one element is zero
    False
    >>> x.any()   # because one (or more) elements are non-zero
    True
    

How to use the switch statement in R functions?

Well, switch probably wasn't really meant to work like this, but you can:

AA = 'foo'
switch(AA, 
foo={
  # case 'foo' here...
  print('foo')
},
bar={
  # case 'bar' here...
  print('bar')    
},
{
   print('default')
}
)

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

Change R default library path using .libPaths in Rprofile.site fails to work

I read the readme. In that they mentioned use .libPaths() in command line to check which paths are there. I had 2 library paths earlier. When I used the command .libpath("C:/Program Files/R/R-3.2.4revised/library") where I wanted, it changed the library path. When I typed in .libPaths() at the command line again it showed me the correct path. Hope this helps

What is the best way to insert source code examples into a Microsoft Word document?

There is an easy way if you want simple code formatting.

  1. Open word> Insert tab> click on "Get Add-ins"
  2. search for "Content mixer" 3.click on "Add"

Then content mixer add will open automatically and you can copy paste your code in there and click on "Insert" to insert it in word doc.

WAMP won't turn green. And the VCRUNTIME140.dll error

I had the same problem, and I solved it by installing :

NB : 64 bit installation was enough, I had to uninstall / reinstall Wamp after that

How to start up spring-boot application via command line?

A Spring Boot project configured through Maven can be run using the following command from the project source folder

mvn spring-boot:run

How to output JavaScript with PHP

<?php

echo '<script type="text/javascript">document.write(\'Hello world\');</script>';
?>

JS. How to replace html element with another element/text, represented in string?

Using jQuery you can do this:

var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);

http://jsfiddle.net/hZBeW/4/

Or in pure javascript:

var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;

http://jsfiddle.net/hZBeW/1/

The real difference between "int" and "unsigned int"

Yes, because in your case they use the same representation.

The bit pattern 0xFFFFFFFF happens to look like -1 when interpreted as a 32b signed integer and as 4294967295 when interpreted as a 32b unsigned integer.

It's the same as char c = 65. If you interpret it as a signed integer, it's 65. If you interpret it as a character it's a.


As R and pmg point out, technically it's undefined behavior to pass arguments that don't match the format specifiers. So the program could do anything (from printing random values to crashing, to printing the "right" thing, etc).

The standard points it out in 7.19.6.1-9

If a conversion speci?cation is invalid, the behavior is unde?ned. If any argument is not the correct type for the corresponding conversion speci?cation, the behavior is unde?ned.

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

Non-static method requires a target

I think this confusing exception occurs when you use a variable in a lambda which is a null-reference at run-time. In your case, I would check if your variable calculationViewModel is a null-reference.

Something like:

public ActionResult MNPurchase()
{
    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];

    if (calculationViewModel != null)
    {
        decimal OP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.SalesPrice)
            .FirstOrDefault()
            .OP;

        decimal MP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.MortgageAmount)
            .FirstOrDefault()
            .MP;

        calculationViewModel.LoanAmount = (OP + 100) - MP;
        calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);

        return View(calculationViewModel);
    }
    else
    {
        // Do something else...
    }
}

How can I start an Activity from a non-Activity class?

I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.

Try this: ((Activity) mContext).startActivity(...)

How to find the extension of a file in C#?

I'm not sure if this is what you want but:

Directory.GetFiles(@"c:\mydir", "*.flv");

Or:

Path.GetExtension(@"c:\test.flv")

Aren't Python strings immutable? Then why does a + " " + b work?

Consider this addition to your example

 a = "Dog"
 b = "eats"
 c = "treats"
 print (a,b,c)
 #Dog eats treats
 d = a + " " + b + " " + c
 print (a)
 #Dog
 print (d)
 #Dog eats treats

One of the more precise explanations I found in a blog is:

In Python, (almost) everything is an object. What we commonly refer to as "variables" in Python are more properly called names. Likewise, "assignment" is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.

Eg:

some_guy = 'Fred'
# ...
some_guy = 'George'

When we later say some_guy = 'George', the string object containing 'Fred' is unaffected. We've just changed the binding of the name some_guy. We haven't, however, changed either the 'Fred' or 'George' string objects. As far as we're concerned, they may live on indefinitely.

Link to blog: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

Check if enum exists in Java

Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.

I have come up with the following three alternatives on how to look up an enum:

private enum Test {
    TEST1, TEST2;

    public Test fromNameOrThrowException(String name) {
        return Arrays.stream(values())
                .filter(e -> e.name().equals(name))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
    }

    public Test fromNameOrNull(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
    }

    public Optional<Test> fromName(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
    }
}

How can I pass a parameter in Action?

If you know what parameter you want to pass, take a Action<T> for the type. Example:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

If you want the parameter to be passed to your method, make the method generic:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}

And the caller code:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");

Update. Your code should look like:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}

How to convert an address to a latitude/longitude?

Try with this code, i work like this with addresses:

It is link in which with GET method you will send request and get lat and lng. http://maps.google.com/maps/api/geocode/json?address=YOUR ADDRES&sensor=false

For exemple: http://maps.google.com/maps/api/geocode/json?address=W Main St, Bergenfield, NJ 07621&sensor=false

1. Create your GET method.

 public static String GET(String url) throws Exception {//GET Method
        String result = null;
        InputStream inputStream = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

        Log.v("ExecuteGET: ", httpGet.getRequestLine().toString());

        HttpResponse httpResponse = httpclient.execute(httpGet);
        inputStream = httpResponse.getEntity().getContent();
        if (inputStream != null) {
            result = convertInputStreamToString(inputStream);
            Log.v("Result: ", "result\n" + result);
        } 
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

2. Create method for send request

@SuppressWarnings("deprecation")
    public static String getLatLng(String accessToken) throws Exception{
        String query=StaticString.gLobalGoogleUrl+"json?address="+URLEncoder.encode(accessToken)+"&sensor=false";
        Log.v("GETGoogleGeocoder", query+"");
        return GET(query);
    }

gLobalGoogleUrl="http://maps.google.com/maps/api/geocode/"

3. Call method getLatLng

String result=getLatLng("W Main St, Bergenfield, NJ 07621");

4. Parse JSONObject

Now result is JSONObject with information about address and lan,lng. Parse JSONObject (result) with gson(). After that use lat,lng.

If you have question about code , ask.

Is it good practice to make the constructor throw an exception?

This is totally valid, I do it all the time. I usually use IllegalArguemntException if it is a result of parameter checking.

In this case I wouldn't suggest asserts because they are turned off in a deployment build and you always want to stop this from happening, but they are valid if your group does ALL it's testing with asserts turned on and you think the chance of missing a parameter problem at runtime is more acceptable than throwing an exception that is maybe more likely to cause a runtime crash.

Also, an assert would be more difficult for the caller to trap, this is easy.

You probably want to list it as a "throws" in your method's javadocs along with the reason so that callers aren't surprised.

git push to specific branch

git push origin amd_qlp_tester will work for you. If you just type git push, then the remote of the current branch is the default value.

Syntax of push looks like this - git push <remote> <branch>. If you look at your remote in .git/config file, you will see an entry [remote "origin"] which specifies url of the repository. So, in the first part of command you will tell Git where to find repository for this project, and then you just specify a branch.

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

PHP exec() vs system() vs passthru()

They have slightly different purposes.

  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Regardless, I suggest you not use any of them. They all produce highly unportable code.

What is a plain English explanation of "Big O" notation?

I've more simpler way to understand the time complexity he most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

statement;

Is constant. The running time of the statement will not change in relation to N

for ( i = 0; i < N; i++ )
  statement;

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) 
{
for ( j = 0; j < N; j++ )
  statement;
}

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) 
{
 mid = ( low + high ) / 2;
 if ( target < list[mid] )
 high = mid - 1;
 else if ( target > list[mid] )
  low = mid + 1;
else break;
}

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
{
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );
}

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( ) where is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note: None of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course.

Displaying the Error Messages in Laravel after being Redirected from controller

Below input field I include additional view:

@include('input-errors', ['inputName' => 'inputName']) #For your case it would be 'email'

input-errors.blade.php

@foreach ($errors->get($inputName) as $message)
    <span class="input-error">{{ $message }}</span>
@endforeach

CSS - adds red color to the message.

.input-error {
    color: #ff5555;
}

Hiding axis text in matplotlib plots

I've colour coded this figure to ease the process.

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

enter image description here

You can have full control over the figure using these commands, to complete the answer I've add also the control over the splines:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)

How can I use onItemSelected in Android?

spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner2 has a selected item and show the value in edittext

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

               //check if spinner1 has a selected item and show the value in edittext


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Set column as unique in SQL Server from the GUI:

They really make you run around the barn to do it with the GUI:

Make sure your column does not violate the unique constraint before you begin.

  1. Open SQL Server Management Studio.
  2. Right click your Table, click "Design".
  3. Right click the column you want to edit, a popup menu appears, click Indexes/Keys.
  4. Click the "Add" Button.
  5. Expand the "General" tab.
  6. Make sure you have the column you want to make unique selected in the "columns" box.
  7. Change the "Type" box to "Unique Key".
  8. Click "Close".
  9. You see a little asterisk in the file window, this means changes are not yet saved.
  10. Press Save or hit Ctrl+s. It should save, and your column should be unique.

Or set column as unique from the SQL Query window:

alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);

Changes take effect immediately:

Command(s) completed successfully.

OnClick in Excel VBA

This has worked for me.....

Private Sub Worksheet_Change(ByVal Target As Range)

    If Mid(Target.Address, 3, 1) = "$" And Mid(Target.Address, 2, 1) < "E" Then
       ' The logic in the if condition will filter for a specific cell or block of cells
       Application.ScreenUpdating = False
       'MsgBox "You just changed " & Target.Address

       'all conditions are true .... DO THE FUNCTION NEEDED 
       Application.ScreenUpdating = True
    End If
    ' if clicked cell is not in the range then do nothing (if condttion is not run)  
End Sub

NOTE: this function in actual use recalculated a pivot table if a user added a item in a data range of A4 to D500. The there were protected and unprotected sections in the sheet so the actual check for the click is if the column is less that "E" The logic can get as complex as you want to include or exclude any number of areas

block1  = row > 3 and row < 5 and column column >"b" and < "d" 
block2  = row > 7 and row < 12 and column column >"b" and < "d" 
block3  = row > 10 and row < 15 and column column >"e" and < "g"

If block1 or block2 or block 3 then
  do function .....
end if  

Setting onClickListener for the Drawable right of an EditText

Please use below trick:

  • Create an image button with your icon and set its background color to be transparent.
  • Put the image button on the EditText
  • Implement the 'onclic'k listener of the button to execute your function

Accessing the index in 'for' loops?

Here's what you get when you're accessing index in for loops:

for i in enumerate(items): print(i)

items = [8, 23, 45, 12, 78]

for i in enumerate(items):
    print("index/value", i)

Result:

# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)

for i, val in enumerate(items): print(i, val)

items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i, "for value", val)

Result:

# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78

for i, val in enumerate(items): print(i)

items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i)

Result:

# index 0
# index 1
# index 2
# index 3
# index 4

How can I select the row with the highest ID in MySQL?

SELECT MAX(id) FROM TABELNAME

This identifies the largest id and returns the value

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

this worked for me.

    $('#thedate').datepicker({
    dateFormat: 'dd-mm-yy',
    altField: '#thealtdate',
    altFormat: 'yy-mm-dd'
});

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Can't import all at once but can use following combination:

ALT + Enter --> Show intention actions and quick-fixes.

F2 --> Next highlighted error.

How to add a line to a multiline TextBox?

If you know how many lines you want, create an array of String with that many members (e.g. myStringArray). Then use myListBox.Lines = myStringArray;

Strange PostgreSQL "value too long for type character varying(500)"

By specifying the column as VARCHAR(500) you've set an explicit 500 character limit. You might not have done this yourself explicitly, but Django has done it for you somewhere. Telling you where is hard when you haven't shown your model, the full error text, or the query that produced the error.

If you don't want one, use an unqualified VARCHAR, or use the TEXT type.

varchar and text are limited in length only by the system limits on column size - about 1GB - and by your memory. However, adding a length-qualifier to varchar sets a smaller limit manually. All of the following are largely equivalent:

column_name VARCHAR(500)

column_name VARCHAR CHECK (length(column_name) <= 500) 

column_name TEXT CHECK (length(column_name) <= 500) 

The only differences are in how database metadata is reported and which SQLSTATE is raised when the constraint is violated.

The length constraint is not generally obeyed in prepared statement parameters, function calls, etc, as shown:

regress=> \x
Expanded display is on.
regress=> PREPARE t2(varchar(500)) AS SELECT $1;
PREPARE
regress=> EXECUTE t2( repeat('x',601) );
-[ RECORD 1 ]-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
?column? | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

and in explicit casts it result in truncation:

regress=> SELECT repeat('x',501)::varchar(1);
-[ RECORD 1 ]
repeat | x

so I think you are using a VARCHAR(500) column, and you're looking at the wrong table or wrong instance of the database.

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

Does a foreign key automatically create an index?

A foreign key is a constraint, a relationship between two tables - that has nothing to do with an index per se.

But it is a known fact that it makes a lot of sense to index all the columns that are part of any foreign key relationship, because through a FK-relationship, you'll often need to lookup a relating table and extract certain rows based on a single value or a range of values.

So it makes good sense to index any columns involved in a FK, but a FK per se is not an index.

Check out Kimberly Tripp's excellent article "When did SQL Server stop putting indexes on Foreign Key columns?".

How do I pre-populate a jQuery Datepicker textbox with today's date?

var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);

seemed to work, but there might be a better way out there..

Why are interface variables static and final by default?

(This is not a philosophical answer but more of a practical one). The requirement for static modifier is obvious which has been answered by others. Basically, since the interfaces cannot be instantiated, the only way to access its fields are to make them a class field -- static.

The reason behind the interface fields automatically becoming final (constant) is to prevent different implementations accidentally changing the value of interface variable which can inadvertently affect the behavior of the other implementations. Imagine the scenario below where an interface property did not explicitly become final by Java:

public interface Actionable {
    public static boolean isActionable = false;

    public void performAction();
}

public NuclearAction implements Actionable {

    public void performAction() {
        // Code that depends on isActionable variable
        if (isActionable) {
            // Launch nuclear weapon!!!
        }
    }
}

Now, just think what would happen if another class that implements Actionable alters the state of the interface variable:

public CleanAction implements Actionable  {

    public void performAction() {
        // Code that can alter isActionable state since it is not constant
        isActionable = true;
    }
}

If these classes are loaded within a single JVM by a classloader, then the behavior of NuclearAction can be affected by another class, CleanAction, when its performAction() is invoke after CleanAction's is executed (in the same thread or otherwise), which in this case can be disastrous (semantically that is).

Since we do not know how each implementation of an interface is going to use these variables, they must implicitly be final.

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

A few comments:

import sun.misc.*; Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.

byte[] encVal = c.doFinal(Data.getBytes()); You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8")); Defaults might be different in different places.

As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.

unique object identifier in javascript

I faced the same problem and here's the solution I implemented with ES6

code
let id = 0; // This is a kind of global variable accessible for every instance 

class Animal {
constructor(name){
this.name = name;
this.id = id++; 
}

foo(){}
 // Executes some cool stuff
}

cat = new Animal("Catty");


console.log(cat.id) // 1 

javascript: detect scroll end

This will actually be the correct answer:

function scrolled(event) {
   const container = event.target.body
   const {clientHeight, scrollHeight, scrollY: scrollTop} = container

   if (clientHeight + scrollY >= scrollHeight) {
    scrolledToBottom(event);
   }
}

The reason for using the event is up-to-date data, if you'll use a direct reference to the div you'll get outdated scrollY and will fail to detect the position correctly.

additional way is to wrap it in a setTimeout and wait till the data updates.

How to drop a unique constraint from table column?

   ALTER TABLE dbo.table
DROP CONSTRAINT uq_testConstrain

constraint name uq_testConstrain can be found under database->table->keys folder

How to call an async method from a getter or setter?

I think that we can await for the value just returning first null and then get the real value, so in the case of Pure MVVM (PCL project for instance) I think the following is the most elegant solution:

private IEnumerable myList;
public IEnumerable MyList
{
  get
    { 
      if(myList == null)
         InitializeMyList();
      return myList;
     }
  set
     {
        myList = value;
        NotifyPropertyChanged();
     }
}

private async void InitializeMyList()
{
   MyList = await AzureService.GetMyList();
}

Is it possible to refresh a single UITableViewCell in a UITableView?

I tried just calling -[UITableView cellForRowAtIndexPath:], but that didn't work. But, the following works for me for example. I alloc and release the NSArray for tight memory management.

- (void)reloadRow0Section0 {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    [indexPaths release];
}

Append a Lists Contents to another List C#

Here is my example:

    private List<int> m_machinePorts = new List<int>();

    public List<int> machinePorts
    {
        get { return m_machinePorts; }
    }

    Init()
    {
        // Custom function to get available ethernet ports
        List<int> localEnetPorts = _Globals.GetAvailableEthernetPorts();

        // Custome function to get available serial ports
        List<int> localPorts = _Globals.GetAvailableSerialPorts();

        // Build Available port list 
        m_machinePorts.AddRange(localEnetPorts);
        m_machinePorts.AddRange(localPorts);
     }

How to save a new sheet in an existing excel file, using Pandas?

#This program is to read from excel workbook to fetch only the URL domain names and write to the existing excel workbook in a different sheet..
#Developer - Nilesh K
import pandas as pd
from openpyxl import load_workbook #for writting to the existing workbook

df = pd.read_excel("urlsearch_test.xlsx")

#You can use the below for the relative path.
# r"C:\Users\xyz\Desktop\Python\

l = [] #To make a list in for loop

#begin
#loop starts here for fetching http from a string and iterate thru the entire sheet. You can have your own logic here.
for index, row in df.iterrows():
    try: 
        str = (row['TEXT']) #string to read and iterate
        y = (index)
        str_pos = str.index('http') #fetched the index position for http
        str_pos1 = str.index('/', str.index('/')+2) #fetched the second 3rd position of / starting from http
        str_op = str[str_pos:str_pos1] #Substring the domain name
        l.append(str_op) #append the list with domain names

    #Error handling to skip the error rows and continue.
    except ValueError:
            print('Error!')
print(l)
l = list(dict.fromkeys(l)) #Keep distinct values, you can comment this line to get all the values
df1 = pd.DataFrame(l,columns=['URL']) #Create dataframe using the list
#end

#Write using openpyxl so it can be written to same workbook
book = load_workbook('urlsearch_test.xlsx')
writer = pd.ExcelWriter('urlsearch_test.xlsx',engine = 'openpyxl')
writer.book = book
df1.to_excel(writer,sheet_name = 'Sheet3')
writer.save()
writer.close()

#The below can be used to write to a different workbook without using openpyxl
#df1.to_excel(r"C:\Users\xyz\Desktop\Python\urlsearch1_test.xlsx",index='false',sheet_name='sheet1')

OpenSSL: unable to verify the first certificate for Experian URL

Here is what you can do:-

Exim SSL certificates

By default, the /etc/exim.conf will use the cert/key files:

/etc/exim.cert
/etc/exim.key

so if you're wondering where to set your files, that's where.

They're controlled by the exim.conf's options:

tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key

Intermediate Certificates

If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.

Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.

Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option. So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)

AngularJS access scope from outside js function

You need to use $scope.$apply() if you want to make any changes to a scope value from outside the control of angularjs like a jquery/javascript event handler.

function change() {
    alert("a");
    var scope = angular.element($("#outer")).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    })
}

Demo: Fiddle

What's the difference between Unicode and UTF-8?

Let's start from keeping in mind that data is stored as bytes; Unicode is a character set where characters are mapped to code points (unique integers), and we need something to translate these code points data into bytes. That's where UTF-8 comes in so called encoding – simple!

Add Marker function with Google Maps API

function initialize() {
    var location = new google.maps.LatLng(44.5403, -78.5463);
    var mapCanvas = document.getElementById('map_canvas');
    var map_options = {
      center: location,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(map_canvas, map_options);

    new google.maps.Marker({
        position: location,
        map: map
    });
}
google.maps.event.addDomListener(window, 'load', initialize);

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

How to customize the configuration file of the official PostgreSQL Docker image?

When you run the official entrypoint (A.K.A. when you launch the container), it runs initdb in $PGDATA (/var/lib/postgresql/data by default), and then it stores in that directory these 2 files:

  • postgresql.conf with default manual settings.
  • postgresql.auto.conf with settings overriden automatically with ALTER SYSTEM commands.

The entrypoint also executes any /docker-entrypoint-initdb.d/*.{sh,sql} files.

All this means you can supply a shell/SQL script in that folder that configures the server for the next boot (which will be immediately after the DB initialization, or the next times you boot the container).

Example:

conf.sql file:

ALTER SYSTEM SET max_connections = 6;
ALTER SYSTEM RESET shared_buffers;

Dockerfile file:

FROM posgres:9.6-alpine
COPY *.sql /docker-entrypoint-initdb.d/
RUN chmod a+r /docker-entrypoint-initdb.d/*

And then you will have to execute conf.sql manually in already-existing databases. Since configuration is stored in the volume, it will survive rebuilds.


Another alternative is to pass -c flag as many times as you wish:

docker container run -d postgres -c max_connections=6 -c log_lock_waits=on

This way you don't need to build a new image, and you don't need to care about already-existing or not databases; all will be affected.

Include files from parent or other directory

Any path beginning with a slash will be an absolute path. From the root-folder of the server and not the root-folder of your document root. You can use ../ to go into the parent directory.

Add click event on div tag using javascript

the document class selector:

document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)

also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

document.querySelector(".drill_cursor").addEventListener('click',function(){},false)

What is the difference between x86 and x64

If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:

  • x86 is for 32-bit OS
  • x64 is for 64-bit OS

In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.

At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.

google console error `OR-IEH-01`

i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification

Make Div Draggable using CSS

Draggable div not possible only with CSS, if you want draggable div you must need to use javascript.

http://jqueryui.com/draggable/

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

Converting a column within pandas dataframe from int to string

Change data type of DataFrame column:

To int:

df.column_name = df.column_name.astype(np.int64)

To str:

df.column_name = df.column_name.astype(str)

How to play a local video with Swift?

PlayerView for swift 4.2

import AVFoundation
import UIKit

class PlayerView: UIView {

    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }

    // Override UIView property
    override static var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

How can I print each command before executing?

The easiest way to do this is to let bash do it:

set -x

Or run it explicitly as bash -x myscript.

How to display list of repositories from subversion server

Doesn't your access to SVN work just like a Web service? When I access the top directory of my SVN server, I get a page that's essentially a Table Of Contents of the whole works. It's an Unordered List that I can simply scan through.

EDIT: Here's how I would do it from the command line:

wget http://user:password@svn-url/ -O - | grep \<li\>

Change Project Namespace in Visual Studio

Assuming this is for a C# project and assuming that you want to change the default namespace, you need to go to Project Properties, Application tab, and specify "Default Namespace".

Default namespace is the namespace that Visual studio sets when you create a new class. Next time you do Right Click > Add > Class it would use the namespace you specified in the above step.

How do I increase the scrollback buffer in a running screen session?

Press Ctrl-a then : and then type

scrollback 10000

to get a 10000 line buffer, for example.

You can also set the default number of scrollback lines by adding

defscrollback 10000

to your ~/.screenrc file.

To scroll (if your terminal doesn't allow you to by default), press Ctrl-a ESC and then scroll (with the usual Ctrl-f for next page or Ctrl-a for previous page, or just with your mouse wheel / two-fingers). To exit the scrolling mode, just press ESC.

Another tip: Ctrl-a i shows your current buffer setting.

How do I print a datetime in the local timezone?

Think your should look around: datetime.astimezone()

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Also see pytz module - it's quite easy to use -- as example:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Example:

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00

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

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

Help with packages in java - import does not work

You got a bunch of good answers, so I'll just throw out a suggestion. If you are going to be working on this project for more than 2 days, download eclipse or netbeans and build your project in there.

If you are not normally a java programmer, then the help it will give you will be invaluable.

It's not worth the 1/2 hour download/install if you are only spending 2 hours on it.

Both have hotkeys/menu items to "Fix imports", with this you should never have to worry about imports again.

./configure : /bin/sh^M : bad interpreter

Just adding sh before script name make it work in my case.

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Working solution for office 365

  • save in UTF-16 (no LE, BE)
  • use separator \t

Code in PHP

$header = ['císlo', 'vytvoreno', 'ešcržýáíé'];
$fileName = 'excel365.csv';
$fp = fopen($fileName, 'w');
fputcsv($fp, $header, "\t");
fclose($fp);

$handle = fopen($fileName, "r");
$contents = fread($handle, filesize($fileName));
$contents = iconv('UTF-8', 'UTF-16', $contents);
fclose($handle);

$handle = fopen($fileName, "w");
fwrite($handle, $contents);
fclose($handle);

How to generate unique ID with node.js

edit: shortid has been deprecated. The maintainers recommend to use nanoid instead.


Another approach is using the shortid package from npm.

It is very easy to use:

var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF

and has some compelling features:

ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

  • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
  • Non-sequential so they are not predictable.
  • Can generate any number of ids without duplicates, even millions per day.
  • Apps can be restarted any number of times without any chance of repeating an id.

SmartGit Installation and Usage on Ubuntu

What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon

In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

Sending a file over TCP sockets in Python

Remove below code

s.send("Hello server!")

because your sending s.send("Hello server!") to server, so your output file is somewhat more in size.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

If you are using AngularJS you need to pass the body params as string:

    factory.getToken = function(person_username) {
    console.log('Getting DI Token');
    var url = diUrl + "/token";

    return $http({
        method: 'POST',
        url: url,
        data: 'grant_type=password&[email protected]&password=mypass',
        responseType:'json',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
};

Pandas DataFrame Groupby two columns and get counts

You are looking for size:

In [11]: df.groupby(['col5', 'col2']).size()
Out[11]:
col5  col2
1     A       1
      D       3
2     B       2
3     A       3
      C       1
4     B       1
5     B       2
6     B       1
dtype: int64

To get the same answer as waitingkuo (the "second question"), but slightly cleaner, is to groupby the level:

In [12]: df.groupby(['col5', 'col2']).size().groupby(level=1).max()
Out[12]:
col2
A       3
B       2
C       1
D       3
dtype: int64

Escape Character in SQL Server

Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.

Binding a WPF ComboBox to a custom list

I had a similar issue where the SelectedItem never got updated.

My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.

public override bool Equals(object obj)
{
    return this.Id == (obj as MyCustomObject).Id;
}

assign value using linq

Be aware that it only updates the first company it found with company id 1. For multiple

 (from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";

For Multiple updates

 from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name";  return c;}

JavaScript CSS how to add and remove multiple CSS classes to an element

Try doing this...

document.getElementById("MyElement").className += " MyClass";

Got this here...

favicon not working in IE

Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:

Is the code like this:

<link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />

Is it in the <head>?

Is the image a real ico file? (renaming a bitmap is not a real .ico! Mildly different format)

Does it work when you add the page as a bookmark?

How can I stream webcam video with C#?

You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.

Checking if an object is a number in C#

There are three different concepts there:

  • to check if it is a number (i.e. a (typically boxed) numeric value itself), check the type with is - for example if(obj is int) {...}
  • to check if a string could be parsed as a number; use TryParse()
  • but if the object isn't a number or a string, but you suspect ToString() might give something that looks like a number, then call ToString() and treat it as a string

In both the first two cases, you'll probably have to handle separately each numeric type you want to support (double/decimal/int) - each have different ranges and accuracy, for example.

You could also look at regex for a quick rough check.

SQLite UPSERT / UPDATE OR INSERT

To have a pure UPSERT with no holes (for programmers) that don't relay on unique and other keys:

UPDATE players SET user_name="gil", age=32 WHERE user_name='george'; 
SELECT changes();

SELECT changes() will return the number of updates done in the last inquire. Then check if return value from changes() is 0, if so execute:

INSERT INTO players (user_name, age) VALUES ('gil', 32); 

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

How to download Visual Studio 2017 Community Edition for offline installation?

It seems that so far you've just followed the first step of the instructions, headed "Create an offline installation folder". Have you done the second step? "Install from the offline installation folder" - that is, install the certificates and then run vs_Community.exe from inside the folder.

HTTP 404 when accessing .svc file in IIS

Verifies that you directory has been converted into an Application is your IIS.

How do you easily create empty matrices javascript?

_x000D_
_x000D_
// initializing depending on i,j:_x000D_
var M=Array.from({length:9}, (_,i) => Array.from({length:9}, (_,j) => i+'x'+j))_x000D_
_x000D_
// Print it:_x000D_
_x000D_
console.table(M)_x000D_
// M.forEach(r => console.log(r))_x000D_
document.body.innerHTML = `<pre>${M.map(r => r.join('\t')).join('\n')}</pre>`_x000D_
// JSON.stringify(M, null, 2) // bad for matrices
_x000D_
_x000D_
_x000D_

Beware that doing this below, is wrong:

// var M=Array(9).fill([]) // since arrays are sparse
// or Array(9).fill(Array(9).fill(0))// initialization

// M[4][4] = 1
// M[3][4] is now 1 too!

Because it creates the same reference of Array 9 times, so modifying an item modifies also items at the same index of other rows (since it's the same reference), so you need an additional call to .slice or .map on the rows to copy them (cf torazaburo's answer which fell in this trap)

note: It may look like this in the future, with slice-notation-literal proposal (stage 1)

const M = [...1:10].map(i => [...1:10].map(j => i+'x'+j))

Error in setting JAVA_HOME

The JAVA_HOME should point to the JDK home rather than the JRE home if you are going to be compiling stuff, likewise - I would try and install the JDK in a directory that doesn't include a space. Even if this is not your problem now, it can cause problems in the future!

How to recover Git objects damaged by hard disk failure?

The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.

So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository

I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:

"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."

You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:

"git reflog expire --expire=now --all && git gc --prune=now --aggressive"

When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:

"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"

Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".

What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)

I hope this saves someone's time

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).

==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.

I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!

Hope this helps to make things even clearer!

enter image description here

"Register" an .exe so you can run it from any command line in Windows

It is very simple and it won't take more than 30 seconds.

For example the software called abc located in D:/Softwares/vlc/abc.exe Add the folder path of abc.exe to system environment variables.

My Computer -> Click Properties -> Click Advanced system settings -> Click Environment Variables

enter image description here

enter image description here

Click on Ok.

now you can just open cmd prompt and you can launch the software from anywhere. to use abc.exe just type abc in the command line.

Codeigniter LIKE with wildcard(%)

$this->db->like() automatically adds the %s and escapes the string. So all you need is

$this->db->like('title', $query);
$res = $this->db->get('film');

See the CI documentation for reference: CI 2, CI 3, CI 4

milliseconds to days

In case you solve a more complex task of logging execution statistics in your code:

public void logExecutionMillis(LocalDateTime start, String callerMethodName) {

  LocalDateTime end = getNow();
  long difference = Duration.between(start, end).toMillis();

  Logger logger = LoggerFactory.getLogger(ProfilerInterceptor.class);

  long millisInDay = 1000 * 60 * 60 * 24;
  long millisInHour = 1000 * 60 * 60;
  long millisInMinute = 1000 * 60;
  long millisInSecond = 1000;

  long days = difference / millisInDay;
  long daysDivisionResidueMillis = difference - days * millisInDay;

  long hours = daysDivisionResidueMillis / millisInHour;
  long hoursDivisionResidueMillis = daysDivisionResidueMillis - hours * millisInHour;

  long minutes = hoursDivisionResidueMillis / millisInMinute;
  long minutesDivisionResidueMillis = hoursDivisionResidueMillis - minutes * millisInMinute;

  long seconds = minutesDivisionResidueMillis / millisInSecond;
  long secondsDivisionResidueMillis = minutesDivisionResidueMillis - seconds * millisInSecond;

  logger.info(
      "\n************************************************************************\n"
          + callerMethodName
          + "() - "
          + difference
          + " millis ("
          + days
          + " d. "
          + hours
          + " h. "
          + minutes
          + " min. "
          + seconds
          + " sec."
          + secondsDivisionResidueMillis
          + " millis).");
}

P.S. Logger can be replaced with simple System.out.println() if you like.

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

ANTLR: Is there a simple example?

At https://github.com/BITPlan/com.bitplan.antlr you'll find an ANTLR java library with some useful helper classes and a few complete examples. It's ready to be used with maven and if you like eclipse and maven.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/exp/Exp.g4

is a simple Expression language that can do multiply and add operations. https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestExpParser.java has the corresponding unit tests for it.

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/main/antlr4/com/bitplan/iri/IRIParser.g4 is an IRI parser that has been split into the three parts:

  1. parser grammar
  2. lexer grammar
  3. imported LexBasic grammar

https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIRIParser.java has the unit tests for it.

Personally I found this the most tricky part to get right. See http://wiki.bitplan.com/index.php/ANTLR_maven_plugin

https://github.com/BITPlan/com.bitplan.antlr/tree/master/src/main/antlr4/com/bitplan/expr

contains three more examples that have been created for a performance issue of ANTLR4 in an earlier version. In the meantime this issues has been fixed as the testcase https://github.com/BITPlan/com.bitplan.antlr/blob/master/src/test/java/com/bitplan/antlr/TestIssue994.java shows.

How to get a random number in Ruby

Well, I figured it out. Apparently there is a builtin (?) function called rand:

rand(n + 1)

If someone answers with a more detailed answer, I'll mark that as the correct answer.

git rebase merge conflict

Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)

git mergetool

Then add your changes and go on

git rebase --continue

Good luck

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

If you are getting this same error after adding dynamic module then don't worry follow this:

  • Add productFlavors in your build.gradle(dynamic- module)

    productFlavors {
    flavorDimensions "default"
    stage {
       // to do
    }
    prod {
       // to do
    
     }
    }
    

Loading a .json file into c# program

Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class RootObject
{
    public string url_short { get; set; }
    public string url_long { get; set; }
    public int type { get; set; }
}

public class Program
{
    static public void Main()
    {
       using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
       {
           string json = r.ReadToEnd();
           List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
       }

    Console.WriteLine(ro[0].url_short);                 
    }  
}

Note : Look below link also I have answered for question similar to this.It will be help full for you How to Parse an example string in C#

How to remove specific substrings from a set of strings in Python?

if you delete something from list , u can use this way : (method sub is case sensitive)

new_list = []
old_list= ["ABCDEFG","HKLMNOP","QRSTUV"]

for data in old_list:
     new_list.append(re.sub("AB|M|TV", " ", data))

print(new_list) // output : [' CDEFG', 'HKL NOP', 'QRSTUV']

jQuery UI Dialog individual CSS styling

You can add the class to the title like this:

$('#dialog_style1').siblings('div.ui-dialog-titlebar').addClass('dialog1');

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Getting each individual digit from a whole integer

Don't reinvent the wheel. C has sprintf for a reason. Since your variable is called score, I'm guessing this is for a game where you're planning to use the individual digits of the score to display the numeral glyphs as images. In this case, sprintf has convenient format modifiers that will let you zero-pad, space-pad, etc. the score to a fixed width, which you may want to use.

iPad/iPhone hover problem causes the user to double click a link

It is not entirely clear what your question is, but if you just want to eliminate the double click, while retaining the hover effect for the mouse, my advice is to:

  • Add hover effects on touchstart and mouseenter.
  • Remove hover effects on mouseleave, touchmove and click.

Background

In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):

  1. touchstart
  2. touchmove
  3. touchend
  4. 300ms delay, where the browser makes sure this is a single tap, not a double tap
  5. mouseover
  6. mouseenter
    • Note: If a mouseover, mouseenter or mousemove event changes the page content, the following events are never fired.
  7. mousemove
  8. mousedown
  9. mouseup
  10. click

It does not seem possible to simply tell the webbrowser to skip the mouse events.

What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.

Solution Explained

To recap:

  • Add hover effects on touchstart and mouseenter.
  • Remove hover effects on mouseleave, touchmove and click.

Note that there is no action on touchend!

This clearly works for mouse events: mouseenter and mouseleave (slightly improved versions of mouseover and mouseout) are fired, and add and remove the hover.

If the user actually clicks a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.

This also works for touch events: on touchstart the hover effect is added. It is '''not''' removed on touchend. It is added again on mouseenter, and since this causes no content changes (it was already added), the click event is also fired, and the link is followed without the need for the user to click again!

The 300ms delay that a browser has between a touchstart event and click is actually put in good use because the hover effect will be shown during this short time.

If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove.

That's it!

Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.

Alternative Solutions

I've found the following problems with the following alternatives:

  • browser detection: Extremely prone to errors. Assumes that a device has either mouse or touch, while a combination of both will become more and more common when touch displays prolifirate.
  • CSS media detection: The only CSS-only solution I'm aware of. Still prone to errors, and still assumes that a device has either mouse or touch, while both are possible.
  • Emulate the click event in touchend: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.
  • Use a variable to suppress mouse events: This set a variable in touchend that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).

Further Reading

See also iPad/iPhone double click problem and Disable hover effects on mobile browsers.

Timeout a command in bash without unnecessary delay

In 99% of the cases the answer is NOT to implement any timeout logic. Timeout logic is in nearly any situation a red warning sign that something else is wrong and should be fixed instead.

Is your process hanging or breaking after n seconds sometimes? Then find out why and fix that instead.

As an aside, to do strager's solution right, you need to use wait "$SPID" instead of fg 1, since in scripts you don't have job control (and trying to turn it on is stupid). Moreover, fg 1 relies on the fact that you didn't start any other jobs previously in the script which is a bad assumption to make.

What is the id( ) function used for?

The is operator uses it to check whether two objects are identical (as opposed to equal). The actual value that is returned from id() is pretty much never used for anything because it doesn't really have a meaning, and it's platform-dependent.

nodeJs callbacks simple example

var myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};

Now open node or browser console and paste the above definitions.

Finally use it with this next line:

usingItNow(myCallback);

With Respect to the Node-Style Error Conventions

Costa asked what this would look like if we were to honor the node error callback conventions.

In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.

Here I rewrite our example in this convention.

var myCallback = function(err, data) {
  if (err) throw err; // Check for the error and throw if it exists.
  console.log('got data: '+data); // Otherwise proceed as usual.
};

var usingItNow = function(callback) {
  callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};

If we want to simulate an error case, we can define usingItNow like this

var usingItNow = function(callback) {
  var myError = new Error('My custom error!');
  callback(myError, 'get it?'); // I send my error as the first argument.
};

The final usage is exactly the same as in above:

usingItNow(myCallback);

The only difference in behavior would be contingent on which version of usingItNow you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.

Finding the position of the max element

You can use max_element() function to find the position of the max element.

int main()
{
    int num, arr[10];
    int x, y, a, b;

    cin >> num;

    for (int i = 0; i < num; i++)
    {
        cin >> arr[i];
    }

    cout << "Max element Index: " << max_element(arr, arr + num) - arr;

    return 0;
}

sqlite3.OperationalError: unable to open database file

You haven't specified the absolute path - you've used a shortcut , ~, which might not work in this context. Use /home/yourusername/Harold-Server/OmniCloud.db instead.

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java does not support multiple inheritance , multipath and hybrid inheritance because of ambiguity problem:

 Scenario for multiple inheritance: Let us take class A , class B , class C. class A has alphabet(); method , class B has also alphabet(); method. Now class C extends A, B and we are creating object to the subclass i.e., class C , so  C ob = new C(); Then if you want call those methods ob.alphabet(); which class method takes ? is class A method or class B method ?  So in the JVM level ambiguity problem occurred. Thus Java does not support multiple inheritance.

multiple inheritance

Reference Link: https://plus.google.com/u/0/communities/102217496457095083679

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

MySQL JDBC Driver 5.1.33 - Time Zone Issue

This is a bug in mysql-connector-java from version 5.1.33 to 5.1.37. I've reported it here: http://bugs.mysql.com/bug.php?id=79343

Edited: This has been corrected from mysql-connector-java 5.1.39

It was a typo in TimeUtil class in loadTimeZoneMappings method that raises a NPE locating /com/mysql/jdbc/TimeZoneMapping.properties file. If you look at the code, the file should be located within TimeUtil class loader, not TimeZone:

TimeUtil.class.getResourceAsStream(TIME_ZONE_MAPPINGS_RESOURCE);

The parameter useLegacyDatetimeCode allows to correct the difference between client and server timezones automatically when using dates. So it helps you precissely not having to specify timezones in each part. Althought using serverTimeZone parameter is a workaround, and meanwhile the patch is released, you can try better correcting the code by yourself as I did.

  • If it's a standalone application, you can try simply to add a corrected com/mysql/jdbc/TimeUtil class to your code and be careful with jar loading order. This can help: https://owenou.com/2010/07/20/patching-with-class-shadowing-and-maven.html

  • If it's a web application, the easier solution is to create your own mysql-connector-java-5.1.37-patched.jar, substituting the .class directly into the original jar.

Empty responseText from XMLHttpRequest

This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.

In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.

Now sure why it worked, but it did.

JSON string to JS object

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

Java: convert seconds to minutes, hours and days

It should be like:

    public static void calculateTime(long seconds) {
            int day = (int)TimeUnit.SECONDS.toDays(seconds);        
            long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);

            System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);

        }

Explanation:

TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours with out consideration for days. Minus the hours for days you already got i.e, day*24. You now got remaining hours. Same for minute and second. You need to minus the already got hour and minutes respectively.

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I agree with above answer. But here is another way of CSS compression.

You can concat your CSS by using YUI compressor:

module.exports = function(grunt) {
  var exec = require('child_process').exec;
   grunt.registerTask('cssmin', function() {
    var cmd = 'java -jar -Xss2048k '
      + __dirname + '/../yuicompressor-2.4.7.jar --type css '
      + grunt.template.process('/css/style.css') + ' -o '
      + grunt.template.process('/css/style.min.css')
    exec(cmd, function(err, stdout, stderr) {
      if(err) throw err;
    });
  });
}; 

React-Router External link

Using some of the info here, I came up with the following component which you can use within your route declarations. It's compatible with React Router v4.

It's using typescript, but should be fairly straight-forward to convert to native javascript:

interface Props {
  exact?: boolean;
  link: string;
  path: string;
  sensitive?: boolean;
  strict?: boolean;
}

const ExternalRedirect: React.FC<Props> = (props: Props) => {
  const { link, ...routeProps } = props;

  return (
    <Route
      {...routeProps}
      render={() => {
        window.location.replace(props.link);
        return null;
      }}
    />
  );
};

And use with:

<ExternalRedirect
  exact={true}
  path={'/privacy-policy'}
  link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

Java generics - why is "extends T" allowed but not "implements T"?

Here is a more involved example of where extends is allowed and possibly what you want:

public class A<T1 extends Comparable<T1>>

Why does "pip install" inside Python raise a SyntaxError?

pip is run from the command line, not the Python interpreter. It is a program that installs modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do import selenium.

The Python shell is not a command line, it is an interactive interpreter. You type Python code into it, not commands.

What is logits, softmax and softmax_cross_entropy_with_logits?

Tensorflow 2.0 Compatible Answer: The explanations of dga and stackoverflowuser2010 are very detailed about Logits and the related Functions.

All those functions, when used in Tensorflow 1.x will work fine, but if you migrate your code from 1.x (1.14, 1.15, etc) to 2.x (2.0, 2.1, etc..), using those functions result in error.

Hence, specifying the 2.0 Compatible Calls for all the functions, we discussed above, if we migrate from 1.x to 2.x, for the benefit of the community.

Functions in 1.x:

  1. tf.nn.softmax
  2. tf.nn.softmax_cross_entropy_with_logits
  3. tf.nn.sparse_softmax_cross_entropy_with_logits

Respective Functions when Migrated from 1.x to 2.x:

  1. tf.compat.v2.nn.softmax
  2. tf.compat.v2.nn.softmax_cross_entropy_with_logits
  3. tf.compat.v2.nn.sparse_softmax_cross_entropy_with_logits

For more information about migration from 1.x to 2.x, please refer this Migration Guide.

Select all 'tr' except the first one

By adding a class to either the first tr or the subsequent trs. There is no crossbrowser way of selecting the rows you want with CSS alone.

However, if you don't care about Internet Explorer 6, 7 or 8:

tr:not(:first-child) {
    color: red;
}

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Netbeans needs to be able to index the maven repository. Allow it to do that and try again. It was giving me the same error and after it indexed the repository it ran like a charm

How do HashTables deal with collisions?

It will use the equals method to see if the key is present even and especially if there are more than one element in the same bucket.

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

How to access a property of an object (stdClass Object) member/element of an array?

How about something like this.

function objectToArray( $object ){
   if( !is_object( $object ) && !is_array( $object ) ){
    return $object;
 }
if( is_object( $object ) ){
    $object = get_object_vars( $object );
}
    return array_map( 'objectToArray', $object );
}

and call this function with your object

$array = objectToArray( $yourObject );

reference

mysql after insert trigger which updates another table's column

Try this:

DELIMITER $$
CREATE TRIGGER occupy_trig
AFTER INSERT ON `OccupiedRoom` FOR EACH ROW
begin
       DECLARE id_exists Boolean;
       -- Check BookingRequest table
       SELECT 1
       INTO @id_exists
       FROM BookingRequest
       WHERE BookingRequest.idRequest= NEW.idRequest;

       IF @id_exists = 1
       THEN
           UPDATE BookingRequest
           SET status = '1'
           WHERE idRequest = NEW.idRequest;
        END IF;
END;
$$
DELIMITER ;

Change bullets color of an HTML list without using span

For me the best option is to use CSS pseudo elements, so for disc bullet styling it would look like that:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li:before {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  width: 5px; /* adjust to suit your needs */_x000D_
  height: 5px; /* adjust to suit your needs */_x000D_
  border-radius: 50%;_x000D_
  left: -15px; /* adjust to suit your needs */_x000D_
  top: 0.5em;_x000D_
  background: #f00; /* adjust to suit your needs */_x000D_
}
_x000D_
<ul>_x000D_
  <li>first</li>_x000D_
  <li>second</li>_x000D_
  <li>third</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Notes:

  • width and height should have equal values to keep pointers rounded
  • you may set border-radius to zero if you want to have square list bullets

For more bullets styles you may use other css shapes https://css-tricks.com/examples/ShapesOfCSS/ (choose this which doesn't require pseudo elements to work, so for example triangles)

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

JasperReports: http://jasperforge.org.

openreports: http://oreports.com/ For hosting jasper files.

Not specifically a reporting tool but displaytag is a simple java tag that will emit, csv, xls and pdf.

http://displaytag.sourceforge.net/1.2/

HTML embed autoplay="false", but still plays automatically

None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed or object elements in HTML5. For video or audio elements they did stop autoplay. For embed and object they did not.

I tested this using the embed and object elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video or audio elements, just when using embed and object.

It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.

To do this in Firefox I have posted the settings below:

  1. Open up your Firefox Browser, click the menu button, and select "Options"
  2. Select the "Privacy & Security" panel and scroll down to the "Permissions" section
  3. Find "Autoplay" and click the "Settings" button. In the dropdown change it to block audio and video. The default is just audio.

Your videos will NOT autoplay now when displaying videos in web pages using object or embed elements.

How get all values in a column using PHP?

Here is a simple way to do this using either PDO or mysqli

$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);

or, using mysqli

$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
    $array[] = $row['column'];
}
print_r($array);

Array
(
    [0] => 7960
    [1] => 7972
    [2] => 8028
    [3] => 8082
    [4] => 8233
)

Eclipse CDT: Symbol 'cout' could not be resolved

Just adding yet another bit of advice after trying a bunch of stuff myself and it not working....

I had GCC installed and the path to the includes set correctly. Had the std error as well, and couldn't get anything working for cout (and I suspect anything in the SL...)

Took me awhile to realize that g++ wasn't installed - gcc was but not g++. So just do:

sudo apt-get install g++

Restart eclipse. Assuming above mentioned details about gcc & paths to includes are fine, you should be okay now...

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

But if i take the piece of sql and run it from sql management studio, it will run without issue.

If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.

The real crux of the issue is:

I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")

Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.

jQuery equivalent of JavaScript's addEventListener method

Not all browsers support event capturing (for example, Internet Explorer versions less than 9 don't) but all do support event bubbling, which is why it is the phase used to bind handlers to events in all cross-browser abstractions, jQuery's included.

The nearest to what you are looking for in jQuery is using bind() (superseded by on() in jQuery 1.7+) or the event-specific jQuery methods (in this case, click(), which calls bind() internally anyway). All use the bubbling phase of a raised event.

How to calculate time elapsed in bash script?

I needed a time difference script for use with mencoder (its --endpos is relative), and my solution is to call a Python script:

$ ./timediff.py 1:10:15 2:12:44
1:02:29

fractions of seconds are also supported:

$ echo "diff is `./timediff.py 10:51.6 12:44` (in hh:mm:ss format)"
diff is 0:01:52.4 (in hh:mm:ss format)

and it can tell you that the difference between 200 and 120 is 1h 20m:

$ ./timediff.py 120:0 200:0
1:20:0

and can convert any (probably fractional) number of seconds or minutes or hours to hh:mm:ss

$ ./timediff.py 0 3600
1:00:0
$ ./timediff.py 0 3.25:0:0
3:15:0

timediff.py:

#!/usr/bin/python

import sys

def x60(h,m):
    return 60*float(h)+float(m)

def seconds(time):
    try:
       h,m,s = time.split(':')
       return x60(x60(h,m),s)
    except ValueError:
       try:
          m,s = time.split(':')
          return x60(m,s)
       except ValueError:
          return float(time)

def difftime(start, end):
    d = seconds(end) - seconds(start)
    print '%d:%02d:%s' % (d/3600,d/60%60,('%02f' % (d%60)).rstrip('0').rstrip('.'))

if __name__ == "__main__":
   difftime(sys.argv[1],sys.argv[2])

Failed to find Build Tools revision 23.0.1

I faced the same problem and I solved it doing the following:

Go to /home/[USER]/Android/Sdk/tools and execute:

$android list sdk -a

Which will show a list like:

  1. Android SDK Tools, revision 24.0.2
  2. Android SDK Platform-tools, revision 23.0.2
  3. Android SDK Platform-tools, revision 23.0.1

... and many more

Then, execute the command (attention! at your computer the third option may be different):

$android update sdk -a -u -t 3

It will install the 23.0.1 SDK Platform-tools components.

Try to build your project again.

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

Here is an example using css3:

CSS:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}
.footer {
    position: relative;
    clear:both;
}

HTML:

<div id="wrap">
    body content....
</div>
<footer class="footer">
    footer content....
</footer>

jsfiddle

Update
As @Martin pointed, the ´position: relative´ is not mandatory on the .footer element, the same for clear:both. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}

Also, there is an excellent article at css-tricks showing different ways to do this: https://css-tricks.com/couple-takes-sticky-footer/

Interface type check with Typescript

You can achieve what you want without the instanceof keyword as you can write custom type guards now:

interface A{
    member:string;
}

function instanceOfA(object: any): object is A {
    return 'member' in object;
}

var a:any={member:"foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}

Lots of Members

If you need to check a lot of members to determine whether an object matches your type, you could instead add a discriminator. The below is the most basic example, and requires you to manage your own discriminators... you'd need to get deeper into the patterns to ensure you avoid duplicate discriminators.

interface A{
    discriminator: 'I-AM-A';
    member:string;
}

function instanceOfA(object: any): object is A {
    return object.discriminator === 'I-AM-A';
}

var a:any = {discriminator: 'I-AM-A', member:"foobar"};

if (instanceOfA(a)) {
    alert(a.member);
}