Programs & Examples On #Browscap

Unable to convert MySQL date/time value to System.DateTime

if "allow zero datetime=true" is not working then use the following sollutions:-

Add this to your connection string: "allow zero datetime=no" - that made the type cast work perfectly.

Python 3 - Encode/Decode vs Bytes/Str

Neither is better than the other, they do exactly the same thing. However, using .encode() and .decode() is the more common way to do it. It is also compatible with Python 2.

Check Postgres access for a user

You could query the table_privileges table in the information schema:

SELECT table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee = 'MY_USER'

Mongoose query where value is not null

You should be able to do this like (as you're using the query api):

Entrant.where("pincode").ne(null)

... which will result in a mongo query resembling:

entrants.find({ pincode: { $ne: null } })

A few links that might help:

Composer killed while updating

Fix for AWS ec2 Ubuntu Server Php Memory Value Upgrade For Magento 2.3.X

  • Php 7.2 / 7.3
  • nginx
  • ubuntu
  • composer 1.X
  • mariaDB
  • magento 2.3.X

Error : Updating dependencies (including require-dev) Killed for

  1. Ram Must at least 4GB
  2. Change instance type to suitable or Upgrade Ram
  3. Php Memory Value change
  4. Server Restart
  5. Try to install the same package again

PHP value update may locate under '/etc/php/7.2/fpm/php.ini' depend on your server and PHP fpm X.XX version

Using Seed command 'change as your server requires' on my case >> /etc/php/7.2/fpm/php.ini

memory limit type as "3.5G" or "3500MB" Php 7.2.X

sudo sed -i "s/memory_limit = .*/memory_limit = 3.5G/" /etc/php/7.2/fpm/php.ini
  

Php 7.3.X

  sudo sed -i "s/memory_limit = .*/memory_limit = 3.5G/" /etc/php/7.3/fpm/php.ini

Test if applied on 'free -h' command

    free -h

Install-Package Again#

Install extension via Composer

go to your Magento 2 installation directory

cd /var/www/html/

with 'superuser' privileges

sudo su

Start installation

composer require XXXXXX/XXXXXXX

Enable Module s

php bin/magento module:enable XXXXXX/XXXXXXX


php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
Restart
sudo reboot

Enjioy

continuing execution after an exception is thrown in java

Try this:

try
{
    throw new InvalidEmployeeTypeException();
    input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
      //do error handling
}

continue;

using jQuery .animate to animate a div from right to left?

so the .animate method works only if you have given a position attribute to an element, if not it didn't move?

for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;

How can I close a browser window without receiving the "Do you want to close this window" prompt?

My friend... there is a way but "hack" does not begin to describe it. You have to basically exploit a bug in IE 6 & 7.

Works every time!

Instead of calling window.close(), redirect to another page.

Opening Page:

alert("No whammies!");
window.open("closer.htm", '_self');

Redirect to another page. This fools IE into letting you close the browser on this page.

Closing Page:

<script type="text/javascript">
    window.close();
</script>

Awesome huh?!

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

Bootstrap modal: close current, open new

Just copy and paste this code and you can experiment with two modals. Second modal is open after closing the first one:

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
</button>

<!-- The Modal -->
<div class="modal" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Modal Heading</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                Modal body..
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>

        </div>
    </div>
</div>



<!-- The Modal 2 -->
<div class="modal" id="myModal2">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Second modal</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                Modal body..
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>

        </div>
    </div>
</div>




<script>
    $('#myModal').on('hidden.bs.modal', function () {
        $('#myModal2').modal('show')
    })
</script>

Cheers!

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

After looking in question, you should not use 404 why?

Based on RFC 7231 the correct status code is 204

In the anwsers above I noticed 1 small missunderstanding:

1.- the resource is: /users

2.- /users/8 is not the resource, this is: the resource /users with route parameter 8, consumer maybe cannot notice it and does not know the difference, but publisher does and must know this!... so he must return an accurate response for consumers. period.

so:

Based on the RFC: 404 is incorrect because the resources /users is found, but the logic executed using the parameter 8 did not found any content to return as a response, so the correct answer is: 204

The main point here is: 404 not even the resource was found to process the internal logic

204 is a: I found the resource, the logic was executed but I did not found any data using your criteria given in the route parameter so I cant return anything to you. Im sorry, verify your criteria and call me again.

200: ok i found the resource, the logic was executed (even when Im not forced to return anything) take this and use it at your will.

205: (the best option of a GET response) I found the resource, the logic was executed, I have some content for you, use it well, oh by the way if your are going to share this in a view please refresh the view to display it.

Hope it helps.

Delete all the records

To delete all records from a table without deleting the table.

DELETE FROM table_name use with care, there is no undo!

To remove a table

DROP TABLE table_name

How to Customize the time format for Python logging?

To add to the other answers, here are the variable list from Python Documentation.

Directive   Meaning Notes

%a  Locale’s abbreviated weekday name.   
%A  Locale’s full weekday name.  
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.    
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].  
%p  Locale’s equivalent of either AM or PM. (1)
%S  Second as a decimal number [00,61]. (2)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z  Time zone name (no characters if no time zone exists).   
%%  A literal '%' character.     

SQL Server: How to check if CLR is enabled?

SELECT * FROM sys.configurations
WHERE name = 'clr enabled'

How do I crop an image in Java?

I'm giving this example because this actually work for my use case.

I was trying to use the AWS Rekognition API. The API returns a BoundingBox object:

BoundingBox boundingBox = faceDetail.getBoundingBox();

The code below uses it to crop the image:

import com.amazonaws.services.rekognition.model.BoundingBox;

private BufferedImage cropImage(BufferedImage image, BoundingBox box) {
        Rectangle goal = new Rectangle(Math.round(box.getLeft()* image.getWidth()),Math.round(box.getTop()* image.getHeight()),Math.round(box.getWidth() * image.getWidth()), Math.round(box.getHeight() * image.getHeight()));

        Rectangle clip = goal.intersection(new Rectangle(image.getWidth(), image.getHeight()));

        BufferedImage clippedImg = image.getSubimage(clip.x, clip.y , clip.width, clip.height);

        return clippedImg;
    }

How to save a list as numpy array in python?

you mean something like this ?

from numpy  import array
a = array( your_list )

How to implement a secure REST API with node.js

I've had the same problem you describe. The web site I'm building can be accessed from a mobile phone and from the browser so I need an api to allow users to signup, login and do some specific tasks. Furthermore, I need to support scalability, the same code running on different processes/machines.

Because users can CREATE resources (aka POST/PUT actions) you need to secure your api. You can use oauth or you can build your own solution but keep in mind that all the solutions can be broken if the password it's really easy to discover. The basic idea is to authenticate users using the username, password and a token, aka the apitoken. This apitoken can be generated using node-uuid and the password can be hashed using pbkdf2

Then, you need to save the session somewhere. If you save it in memory in a plain object, if you kill the server and reboot it again the session will be destroyed. Also, this is not scalable. If you use haproxy to load balance between machines or if you simply use workers, this session state will be stored in a single process so if the same user is redirected to another process/machine it will need to authenticate again. Therefore you need to store the session in a common place. This is typically done using redis.

When the user is authenticated (username+password+apitoken) generate another token for the session, aka accesstoken. Again, with node-uuid. Send to the user the accesstoken and the userid. The userid (key) and the accesstoken (value) are stored in redis with and expire time, e.g. 1h.

Now, every time the user does any operation using the rest api it will need to send the userid and the accesstoken.

If you allow the users to signup using the rest api, you'll need to create an admin account with an admin apitoken and store them in the mobile app (encrypt username+password+apitoken) because new users won't have an apitoken when they sign up.

The web also uses this api but you don't need to use apitokens. You can use express with a redis store or use the same technique described above but bypassing the apitoken check and returning to the user the userid+accesstoken in a cookie.

If you have private areas compare the username with the allowed users when they authenticate. You can also apply roles to the users.

Summary:

sequence diagram

An alternative without apitoken would be to use HTTPS and to send the username and password in the Authorization header and cache the username in redis.

Reading DataSet

TL;DR: - grab the datatable from the dataset and read from the rows property.

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn("Id", typeof(int));
            dt.Columns.Add(col);
            dt.Rows.Add(new object[] { 1 });
            ds.Tables.Add(dt);

            var row = ds.Tables[0].Rows[0];
            //access the ID column.  
            var id = (int) row.ItemArray[0];

A DataSet is a copy of data accessed from a database, but doesn't even require a database to use at all. It is preferred, though.

Note that if you are creating a new application, consider using an ORM, such as the Entity Framework or NHibernate, since DataSets are no longer preferred; however, they are still supported and as far as I can tell, are not going away any time soon.

If you are reading from standard dataset, then @KMC's answer is what you're looking for. The proper way to do this, though, is to create a Strongly-Typed DataSet and use that so you can take advantage of Intellisense. Assuming you are not using the Entity Framework, proceed.

If you don't already have a dedicated space for your data access layer, such as a project or an App_Data folder, I suggest you create one now. Otherwise, proceed as follows under your data project folder: Add > Add New Item > DataSet. The file created will have an .xsd extension.

You'll then need to create a DataTable. Create a DataTable (click on the file, then right click on the design window - the file has an .xsd extension - and click Add > DataTable). Create some columns (Right click on the datatable you just created > Add > Column). Finally, you'll need a table adapter to access the data. You'll need to setup a connection to your database to access data referenced in the dataset.

After you are done, after successfully referencing the DataSet in your project (using statement), you can access the DataSet with intellisense. This makes it so much easier than untyped datasets.

When possible, use Strongly-Typed DataSets instead of untyped ones. Although it is more work to create, it ends up saving you lots of time later with intellisense. You could do something like:

MyStronglyTypedDataSet trainDataSet = new MyStronglyTypedDataSet();
DataAdapterForThisDataSet dataAdapter = new DataAdapterForThisDataSet();
//code to fill the dataset 
//omitted - you'll have to either use the wizard to create data fill/retrieval
//methods or you'll use your own custom classes to fill the dataset.
if(trainDataSet.NextTrainDepartureTime > CurrentTime){
   trainDataSet.QueueNextTrain = true; //assumes QueueNextTrain is in your Strongly-Typed dataset
}
else
    //do some other work

The above example assumes that your Strongly-Typed DataSet has a column of type DateTime named NextTrainDepartureTime. Hope that helps!

What does "collect2: error: ld returned 1 exit status" mean?

Include: #include<stdlib.h>

and use System("cls") instead of clrscr()

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

how to insert date and time in oracle?

You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a

alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'

or something similar including a time component, you will see that the time successfully made it into the database.

How to add a char/int to an char array in C?

Suggest replacing this:

char str[1024];
char tmp = '.';

strcat(str, tmp);

with this:

char str[1024] = {'\0'}; // set array to initial all NUL bytes
char tmp[] = "."; // create a string for the call to strcat()

strcat(str, tmp); // 

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Sending Email in Android using JavaMail API without using the default/built-in app

In order to help those getting a Network On Main Thread Exception with an SDK Target >9. This is using droopie's code above but will work similarly for any.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

android.os.NetworkOnMainThreadException

You can use AsyncTask as below

public void onClickMail(View view) {
    new SendEmailAsyncTask().execute();
}

class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
    Mail m = new Mail("[email protected]", "my password");

    public SendEmailAsyncTask() {
        if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
        String[] toArr = { "to [email protected]"};
        m.setTo(toArr);
        m.setFrom("from [email protected]");
        m.setSubject("Email from Android");
        m.setBody("body.");
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
        try {
            m.send();
            return true;
        } catch (AuthenticationFailedException e) {
            Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null) + "failed");
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

Force Internet Explorer to use a specific Java Runtime Environment install?

As has been mentioned here for JRE6 and JRE5, I will update for JRE1.4:

You will need to run the jpicpl32.exe application in the jre/bin directory of your java installation (e.g. c:\java\jdk1.4.2_07\jre\bin\jpicpl32.exe).

This is an earlier version of the application mentioned in Daniel Cassidy's post.

How to count the NaN values in a column in pandas DataFrame

df.isnull().sum() will give the column-wise sum of missing values.

If you want to know the sum of missing values in a particular column then following code will work: df.column.isnull().sum()

Abstraction vs Encapsulation in Java

In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.

Using floats with sprintf() in embedded C

Yes of course, there is nothing special with floats. You can use the format strings as you use in printf() for floats and anyother datatypes.

EDIT I tried this sample code:

float x = 0.61;
char buf[10];
sprintf(buf, "Test=%.2f", x);
printf(buf);

Output was : Test=0.61

NHibernate.MappingException: No persister for: XYZ

My issue was that I forgot to put the .hbm in the name of the mapping xml. Also make sure you make it an embedded resource!

How do I convert NSMutableArray to NSArray?

i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it so here is the swift 3 code

let array: [String] = nsMutableArrayObject.copy() as! [String]

Regex to remove letters, symbols except numbers

You can use \D which means non digits.

var removedText = self.val().replace(/\D+/g, '');

jsFiddle.

You could also use the HTML5 number input.

<input type="number" name="digit" />

jsFiddle.

Fragment Inside Fragment

That may help those who works on Kotlin you can use extension function so create a kotlin file let's say "util.kt" and add this piece of code

fun Fragment.addChildFragment(fragment: Fragment, frameId: Int) {

    val transaction = childFragmentManager.beginTransaction()
    transaction.replace(frameId, fragment).commit()
}

Let's say this is the class of the child

class InputFieldPresentation: Fragment()
{
    var views: View? = null
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        views = inflater!!.inflate(R.layout.input_field_frag, container, false)
        return views
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ...
    }
    ...
}

Now you can add the children to the father fragment like this

 FatherPresentation:Fragment()
{
  ...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fieldFragment= InputFieldPresentation()
        addChildFragment(fieldFragment,R.id.fragmet_field)
    }
...
}

where R.id.fragmet_field is the id of the layout which will contain the fragment.This lyout is inside the father fragment of course. Here is an example

father_fragment.xml:

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    ...

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/fragmet_field"
            android:orientation="vertical"
            >
        </LinearLayout>
    ...

    </LinearLayout>

How do you calculate log base 2 in Java for integers?

If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.

I usually try to avoid FP calculations whenever possible.

Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2)) evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2)) is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2)) fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.

The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10) should never fail. The choice of this "epsilon" is not a trivial task.

More demonstration, using a more general task - trying to implement int log(int x, int base):

The testing code:

static int pow(int base, int power) {
    int result = 1;
    for (int i = 0; i < power; i++)
        result *= base;
    return result;
}

private static void test(int base, int pow) {
    int x = pow(base, pow);
    if (pow != log(x, base))
        System.out.println(String.format("error at %d^%d", base, pow));
    if(pow!=0 && (pow-1) != log(x-1, base))
        System.out.println(String.format("error at %d^%d-1", base, pow));
}

public static void main(String[] args) {
    for (int base = 2; base < 500; base++) {
        int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
        for (int pow = 0; pow <= maxPow; pow++) {
            test(base, pow);
        }
    }
}

If we use the most straight-forward implementation of logarithm,

static int log(int x, int base)
{
    return (int) (Math.log(x) / Math.log(base));
}

this prints:

error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...

To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14. Could you have told this before testing? I definitely could not.

Rename file with Git

I had a similar problem going through a tutorial.

# git mv README README.markdown

fatal: bad source, source=README, destination=README.markdown

I included the filetype in the source file:

# git mv README.rdoc README.markdown

and it worked perfectly. Don't forget to commit the changes with i.e.:

# git commit -a -m "Improved the README"

Sometimes it is simple little things like that, that piss us off. LOL

How to run Java program in terminal with external library JAR

  1. you can set your classpath in the in the environment variabl CLASSPATH. in linux, you can add like CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external and just run in side ......src/Report/

Javac Reporter.java

java Reporter

Similarily, you can set it in windows environment variables. for example, in Win7

Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila

Extension gd is missing from your system - laravel composer Update

Before installing the missing dependency, you need to check which version of PHP is installed on your system.

php -v
PHP 7.2.10-0ubuntu0.18.04.1 (cli) (built: Sep 13 2018 13:45:02) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.10-0ubuntu0.18.04.1, Copyright (c) 1999-2018, by Zend Technologies

In this case it's php7.2. apt search php7.2 returns all the available PHP extensions.

apt search php7.2
Sorting... Done
Full Text Search... Done
libapache2-mod-php7.2/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (Apache 2 module)

libphp7.2-embed/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  HTML-embedded scripting language (Embedded SAPI library)

php-all-dev/bionic,bionic 1:60ubuntu1 all
  package depending on all supported PHP development packages

php7.2/bionic-updates,bionic-updates,bionic-security,bionic-security 7.2.10-0ubuntu0.18.04.1 all
  server-side, HTML-embedded scripting language (metapackage)

php7.2-bcmath/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Bcmath module for PHP

php7.2-bz2/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  bzip2 module for PHP

php7.2-cgi/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (CGI binary)

php7.2-cli/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  command-line interpreter for the PHP scripting language

php7.2-common/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  documentation, examples and common module for PHP

php7.2-curl/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  CURL module for PHP

php7.2-dba/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  DBA module for PHP

php7.2-dev/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Files for PHP7.2 module development

php7.2-enchant/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Enchant module for PHP

php7.2-fpm/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  server-side, HTML-embedded scripting language (FPM-CGI binary)

php7.2-gd/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  GD module for PHP

php7.2-gmp/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  GMP module for PHP

php7.2-imap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  IMAP module for PHP

php7.2-interbase/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Interbase module for PHP

php7.2-intl/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Internationalisation module for PHP

php7.2-json/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  JSON module for PHP

php7.2-ldap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  LDAP module for PHP

php7.2-mbstring/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  MBSTRING module for PHP

php7.2-mysql/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  MySQL module for PHP

php7.2-odbc/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  ODBC module for PHP

php7.2-opcache/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  Zend OpCache module for PHP

php7.2-pgsql/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  PostgreSQL module for PHP

php7.2-phpdbg/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (PHPDBG binary)

php7.2-pspell/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  pspell module for PHP

php7.2-readline/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  readline module for PHP

php7.2-recode/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  recode module for PHP

php7.2-snmp/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  SNMP module for PHP

php7.2-soap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  SOAP module for PHP

php7.2-sqlite3/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  SQLite3 module for PHP

php7.2-sybase/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Sybase module for PHP

php7.2-tidy/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  tidy module for PHP

php7.2-xml/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  DOM, SimpleXML, WDDX, XML, and XSL module for PHP

php7.2-xmlrpc/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  XMLRPC-EPI module for PHP

php7.2-xsl/bionic-updates,bionic-updates,bionic-security,bionic-security 7.2.10-0ubuntu0.18.04.1 all
  XSL module for PHP (dummy)

php7.2-zip/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Zip module for PHP

You can now proceed to installing the missing dependency by running:

sudo apt install php7.2-gd

Text in HTML Field to disappear when clicked?

This is as simple I think the solution that should solve all your problems:

<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">

This is your submit button:

<input type="submit" id= "submitBtn" value="Submit">

then put this small jQuery in a js file:

//this will submit only if the value is not default
$("#submitBtn").click(function () {
    if ($("#valueText").val() === "ENTER VALUE")
    {
        alert("please insert a valid value");
        return false;
    }
});

//this will put default value if the field is empty
$("#valueText").blur(function () {
    if(this.value == ''){ 
        this.value = 'ENTER VALUE';
    }
}); 

 //this will empty the field is the value is the default one
 $("#valueText").focus(function () {
    if (this.value == 'ENTER VALUE') {
        this.value = ''; 
    }
});

And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.

Adding a new entry to the PATH variable in ZSH

  1. Added path to ~/.zshrc

    sudo vi ~/.zshrc

    add new path

    export PATH="$PATH:[NEW_DIRECTORY]/bin"
    
  2. Update ~/.zshrc

    Save ~/.zshrc

    source ~/.zshrc

  3. Check PATH

    echo $PATH

How to import or copy images to the "res" folder in Android Studio?

I'm in Mac OSX as well and in a new project I need to:

  • Right click on res folder in the project and add a new Android resource directory.
  • Select drawable from the drop down and Accept.
  • Copy and paste the image into the drawable folder.

Disclaimer : This does NOT cover different resolutions etc.

how to download image from any web page in java

If you want to save the image and you know its URL you can do this:

try(InputStream in = new URL("http://example.com/image.jpg").openStream()){
    Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));
}

You will also need to handle the IOExceptions which may be thrown.

Split pandas dataframe in two if it has more than 10 rows

You can use the DataFrame head and tail methods as syntactic sugar instead of slicing/loc here. I use a split size of 3; for your example use headSize=10

def split(df, headSize) :
    hd = df.head(headSize)
    tl = df.tail(len(df)-headSize)
    return hd, tl

df = pd.DataFrame({    'A':[2,4,6,8,10,2,4,6,8,10],
                       'B':[10,-10,0,20,-10,10,-10,0,20,-10],
                       'C':[4,12,8,0,0,4,12,8,0,0],
                      'D':[9,10,0,1,3,np.nan,np.nan,np.nan,np.nan,np.nan]})

# Split dataframe into top 3 rows (first) and the rest (second)
first, second = split(df, 3)

The system cannot find the file specified in java

In your IDE right click on the file you want to read and choose "copy path" then paste it into your code.

Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"

jQuery how to bind onclick event to dynamically added HTML element

Consider this:

jQuery(function(){
  var close_link = $('<a class="" href="#">Click here to see an alert</a>');
      $('.add_to_this').append(close_link);
      $('.add_to_this').children().each(function()
      {
        $(this).click(function() {
            alert('hello from binded function call');
            //do stuff here...
        });
      });
});

It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it.

The best way will probably be - as suggested - to bind it to a specific class via the live method.

Explicitly set column value to null SQL Developer

If you want to use the GUI... click/double-click the table and select the Data tab. Click in the column value you want to set to (null). Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.

enter image description here

More info here:

How to use the SQL Worksheet in SQL Developer to Insert, Update and Delete Data

Android Studio shortcuts like Eclipse

View > Quick Switch Scheme > Keymap > Eclipse
use this option for eclipse keymap or if u want to go with AndroidStudio keymap then follow below link

Click here for Official Android Studio Keymap Refference guide

you may find default keymap referrence in

AndroidStudio --> Help-->Default keymap refrence

Error on renaming database in SQL Server 2008 R2

Another way to close all connections:

Administrative Tools > View Local Services

Stop/Start the "SQL Server (MSSQLSERVER)" service

How do I increment a DOS variable in a FOR /F loop?

I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames

set TEXT_T="myfile.txt"

set /a c=1

setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c=c+1
    set OUTPUT_FILE_NAME=output_!c!.txt
    echo Output file is !OUTPUT_FILE_NAME!
    echo %%i, !c!
)

endlocal

Why is `input` in Python 3 throwing NameError: name... is not defined

I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.

CSS text-transform capitalize on all caps

After researching a lot I found jquery function/expression to change text in first letter in uppercase only, I modify that code accordingly to make it workable for input field. When you will write something in input field and then move to another filed or element, the text of that field will change with 1st-letter capitalization only. No matter user type text in complete lower or upper case capitalization:

Follow this code:

Step-1: Call jquery library in html head:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Step-2: Write code to change text of input fields:

<script>
$(document).ready(function(){
$("#edit-submitted-first-name,#edit-submitted-last-name,#edit-submitted-company-name, #edit-submitted-city").focusout(function(){
var str=$(this).val();
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
});
$(this).val(str);
 });});

 </script>

Step-3: Create HTML input fields with same id's you use in jquery code like:

<input type="text" id="edit-submitted-first-name" name="field name">

The id of this input field is: edit-submitted-first-name (It using in jquery code in step-2)

**Result: Make sure the text will change after you move your focus from that input field at another element. Because we using focus out event of jquery here. Result should like this: User Type: "thank you" it will change with "Thank You". **

Best of luck

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

I also have the same error. I have updated the jackson library version and error has gone.

<!-- Jackson to convert Java object to Json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

and also check your data classes that have you created getters and setters for all the properties.

How to show SVG file on React Native?

After trying many ways and libraries I decided to create a new font (with Glyphs or this tutorial) and add my SVG files to it, then use "Text" component with my custom font.

Hope this helps anyone that has the same problem with SVG in react-native.

How to send a model in jQuery $.ajax() post request to MVC controller method

If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.

Can I have an onclick effect in CSS?

Edit: Answered before OP clarified what he wanted. The following is for an onclick similar to javascripts onclick, not the :active pseudo class.

This can only be achieved with either Javascript or the Checkbox Hack

The checkbox hack essentially gets you to click on a label, that "checks" a checkbox, allowing you to style the label as you wish.

The demo

PHP Unset Session Variable

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable

<?php    unset($_SESSION['counter']); ?>

Here is the call which will destroy all the session variables

<?php    session_destroy(); ?>

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

I want to comment/partially answer/share my thoughts. I am using the overflow-y:scroll technique for a big upcoming project of mine. Using it has two MAJOR advantages.

a) You can use a drawer with action buttons from the bottom of the screen; if the document scrolls and the bottom bar disappears, tapping on a button located at the bottom of the screen will first make the bottom bar appear, and then be clickable. Also, the way this thing works, causes trouble with modals that have buttons at the far bottom.

b) When using an overflown element, the only things that are repainted in case of major css changes are the ones in the viewable screen. This gave me a huge performance boost when using javascript to alter css of multiple elements on the fly. For example, if you have a list of 20 elements you need repainted and only two of them are on-screen in the overflown element, only those are repainted while the rest are repainted when scrolling. Without it all 20 elements are repainted.

..of course it depends on the project and if you need any of the functionality I mentioned. Google uses overflown elements for gmail to use the functionality I described on a). Imo, it's worth the while, even considering the small height in older iphones (372px as you said).

Replace text inside td using jQuery having td containing other elements

$('#demoTable td').contents().each(function() {
    if (this.nodeType === 3) {
        this.textContent
        ? this.textContent = 'The text has been '
        : this.innerText  = 'The text has been '
    } else {
        this.innerHTML = 'changed';
        return false;
    }
})

http://jsfiddle.net/YSAjU/

A weighted version of random.choice

As of Python v3.6, random.choices could be used to return a list of elements of specified size from the given population with optional weights.

random.choices(population, weights=None, *, cum_weights=None, k=1)

  • population : list containing unique observations. (If empty, raises IndexError)

  • weights : More precisely relative weights required to make selections.

  • cum_weights : cumulative weights required to make selections.

  • k : size(len) of the list to be outputted. (Default len()=1)


Few Caveats:

1) It makes use of weighted sampling with replacement so the drawn items would be later replaced. The values in the weights sequence in itself do not matter, but their relative ratio does.

Unlike np.random.choice which can only take on probabilities as weights and also which must ensure summation of individual probabilities upto 1 criteria, there are no such regulations here. As long as they belong to numeric types (int/float/fraction except Decimal type) , these would still perform.

>>> import random
# weights being integers
>>> random.choices(["white", "green", "red"], [12, 12, 4], k=10)
['green', 'red', 'green', 'white', 'white', 'white', 'green', 'white', 'red', 'white']
# weights being floats
>>> random.choices(["white", "green", "red"], [.12, .12, .04], k=10)
['white', 'white', 'green', 'green', 'red', 'red', 'white', 'green', 'white', 'green']
# weights being fractions
>>> random.choices(["white", "green", "red"], [12/100, 12/100, 4/100], k=10)
['green', 'green', 'white', 'red', 'green', 'red', 'white', 'green', 'green', 'green']

2) If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence.

Specifying both weights and cum_weights raises a TypeError.

>>> random.choices(["white", "green", "red"], k=10)
['white', 'white', 'green', 'red', 'red', 'red', 'white', 'white', 'white', 'green']

3) cum_weights are typically a result of itertools.accumulate function which are really handy in such situations.

From the documentation linked:

Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

So, either supplying weights=[12, 12, 4] or cum_weights=[12, 24, 28] for our contrived case produces the same outcome and the latter seems to be more faster / efficient.

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

How can I provide multiple conditions for data trigger in WPF?

@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)

but if you have values other than boolean try using type converters:

<MultiDataTrigger.Conditions>
    <Condition Value="True">
        <Condition.Binding>
            <MultiBinding Converter="{StaticResource conditionConverter}">
                <Binding Path="Name" />
                <Binding Path="State" />
            </MultiBinding>
        </Condition.Binding>
        <Setter Property="Background" Value="Cyan" />
    </Condition>
</MultiDataTrigger.Conditions>

you can use the values in Convert method any way you like to produce a condition which suits you.

What is the difference between an expression and a statement in Python?

Statements before could change the state of our Python program: create or update variables, define function, etc.

And expressions just return some value can't change the global state or local state in a function.

But now we got :=, it's an alien!

tar: file changed as we read it

To enhance Fabian's one-liner; let us say that we want to ignore only exit status 1 but to preserve the exit status if it is anything else:

tar -czf sample.tar.gz dir1 dir2 || ( export ret=$?; [[ $ret -eq 1 ]] || exit "$ret" )

This does everything sandeep's script does, on one line.

How can I grep for a string that begins with a dash/hyphen?

ls -l | grep "^-"

Hope this one would serve your purpose.

Handle file download from ajax post

see: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/ it'll return a blob as a response, which can then be put into filesaver

How to run a command as a specific user in an init script?

For systemd style init scripts it's really easy. You just add a User= in the [Service] section.

Here is an init script I use for qbittorrent-nox on CentOS 7:

[Unit]
Description=qbittorrent torrent server

[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort

[Install]
WantedBy=multi-user.target

how to change listen port from default 7001 to something different?

That file has a listen-port element - that should be what you need to change, although it is currently set to 8080, not 7001.

LINQ to SQL Left Outer Join

I found 1 solution. if want to translate this kind of SQL (left join) into Linq Entity...

SQL:

SELECT * FROM [JOBBOOKING] AS [t0]
LEFT OUTER JOIN [REFTABLE] AS [t1] ON ([t0].[trxtype] = [t1].[code])
                                  AND ([t1]. [reftype] = "TRX")

LINQ:

from job in JOBBOOKINGs
join r in (from r1 in REFTABLEs where r1.Reftype=="TRX" select r1) 
          on job.Trxtype equals r.Code into join1
from j in join1.DefaultIfEmpty()
select new
{
   //cols...
}

List of tuples to dictionary

Functional decision for @pegah answer:

from itertools import groupby

mylist = [('a', 1), ('b', 3), ('a', 2), ('b', 4)]
#mylist = iter([('a', 1), ('b', 3), ('a', 2), ('b', 4)])

result = { k : [*map(lambda v: v[1], values)]
    for k, values in groupby(sorted(mylist, key=lambda x: x[0]), lambda x: x[0])
    }

print(result)
# {'a': [1, 2], 'b': [3, 4]}

"Faceted Project Problem (Java Version Mismatch)" error message

I encountered this issue while running an app on Java 1.6 while I have all three versions of Java 6,7,8 for different apps.I accessed the Navigator View and manually removed the unwanted facet from the facet.core.xml .Clean build and wallah!

<?xml version="1.0" encoding="UTF-8"?>

<fixed facet="jst.java"/>

<fixed facet="jst.web"/>

<installed facet="jst.web" version="2.4"/>

<installed facet="jst.java" version="6.0"/>

<installed facet="jst.utility" version="1.0"/>

Check if all values of array are equal

var listTrue = ['a', 'a', 'a', 'a'];
var listFalse = ['a', 'a', 'a', 'ab'];

function areWeTheSame(list) { 
    var sample = list[0];
    return !(list.some(function(item) {
        return !(item == sample);
    }));
}

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

jQuery find events handlers registered with an object

jQuery is not letting you just simply access the events for a given element. You can access them using undocumented internal method

$._data(element, "events")

But it still won't give you all the events, to be precise won't show you events assigned with

$([selector|element]).on()

These events are stored inside document, so you can fetch them by browsing through

$._data(document, "events")

but that is hard work, as there are events for whole webpage.

Tom G above created function that filters document for only events of given element and merges output of both methods, but it had a flaw of duplicating events in the output (and effectively on the element's jQuery internal event list messing with your application). I fixed that flaw and you can find the code below. Just paste it into your dev console or into your app code and execute it when needed to get nice list of all events for given element.

What is important to notice, element is actually HTMLElement, not jQuery object.

function getEvents(element) {
    var elemEvents = $._data(element, "events");
    var allDocEvnts = $._data(document, "events");
    function equalEvents(evt1, evt2)
    {
        return evt1.guid === evt2.guid;
    }

    for(var evntType in allDocEvnts) {
        if(allDocEvnts.hasOwnProperty(evntType)) {
            var evts = allDocEvnts[evntType];
            for(var i = 0; i < evts.length; i++) {
                if($(element).is(evts[i].selector)) {
                    if(elemEvents == null) {
                        elemEvents = {};
                    }
                    if(!elemEvents.hasOwnProperty(evntType)) {
                        elemEvents[evntType] = [];
                    }
                    if(!elemEvents[evntType].some(function(evt) { return equalEvents(evt, evts[i]); })) {
                        elemEvents[evntType].push(evts[i]);
                    }
                }
            }
        }
    }
    return elemEvents;
}

Ignoring SSL certificate in Apache HttpClient 4.3

Simpler and shorter working code:

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method which you use to make post request...

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue calling and using HttpPost instance in the normal form

Get an element by index in jQuery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

<script>
    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';
    $(selector).css({'background-color':'#343434'});
</script>

There are other selectors that you may use with jQuery to match any element that you need.

SQLAlchemy create_all() does not create tables

This is probably not the main reason why the create_all() method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

def get_db():
  if 'db' not in g:
    g.db = SQLAlchemy(current_app)
  return g.db

I also have a separate cli command that also does the create_all:

# tasks/db.py
from lib.db import get_db

@current_app.cli.command('init-db')
def init_db():
  db = get_db()
  db.create_all()

I also am using a application factory.

When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).

The fix that I came around to was to make sure that the db was a single global reference:

# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy

db = None
def get_db():
  global db
  if not db:
    db = SQLAlchemy(current_app)
  return db

I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.

Show constraints on tables command

Analogous to @Resh32, but without the need to use the USE statement:

SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name" 
      AND TABLE_NAME = "table_name" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

Useful, e.g. using the ORM.

Reset git proxy to default configuration

For me, I had to add:

git config --global --unset http.proxy

Basically, you can run:

git config --global -l 

to get the list of all proxy defined, and then use "--unset" to disable them

How to stop java process gracefully?

Signalling in Linux can be done with "kill" (man kill for the available signals), you'd need the process ID to do that. (ps ax | grep java) or something like that, or store the process id when the process gets created (this is used in most linux startup files, see /etc/init.d)

Portable signalling can be done by integrating a SocketServer in your java application. It's not that difficult and gives you the freedom to send any command you want.

If you meant finally clauses in stead of finalizers; they do not get extecuted when System.exit() is called. Finalizers should work, but shouldn't really do anything more significant but print a debug statement. They're dangerous.

Get current time in seconds since the Epoch on Linux, Bash

This is an extension to what @pellucide has done, but for Macs:

To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)

$ date -j -f "%b %d %Y %T" "Oct 21 1973 00:00:00" "+%s"
120034800

Please note, that for completeness, I have added the time part to the format. The reason being is that date will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the '00:00:00' part, it will add the time automatically. Such that "Oct 21 1973" will be parsed as "Oct 21 1973 16:19:00". That may not be what you want.

To convert your timestamp back to a date:

$ date -j -r 120034800
Sun Oct 21 00:00:00 PDT 1973

Apple's man page for the date implementation: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/date.1.html

Convert an integer to an array of digits

I modified Jon Skeet's accepted answer as it does not accept negative values.

This now accepts and converts the number appropriately:

public static void main(String[] args) {
    int number = -1203;
    boolean isNegative = false;
    String temp = Integer.toString(number);

    if(temp.charAt(0)== '-') {
        isNegative = true;
    }
    int len = temp.length();
    if(isNegative) {
        len = len - 1;
    }
    int[] myArr = new int[len];

    for (int i = 0; i < len; i++) {
        if (isNegative) {
            myArr[i] = temp.charAt(i + 1) - '0';
        }
        if(!isNegative) {
            myArr[i] = temp.charAt(i) - '0';
        }
    }

    if (isNegative) {
        for (int i = 0; i < len; i++) {
            myArr[i] = myArr[i] * (-1);
        }
    }

    for (int k : myArr) {
        System.out.println(k);
    }
}

Output

-1
-2
0
-3

Column name or number of supplied values does not match table definition

for inserts it is always better to specify the column names see the following

DECLARE @Table TABLE(
        Val1 VARCHAR(MAX)
)

INSERT INTO @Table SELECT '1'

works fine, changing the table def to causes the error

DECLARE @Table TABLE(
        Val1 VARCHAR(MAX),
        Val2 VARCHAR(MAX)
)

INSERT INTO @Table SELECT '1'

Msg 213, Level 16, State 1, Line 6 Insert Error: Column name or number of supplied values does not match table definition.

But changing the above to

DECLARE @Table TABLE(
        Val1 VARCHAR(MAX),
        Val2 VARCHAR(MAX)
)

INSERT INTO @Table (Val1)  SELECT '1'

works. You need to be more specific with the columns specified

supply the structures and we can have a look

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

Add up a column of numbers at the Unix shell

Pipe to gawk:

 cat files.txt | xargs ls -l | cut -c 23-30 | gawk 'BEGIN { sum = 0 } // { sum = sum + $0 } END { print sum }'

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

The simple solution is to cast CLOB to BLOB and then request length of BLOB !

The problem is that Oracle doesn't have a function that cast CLOB to BLOB, but we can simply define a function to do that

create or replace
FUNCTION clob2blob (p_in clob) RETURN blob IS 
    v_blob        blob;
    v_desc_offset PLS_INTEGER := 1;
    v_src_offset  PLS_INTEGER := 1;
    v_lang        PLS_INTEGER := 0;
    v_warning     PLS_INTEGER := 0;  
BEGIN
    dbms_lob.createtemporary(v_blob,TRUE);
    dbms_lob.converttoblob
        ( v_blob
        , p_in
        , dbms_lob.getlength(p_in)
        , v_desc_offset
        , v_src_offset
        , dbms_lob.default_csid
        , v_lang
        , v_warning
        );
    RETURN v_blob;
END;

The SQL command to use to obtain number of bytes is

SELECT length(clob2blob(fieldname)) as nr_bytes 

or

SELECT dbms_lob.getlength(clob2blob(fieldname)) as nr_bytes

I have tested this on Oracle 10g without using Unicode(UTF-8). But I think that this solution must be correct using Unicode(UTF-8) Oracle instance :-)

I want render thanks to Nashev that has posted a solution to convert clob to blob How convert CLOB to BLOB in Oracle? and to this post written in german (the code is in PL/SQL) 13ter.info.blog that give additionally a function to convert blob to clob !

Can somebody test the 2 commands in Unicode(UTF-8) CLOB so I'm sure that this works with Unicode ?

How to update UI from another thread running in another class

Everything that interacts with the UI must be called in the UI thread (unless it is a frozen object). To do that, you can use the dispatcher.

var disp = /* Get the UI dispatcher, each WPF object has a dispatcher which you can query*/
disp.BeginInvoke(DispatcherPriority.Normal,
        (Action)(() => /*Do your UI Stuff here*/));

I use BeginInvoke here, usually a backgroundworker doesn't need to wait that the UI updates. If you want to wait, you can use Invoke. But you should be careful not to call BeginInvoke to fast to often, this can get really nasty.

By the way, The BackgroundWorker class helps with this kind of taks. It allows Reporting changes, like a percentage and dispatches this automatically from the Background thread into the ui thread. For the most thread <> update ui tasks the BackgroundWorker is a great tool.

How to use sed/grep to extract text between two words?

The accepted answer does not remove text that could be before Here or after String. This will:

sed -e 's/.*Here\(.*\)String.*/\1/'

The main difference is the addition of .* immediately before Here and after String.

TypeError: no implicit conversion of Symbol into Integer

Your item variable holds Array instance (in [hash_key, hash_value] format), so it doesn't expect Symbol in [] method.

This is how you could do it using Hash#each:

def format(hash)
  output = Hash.new
  hash.each do |key, value|
    output[key] = cleanup(value)
  end
  output
end

or, without this:

def format(hash)
  output = hash.dup
  output[:company_name] = cleanup(output[:company_name])
  output[:street] = cleanup(output[:street])
  output
end

java.time.format.DateTimeParseException: Text could not be parsed at index 21

Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:

uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)

How to send data in request body with a GET when using jQuery $.ajax()

Just in case somebody ist still coming along this question:

There is a body query object in any request. You do not need to parse it yourself.

E.g. if you want to send an accessToken from a client with GET, you could do it like this:

_x000D_
_x000D_
const request = require('superagent');_x000D_
_x000D_
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {_x000D_
  if (err) throw new Error(err);_x000D_
  console.log(res);_x000D_
});
_x000D_
_x000D_
_x000D_

The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }

C# elegant way to check if a property's property is null

You're obviously looking for the Nullable Monad:

string result = new A().PropertyB.PropertyC.Value;

becomes

string result = from a in new A()
                from b in a.PropertyB
                from c in b.PropertyC
                select c.Value;

This returns null, if any of the nullable properties are null; otherwise, the value of Value.

class A { public B PropertyB { get; set; } }
class B { public C PropertyC { get; set; } }
class C { public string Value { get; set; } }

LINQ extension methods:

public static class NullableExtensions
{
    public static TResult SelectMany<TOuter, TInner, TResult>(
        this TOuter source,
        Func<TOuter, TInner> innerSelector,
        Func<TOuter, TInner, TResult> resultSelector)
        where TOuter : class
        where TInner : class
        where TResult : class
    {
        if (source == null) return null;
        TInner inner = innerSelector(source);
        if (inner == null) return null;
        return resultSelector(source, inner);
    }
}

Center Oversized Image in Div

One option you can use is object-fit: cover it behaves a bit like background-size: cover. More on object-fit.

ignore all the JS below, that's just for the demo.

The key here is that you need to set the image inside a wrapper and give it the following properties.

.wrapper img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

I've created a demo below where you change the height / width of the wrapper and see in play. The image will always be vertically and horizontally centered. It will take up 100% of its parent width and height, and will not be stretched / squashed. This means that the aspect ratio of the image is maintained. The changes are applied by zooming in / out instead.

The only downside to object-fit is that it doesn't work on IE11.

_x000D_
_x000D_
// for demo only_x000D_
const wrapper = document.querySelector('.wrapper');_x000D_
const button = document.querySelector('button');_x000D_
const widthInput = document.querySelector('.width-input');_x000D_
const heightInput = document.querySelector('.height-input');_x000D_
_x000D_
_x000D_
const resizeWrapper = () => {_x000D_
  wrapper.style.width = widthInput.value + "px";_x000D_
  wrapper.style.height = heightInput.value + "px";_x000D_
}_x000D_
_x000D_
button.addEventListener("click", resizeWrapper);
_x000D_
.wrapper {_x000D_
  overflow: hidden;_x000D_
  max-width: 100%;_x000D_
  margin-bottom: 2em;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
.wrapper img {_x000D_
  display: block;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  object-fit: cover;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <img src="https://i.imgur.com/DrzMS8i.png">_x000D_
</div>_x000D_
_x000D_
_x000D_
<!-- demo only -->_x000D_
<lable for="width">_x000D_
  Width: <input name="width" class='width-input'>_x000D_
</lable>_x000D_
<lable for="height">_x000D_
  height: <input name="height" class='height-input'>_x000D_
</lable>_x000D_
<button>change size!</button>
_x000D_
_x000D_
_x000D_

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        </div>
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    </div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {
    $('#resultLoading').show();
    $('#resultLoading').find('.loader-text').html(text);
};

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');
    });
});

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

Recursively add the entire folder to a repository

Check the .gitignore file, if the subdirectory is ignored.

Then try again

git add --all
git commit -am "<commit message>"
git push

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Force youtube embed to start in 720p

None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:

<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>

I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.

When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

How to filter a dictionary according to an arbitrary condition function?

I think that Alex Martelli's answer is definitely the most elegant way to do this, but just wanted to add a way to satisfy your want for a super awesome dictionary.filter(f) method in a Pythonic sort of way:

class FilterDict(dict):
    def __init__(self, input_dict):
        for key, value in input_dict.iteritems():
            self[key] = value
    def filter(self, criteria):
        for key, value in self.items():
            if (criteria(value)):
                self.pop(key)

my_dict = FilterDict( {'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} )
my_dict.filter(lambda x: x[0] < 5 and x[1] < 5)

Basically we create a class that inherits from dict, but adds the filter method. We do need to use .items() for the the filtering, since using .iteritems() while destructively iterating will raise exception.

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

C# Break out of foreach loop after X number of items

int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
   //do stuff
   if (++processed == 50) break;
}

or use LINQ

foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
    //do stuff
}

or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)

for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
    ListViewItem lvi = listView.Items[i];
}

In Java, what does NaN mean?

NaN stands for Not a Number. It is used to signify any value that is mathematically undefined. Like dividing 0.0 by 0.0. You can look here for more information: https://web.archive.org/web/20120819091816/http://www.concentric.net/~ttwang/tech/javafloat.htm

Post your program here if you need more help.

onChange and onSelect in DropDownList

I bet the onchange is getting fired after the onselect, essentially re-enabling the select.

I'd recommend you implement only the onchange, inspect which option has been selected, and enable or disabled based on that.

To get the value of the selected option use:

document.getElementById("mySelect").options[document.getElementById("mySelect").selectedIndex].value

Which will yield .. nothing since you haven't specified a value for each option .. :(

<select id="mySelect" onChange="enable();">
<option onSelect="disable();" value="no">No</option>
<option onSelect="enable();" value="yes">Yes</option>
</select>

Now it will yield "yes" or "no"

Why is C so fast, and why aren't other languages as fast or faster?

C++ is faster on average (as it was initially, largely a superset of C, though there are some differences). However, for specific benchmarks, there is often another language which is faster.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/

fannjuch-redux was fastest in Scala

n-body and fasta were faster in Ada.

spectral-norm was fastest in Fortran.

reverse-complement, mandelbrot and pidigits were fastest in ATS.

regex-dna was fastest in JavaScript.

chameneou-redux was fastest is Java 7.

thread-ring was fastest in Haskell.

The rest of the benchmarks were fastest in C or C++.

How do I use properly CASE..WHEN in MySQL

CASE course_enrollment_settings.base_price is wrong here, it should be just CASE

SELECT 
CASE 
WHEN course_enrollment_settings.base_price = 0      THEN 1 
WHEN course_enrollment_settings.base_price<101      THEN 2 
WHEN course_enrollment_settings.base_price>100 AND    
                  course_enrollment_settings.base_price<201 THEN 3 
    ELSE 6 
END AS 'calc_base_price', 
course_enrollment_settings.base_price 
FROM 
  course_enrollment_settings 
WHERE course_enrollment_settings.base_price = 0 

Some explanations. Your original query will be executed as :

SELECT 
CASE 0
WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - false
WHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - false
WHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - true
ELSE 6, ...

it's why you always get 3

NameError: global name is not defined

That's How Python works. Try this :

from sqlitedbx import SqliteDBzz

Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc

How can foreign key constraints be temporarily disabled using T-SQL?

You can temporarily disable constraints on your tables, do work, then rebuild them.

Here is an easy way to do it...

Disable all indexes, including the primary keys, which will disable all foreign keys, then re-enable just the primary keys so you can work with them...

DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
    'ALTER INDEX ALL ON [' + t.[name] + '] DISABLE;'+CHAR(13)
from  
    sys.tables t
where type='u'

select @sql = @sql +
    'ALTER INDEX ' + i.[name] + ' ON [' + t.[name] + '] REBUILD;'+CHAR(13)
from  
    sys.key_constraints i
join
    sys.tables t on i.parent_object_id=t.object_id
where
    i.type='PK'


exec dbo.sp_executesql @sql;
go

[Do something, like loading data]

Then re-enable and rebuild the indexes...

DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
    'ALTER INDEX ALL ON [' + t.[name] + '] REBUILD;'+CHAR(13)
from  
    sys.tables t
where type='u'

exec dbo.sp_executesql @sql;
go

Can't use modulus on doubles?

You can implement your own modulus function to do that for you:

double dmod(double x, double y) {
    return x - (int)(x/y) * y;
}

Then you can simply use dmod(6.3, 2) to get the remainder, 0.3.

Border Height on CSS

No, there isn't. The border will always be as tall as the element.

You can achieve the same effect by wrapping the contents of the cell in a <span>, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:

background:url(line.png) bottom right no-repeat;

How do I implement a progress bar in C#?

When you perform operations on Background thread and you want to update UI, you can not call or set anything from background thread. In case of WPF you need Dispatcher.BeginInvoke and in case of WinForms you need Invoke method.

WPF:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Dispatcher.BeginInvoke((Action)delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

WinForms:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Invoke(delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

for WinForms delegate may require some casting or you may need little help there, dont remember the exact syntax now.

How to delete from multiple tables in MySQL?

Since this appears to be a simple parent/child relationship between pets and pets_activities, you would be better off creating your foreign key constraint with a deleting cascade.

That way, when a pets row is deleted, the pets_activities rows associated with it are automatically deleted as well.

Then your query becomes a simple:

delete from `pets`
    where `order` > :order
      and `pet_id` = :pet_id

How to validate an email address in PHP

If you want to check if provided domain from email address is valid, use something like:

/*
* Check for valid MX record for given email domain
*/
if(!function_exists('check_email_domain')){
    function check_email_domain($email) {
        //Get host name from email and check if it is valid
        $email_host = explode("@", $email);     
        //Add a dot to the end of the host name to make a fully qualified domain name and get last array element because an escaped @ is allowed in the local part (RFC 5322)
        $host = end($email_host) . "."; 
        //Convert to ascii (http://us.php.net/manual/en/function.idn-to-ascii.php)
        return checkdnsrr(idn_to_ascii($host), "MX"); //(bool)       
    }
}

This is handy way to filter a lot of invalid email addresses, along with standart email validation, because valid email format does not mean valid email.

Note that idn_to_ascii() (or his sister function idn_to_utf8()) function may not be available in your PHP installation, it requires extensions PECL intl >= 1.0.2 and PECL idn >= 0.1.

Also keep in mind that IPv4 or IPv6 as domain part in email (for example user@[IPv6:2001:db8::1]) cannot be validated, only named hosts can.

See more here.

JavaScript "cannot read property "bar" of undefined

Compound checking:

   if (thing.foo && thing.foo.bar) {
      ... thing.foor.bar exists;
   }

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

JAVA_HOME does not point to the JDK

It looks like you are currently pointing JAVA_HOME to /usr/lib/jvm/java-6-openjdk/jre which appears to be a JRE not a JDK. Try setting JAVA_HOME to /usr/lib/jvm/java-6-openjdk.

The JRE does not contain the Java compiler, only the JDK (Java Developer Kit) contains it.

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

Handling 'Sequence has no elements' Exception

The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)

Check the hardware Connections.

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

What is the difference between Bower and npm?

This answer is an addition to the answer of Sindre Sorhus. The major difference between npm and Bower is the way they treat recursive dependencies. Note that they can be used together in a single project.

On the npm FAQ: (archive.org link from 6 Sep 2015)

It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.

On Bower homepage:

Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.

In short, npm aims for stability. Bower aims for minimal resource load. If you draw out the dependency structure, you will see this:

npm:

project root
[node_modules] // default directory for dependencies
 -> dependency A
 -> dependency B
    [node_modules]
    -> dependency A

 -> dependency C
    [node_modules]
    -> dependency B
      [node_modules]
       -> dependency A 
    -> dependency D

As you can see it installs some dependencies recursively. Dependency A has three installed instances!

Bower:

project root
[bower_components] // default directory for dependencies
 -> dependency A
 -> dependency B // needs A
 -> dependency C // needs B and D
 -> dependency D

Here you see that all unique dependencies are on the same level.

So, why bother using npm?

Maybe dependency B requires a different version of dependency A than dependency C. npm installs both versions of this dependency so it will work anyway, but Bower will give you a conflict because it does not like duplication (because loading the same resource on a webpage is very inefficient and costly, also it can give some serious errors). You will have to manually pick which version you want to install. This can have the effect that one of the dependencies will break, but that is something that you will need to fix anyway.

So, the common usage is Bower for the packages that you want to publish on your webpages (e.g. runtime, where you avoid duplication), and use npm for other stuff, like testing, building, optimizing, checking, etc. (e.g. development time, where duplication is of less concern).

Update for npm 3:

npm 3 still does things differently compared to Bower. It will install the dependencies globally, but only for the first version it encounters. The other versions are installed in the tree (the parent module, then node_modules).

  • [node_modules]
    • dep A v1.0
    • dep B v1.0
      • dep A v1.0 (uses root version)
    • dep C v1.0
      • dep A v2.0 (this version is different from the root version, so it will be an nested installation)

For more information, I suggest reading the docs of npm 3

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

Cannot catch toolbar home button click event

This is how I implemented it pre-material design and it seems to still work now I've switched to the new Toolbar. In my case I want to log the user in if they attempt to open the side nav while logged out, (and catch the event so the side nav won't open). In your case you could not return true;.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (!isLoggedIn() && item.getItemId() == android.R.id.home) {
        login();
        return true;
    }
    return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}

jquery click event not firing?

You need to prevent the default event (following the link), otherwise your link will load a new page:

    $(document).ready(function(){
        $('.play_navigation a').click(function(e){
            e.preventDefault();
            console.log("this is the click");
        });
    });

As pointed out in comments, if your link has no href, then it's not a link, use something else.

Not working? Your code is A MESS! and ready() events everywhere... clean it, put all your scripts in ONE ready event and then try again, it will very likely sort things out.

Are there any standard exit status codes in Linux?

When Linux returns 0, it means success. Anything else means failure, each program has its own exit codes, so it would been quite long to list them all... !

About the 11 error code, it's indeed the segmentation fault number, mostly meaning that the program accessed a memory location that was not assigned.

PHP JSON String, escape Double Quotes for JS output

I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

$products = array($ofDirtyArray);
if($products !=null) {
    header("Content-type: application/json");
    header('Content-Type: charset=utf-8');
    array_walk_recursive($products, function(&$val) {
        $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
    });
    echo json_encode($products,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

I hope it helps someone/someone improves it.

how to get program files x86 env variable?

Another relevant environment variable is:

%ProgramW6432%

So, on a 64-bit machine running in 32-bit (WOW64) mode:

  • echo %programfiles% ==> C:\Program Files (x86)
  • echo %programfiles(x86)% ==> C:\Program Files (x86)
  • echo %ProgramW6432% ==> C:\Program Files

From Wikipedia:

The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

Reference: http://en.wikipedia.org/wiki/Environment_variable

Regular expression to return text between parenthesis

If your problem is really just this simple, you don't need regex:

s[s.find("(")+1:s.find(")")]

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

PHP cURL not working - WAMP on Windows 7 64 bit

Go to http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/ and download the cURL version that corresponds to your PHP version under "Fixed curl extensions:".

So if you have PHP 5.3.13, download "php_curl-5.3.13-VC9-x64.zip". Try the "VC" version first. Then replace the php_curl.dll in ext folder. This worked for me.

@Autowired - No qualifying bean of type found for dependency

Instead of @Autowire MailManager mailManager, you can mock the bean as given below:

import org.springframework.boot.test.mock.mockito.MockBean;

::
::

@MockBean MailManager mailManager;

Also, you can configure @MockBean MailManager mailManager; separately in the @SpringBootConfiguration class and initialize like below:

@Autowire MailManager mailManager

How to print without newline or space?

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i)

The above code gives the following output:

 0    
 1
 2
 3
 4

But if you want to print all these output in a straight line then all you should do is add an attribute called end() to print.

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i, end=" ")

Output:

 0 1 2 3 4

And not just a space, you can also add other endings for your output. For example,

 for i in range(0, 5): #setting the value of (i) in the range 0 to 5 
     print(i, end=", ")

Output:

 0, 1, 2, 3, 4, 

Remember:

 Note: The [for variable in range(int_1, int_2):] always prints till the variable is 1

 less than it's limit. (1 less than int_2)

How to change default language for SQL Server?

@John Woo's accepted answer has some caveats which you should be aware of:

  1. Default language setting of a session is controlled from default language setting of the user login instead which you have used to create the session. SQL Server instance level setting doesn't affect the default language of the session.
  2. Changing default language setting at SQL Server instance level doesn't affects the default language setting of the existing SQL Server logins. It is meant to be inherited only by the new user logins that you create after changing the instance level setting.

So, there is an intermediate level between your SQL Server instance and the session which you can use to control the default language setting for session - login level.

SQL Server Instance level setting -> User login level setting -> Query Session level setting

This can help you in case you want to set default language of all new sessions belonging to some specific user only.

Simply change the default language setting of the target user login as per this link and you are all set. You can also do it from SQL Server Management Studio (SSMS) UI. Below you can see the default language setting in properties window of sa user in SQL Server:

enter image description here

Note: Also, it is important to know that changing the setting doesn't affect the default language of already active sessions from that user login. It will affect only the new sessions created after changing the setting.

How can I send emails through SSL SMTP with the .NET Framework?

If it's Implicit SSL, it looks like it can't be done with System.Net.Mail and isn't supported as of yet.

http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx

To check if it's Implicit SSL try this.

Error "package android.support.v7.app does not exist"

First of all check if your project is using androidx or android support library. Check gradle.properties file:

android.useAndroidX=true

android.enableJetifier=true

If it contains the above lines, it is using androidx with an old code from some old tutorial.

In build.gradle (module:app)

Use

implementation 'androidx.appcompat:appcompat:1.0.0'

Instead of

compile 'com.android.support:appcompat-v7:28.0.0'

Also in MainActivity.java : Use

import androidx.appcompat.app.AppCompatActivity;

instead of :

import android.support.v7.app.AppCompatActivity;

"error: assignment to expression with array type error" when I assign a struct field (C)

Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

Refused to load the script because it violates the following Content Security Policy directive

To elaborate some more on this, adding

script-src 'self' http://somedomain 'unsafe-inline' 'unsafe-eval';

to the meta tag like so,

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; script-src 'self' https://somedomain.com/ 'unsafe-inline' 'unsafe-eval';  media-src *">

fixes the error.

HTTP GET in VBS

You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.

The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.

Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).

Here is an example of using XmlHttp to fetch a PDF file and store it:-

Dim oXMLHTTP
Dim oStream

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")

oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send

If oXMLHTTP.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write oXMLHTTP.responseBody
    oStream.SaveToFile "c:\somefolder\file.pdf"
    oStream.Close
End If

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

select command denied to user ''@'' for table ''

This problem is a basically generated after join condition are wrong database name in your join query. So please check the your select query in join table name after database.

Then solve it for example its correct ans ware

string g = " SELECT `emptable`.`image` , `applyleave`.`id` , `applyleave`.`empid` , `applyleave`.`empname` , `applyleave`.`dateapply` , `applyleave`.`leavename` , `applyleave`.`fromdate` , `applyleave`.`todate` , `applyleave`.`resion` , `applyleave`.`contact` , `applyleave`.`leavestatus` , `applyleave`.`username` , `applyleave`.`noday` FROM `DataEMP_ems`.`applyleave` INNER JOIN `DataEMP_ems`.`emptable` ON ( `applyleave`.`empid` = `emptable`.`empid` ) WHERE ( `applyleave`.`leavestatus` = 'panding' ) ";

The join table is imputable and applyleave on the same database but online database name is diffrent then given error on this problem.

event.preventDefault() function not working in IE

in IE, you can use

event.returnValue = false;

to achieve the same result.

And in order not to get an error, you can test for the existence of preventDefault:

if(event.preventDefault) event.preventDefault();

You can combine the two with:

event.preventDefault ? event.preventDefault() : (event.returnValue = false);

How do you implement a Stack and a Queue in JavaScript?

Regards,

In Javascript the implementation of stacks and queues is as follows:

Stack: A stack is a container of objects that are inserted and removed according to the last-in-first-out (LIFO) principle.

  • Push: Method adds one or more elements to the end of an array and returns the new length of the array.
  • Pop: Method removes the last element from an array and returns that element.

Queue: A queue is a container of objects (a linear collection) that are inserted and removed according to the first-in-first-out (FIFO) principle.

  • Unshift: Method adds one or more elements to the beginning of an array.

  • Shift: The method removes the first element from an array.

_x000D_
_x000D_
let stack = [];_x000D_
 stack.push(1);//[1]_x000D_
 stack.push(2);//[1,2]_x000D_
 stack.push(3);//[1,2,3]_x000D_
 _x000D_
console.log('It was inserted 1,2,3 in stack:', ...stack);_x000D_
_x000D_
stack.pop(); //[1,2]_x000D_
console.log('Item 3 was removed:', ...stack);_x000D_
_x000D_
stack.pop(); //[1]_x000D_
console.log('Item 2 was removed:', ...stack);_x000D_
_x000D_
_x000D_
let queue = [];_x000D_
queue.push(1);//[1]_x000D_
queue.push(2);//[1,2]_x000D_
queue.push(3);//[1,2,3]_x000D_
_x000D_
console.log('It was inserted 1,2,3 in queue:', ...queue);_x000D_
_x000D_
queue.shift();// [2,3]_x000D_
console.log('Item 1 was removed:', ...queue);_x000D_
_x000D_
queue.shift();// [3]_x000D_
console.log('Item 2 was removed:', ...queue);
_x000D_
_x000D_
_x000D_

Convert a byte array to integer in Java and vice versa

You can also use BigInteger for variable length bytes. You can convert it to long, int or short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

To get bytes back just:

new BigInteger(bytes).toByteArray()

twitter bootstrap text-center when in xs mode

Use bs3-upgrade library for spacings and text aligment...

https://github.com/studija/bs3-upgrade

col-xs-text-center col-sm-text-left

col-xs-text-center col-sm-text-right

<div class="container">
    <div class="row">
        <div class="col-xs-12 col-sm-6 col-xs-text-center col-sm-text-left">
            <p>
                &copy; 2015 example.com. All rights reserved.
            </p>
        </div>
        <div class="col-xs-12 col-sm-6 col-xs-text-center col-sm-text-right">
            <p>
                <a href="#"><i class="fa fa-facebook"></i></a> 
                <a href="#"><i class="fa fa-twitter"></i></a> 
                <a href="#"><i class="fa fa-google-plus"></i></a>
            </p>
        </div>
    </div>
</div>

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Convert date to datetime in Python

You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight.

from datetime import date
from datetime import datetime

dt = datetime.combine(date.today(), datetime.min.time())

get name of a variable or parameter

Alternatively,

1) Without touching System.Reflection namespace,

GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}

2) The below one can be faster though (from my tests)

GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
    if (myInput == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

You can also extend this for properties of objects (may be with extension methods):

new { myClass.MyProperty1 }.GETNAME();

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

How do you keep parents of floated elements from collapsing?

One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.

It goes something like this...

.cf:after {
    content: " ";
    display: block;
    visibility: hidden;
    height: 0;
    clear: both;
}

You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats.

What I use is another variation which comes from Nicolas Gallagher.

It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here http://nicolasgallagher.com/micro-clearfix-hack/ ).

.cf:after {
    content: " ";
    display: table;
    clear: float;
}

Index of duplicates items in a python list

def index(arr, num):
    for i, x in enumerate(arr):
        if x == num:
            print(x, i)

#index(List, 'A')

How can I get zoom functionality for images?

I just integrated Robert Foss's TouchImageView: it worked perfectly out of the box! Thanks!

I just modified a bit the code so I could be able to instantiate it from my layout.xml.

Just add two constructors

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

public TouchImageView(Context context) {
    super(context);
    init(context);
}

and transform the old constructor into an init method:

private void init(Context context){
    //...old code ofconstructor of Robert Moss's code
}

TextView - setting the text size programmatically doesn't seem to work

Text size 2 will be practically invisible. Try it with 14 at least. BTW, using xml has a lot of advantages and will make your life easier once you need to do anything more complex than 'Hello World'.

Sorting a tab delimited file

I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.

Using Lloyd's clue, the following batch file (.bat) worked for me.

Type the tab character within the double quotes.

C:\>cat foo.bat

sort -k3 -t"    " tabfile.txt

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

If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :

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

@JsonProperty("data")
    private JsonNode data;

What is /dev/null 2>&1?

I use >> /dev/null 2>&1 for a silent cronjob. A cronjob will do the job, but not send a report to my email.

As far as I know, don't remove /dev/null. It's useful, especially when you run cPanel, it can be used for throw-away cronjob reports.

pandas: best way to select all columns whose names start with X

In my case I needed a list of prefixes

colsToScale=["production", "test", "development"]
dc[dc.columns[dc.columns.str.startswith(tuple(colsToScale))]]

PHP - define constant inside a class

This is and old question, but now on PHP 7.1 you can define constant visibility.

EXAMPLE

<?php
class Foo {
    // As of PHP 7.1.0
    public const BAR = 'bar';
    private const BAZ = 'baz';
}
echo Foo::BAR . PHP_EOL;
echo Foo::BAZ . PHP_EOL;
?>

Output of the above example in PHP 7.1:

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.

More info here

Sorting dictionary keys in python

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

Firing a Keyboard Event in Safari, using JavaScript

Did you dispatch the event correctly?

function simulateKeyEvent(character) {
  var evt = document.createEvent("KeyboardEvent");
  (evt.initKeyEvent || evt.initKeyboardEvent)("keypress", true, true, window,
                    0, 0, 0, 0,
                    0, character.charCodeAt(0)) 
  var canceled = !body.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

If you use jQuery, you could do:

function simulateKeyPress(character) {
  jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}

connecting to MySQL from the command line

This worked for me ::-

mysql --host=hostNameorIp --user=username --password=password  

or

mysql --host=hostNameorIp --user=username --password=password database_name

What is stability in sorting algorithms and why is it important?

Some more examples of the reason for wanting stable sorts. Databases are a common example. Take the case of a transaction data base than includes last|first name, date|time of purchase, item number, price. Say the data base is normally sorted by date|time. Then a query is made to make a sorted copy of the data base by last|first name, since a stable sort preserves the original order, even though the inquiry compare only involves last|first name, the transactions for each last|first name will be in data|time order.

A similar example is classic Excel, which limited sorts to 3 columns at a time. To sort 6 columns, a sort is done with the least significant 3 columns, followed by a sort with the most significant 3 columns.

A classic example of a stable radix sort is a card sorter, used to sort by a field of base 10 numeric columns. The cards are sorted from least significant digit to most significant digit. On each pass, a deck of cards is read and separated into 10 different bins according to the digit in that column. Then the 10 bins of cards are put back into the input hopper in order ("0" cards first, "9" cards last). Then another pass is done by the next column, until all columns are sorted. Actual card sorters have more than 10 bins since there are 12 zones on a card, a column can be blank, and there is a mis-read bin. To sort letters, 2 passes per column are needed, 1st pass for digit, 2nd pass for the 12 11 zone.

Later (1937) there were card collating (merging) machines that could merge two decks of cards by comparing fields. The input was two already sorted decks of cards, a master deck and an update deck. The collator merged the two decks into a a new mater bin and an archive bin, which was optionally used for master duplicates so that the new master bin would only have update cards in case of duplicates. This was probably the basis for the idea behind the original (bottom up) merge sort.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

My solution is create a Pipe for return the values array or propierties object

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'valueArray',
})
export class ValueArrayPipe implements PipeTransform {

  // El parametro object representa, los valores de las propiedades o indice
  transform(objects : any = []) {
    return Object.values(objects);
  }
}

The template Implement

<button ion-item *ngFor="let element of element_list | valueArray" >
    {{ element.any_property }}
</button> 

Difference between res.send and res.json in Express.js

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json eventually calls res.send, but before that it:

  • respects the json spaces and json replacer app settings
  • ensures the response will have utf8 charset and application/json content-type

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

how to align img inside the div to the right?

<div style="width:300px; text-align:right;">
        <img src="someimgage.gif">
</div>

SQL subquery with COUNT help

Assuming there is a column named business:

SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.

Eclipse Build Path Nesting Errors

Try this:

From the libraries tab:

Eclipse -> right click on project name in sidebar -> configure build path -> Libraries

Remove your web app libraries:

click on "Web App Libraries" -> click "remove"

Add them back in:

click "Add Library" -> click to highlight "Web App Libraries" -> click "next" -> confirm your desired project is the selected option -> click "Finish"

Highlighting "Web App Libraries":

Highlighting "Web App Libraries"

Checkbox value true/false

Checkboxes can be really weird in JS. You're best off checking for the presence of the checked attribute. (I've had older jQuery versions return true even if checked is set to 'false'.) Once you've determined that something is checked then you can get the value from the value attribute.

Not connecting to SQL Server over VPN

On a default instance, SQL Server listens on TCP/1433 by default. This can be changed. On a named instance, unless configured differently, SQL Server listens on a dynamic TCP port. What that means is should SQL Server discover that the port is in use, it will pick another TCP port. How clients usually find the right port in the case of a named instance is by talking to the SQL Server Listener Service/SQL Browser. That listens on UDP/1434 and cannot be changed. If you have a named instance, you can configure a static port and if you have a need to use Kerberos authentication/delegation, you should.

What you'll need to determine is what port your SQL Server is listening on. Then you'll need to get with your networking/security folks to determine if they allow communication to that port via VPN. If they are, as indicated, check your firewall settings. Some systems have multiple firewalls (my laptop is an example). If so, you'll need to check all the firewalls on your system.

If all of those are correct, verify the server doesn't have an IPSEC policy that restricts access to the SQL Server port via IP address. That also could result in you being blocked.

json_encode/json_decode - returns stdClass instead of Array in PHP

    var_dump(json_decode('{"0":0}'));    // output: object(0=>0)
    var_dump(json_decode('[0]'));          //output: [0]

    var_dump(json_decode('{"0":0}', true));//output: [0]
    var_dump(json_decode('[0]', true));    //output: [0]

If you decode the json into array, information will be lost in this situation.

How to mark a build unstable in Jenkins when running shell scripts

The TextFinder is good only if the job status hasn't been changed from SUCCESS to FAILED or ABORTED. For such cases, use a groovy script in the PostBuild step:

errpattern = ~/TEXT-TO-LOOK-FOR-IN-JENKINS-BUILD-OUTPUT.*/;
manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.NEW-STATUS-TO-SET
    }
 }

See more details in a post I've wrote about it: http://www.tikalk.com/devops/JenkinsJobStatusChange/

heroku - how to see all the logs

My solution is to get complete log the first time the application start, like:

heroku logs -n 1500 > log

then add fgrep -vf to keep it up to date, like:

heroku logs -n 1500 > newlog ; fgrep -vf log newlog >> log

for continuous logging, just iterate it using watch for every x minutes (or seconds).

callback to handle completion of pipe

I found an a bit different solution of my problem regarding this context. Thought worth sharing.

Most of the example create readStreams from file. But in my case readStream has to be created from JSON string coming from a message pool.

var jsonStream = through2.obj(function(chunk, encoding, callback) {
                    this.push(JSON.stringify(chunk, null, 4) + '\n');
                    callback();
                });
// message.value --> value/text to write in write.txt 
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");

//"close" event didn't work for me!
writeStream.on( 'close', function () {
    console.log( "- done!" );
    sftp.end();
    }
);

//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
    console.log( "- done!"
        sftp.end();
        }
);

// finally this worked for me!
jsonStream.on('data', function(data) {
    var toString = Object.prototype.toString.call(data);
    console.log('type of data:', toString);
    console.log( "- file transferred" );
});

jsonStream.pipe( writeStream );

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

php REQUEST_URI

perhaps

$id = isset($_GET['id'])?$_GET['id']:null;

and

$other_var = isset($_GET['othervar'])?$_GET['othervar']:null;

Is there a command line command for verifying what version of .NET is installed

This is working for me:

@echo off
SETLOCAL ENABLEEXTENSIONS

echo Verify .Net Framework Version

for /f "delims=" %%I in ('dir /B /A:D %windir%\Microsoft.NET\Framework') do (
    for /f "usebackq tokens=1,3 delims= " %%A in (`reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\%%I" 2^>nul ^| findstr Install`) do (
        if %%A==Install (
            if %%B==0x1 (
                echo %%I
            )
        )
    )
)

echo Do you see version v4.5.2 or greater in the list?

pause

ENDLOCAL 

The 2^>nul redirects errors to vapor.

Oracle pl-sql escape character (for a " ' ")

Instead of worrying about every single apostrophe in your statement. You can easily use the q' Notation.

Example

SELECT q'(Alex's Tea Factory)' FROM DUAL;

Key Components in this notation are

  • q' which denotes the starting of the notation
  • ( an optional symbol denoting the starting of the statement to be fully escaped.
  • Alex's Tea Factory (Which is the statement itself)
  • )' A closing parenthesis with a apostrophe denoting the end of the notation.

And such that, you can stuff how many apostrophes in the notation without worrying about each single one of them, they're all going to be handled safely.

IMPORTANT NOTE

Since you used ( you must close it with )', and remember it's optional to use any other symbol, for instance, the following code will run exactly as the previous one

SELECT q'[Alex's Tea Factory]' FROM DUAL;

How to stop a function

def player(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over: 
        computer(game_over)  #We are only going to do this if check_winner comes back as False

def check_winner(): 
    check something
    #here needs to be an if / then statement deciding if the game is over, return True if over, false if not
    if score == 100:
        return True
    else:
        return False

def computer(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over:
        player(game_over) #We are only going to do this if check_winner comes back as False

game_over = False   #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over)   #Start your loops, sending in the status of game_over

Above is a pretty simple example... I made up a statement for check_winner using score = 100 to denote the game being over.

You will want to use similar method of passing score into check_winner, using game_over = check_winner(score). Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.

Check if $_POST exists

if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
    echo 'blah' . $_POST['fromPerson'];
}

How to hide 'Back' button on navigation bar on iPhone?

Add this code in your view controller

UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 300, 30)];
UIBarButtonItem *btnL = [[UIBarButtonItem alloc]initWithCustomView:myView];
self.navigationItem.leftBarButtonItem = btnL;

Can't find AVD or SDK manager in Eclipse

Try to reinstall ADT plugin on Eclipse. Check out this: Installing the Eclipse Plugin

Get paragraph text inside an element

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Where to JavaScript</title>
    <!-- JavaScript in head tag-->
    <script>
        function changeHtmlContent() {
            var content = document.getElementById('content').textContent;
            alert(content);
        }
    </script>
</head>
<body>
    <h4 id="content">Welcome to JavaScript!</h4>
    <button onclick="changeHtmlContent()">Change the content</button>
</body>

Here, we can get the text content of h4 by using:

document.getElementById('content').textContent

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html

The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:

SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Open you WAMP panel and open MySQL configuration file. In it search for "sql_mode" if you find it set it to "" else if you don't find it add sql_mode="" to the file.

Restart the MySQL server and you are good to go...

happy coding.

In C#, can a class inherit from another class and an interface?

Yes. Try:

class USBDevice : GenericDevice, IOurDevice

Note: The base class should come before the list of interface names.

Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

Hibernate Auto Increment ID

Do it as follows :-

@Id
@GenericGenerator(name="kaugen" , strategy="increment")
@GeneratedValue(generator="kaugen")
@Column(name="proj_id")
  public Integer getId() {
    return id;
 }

You can use any arbitrary name instead of kaugen. It worked well, I could see below queries on console

Hibernate: select max(proj_id) from javaproj
Hibernate: insert into javaproj (AUTH_email, AUTH_firstName, AUTH_lastName, projname,         proj_id) values (?, ?, ?, ?, ?)

Can I use Homebrew on Ubuntu?

October 2019 - Ubuntu 18.04 on WSL with oh-my-zsh; the instructions here worked perfectly -

(first, install pre-requisites using sudo apt-get install build-essential curl file git)

finally create a ~/.zprofile with the following contents: emulate sh -c '. ~/.profile'

How can I count the number of elements with same class?

$('#maindivid').find('input .inputclass').length

Video format or MIME type is not supported

In my case, this error:

Video format or MIME type is not supported.

Was due to the CSP in my .htaccess that did not allow the content to be loaded. You can check this by opening the browser's console and refreshing the page.

Once I added the domain that was hosting the video in the media-src part of that CSP, the console was clean and the video was loaded properly. Example:

Content-Security-Policy: default-src 'none'; media-src https://myvideohost.domain; script-src 'self'; style-src 'unsafe-inline' 'self'