Programs & Examples On #Thin client

Does Internet Explorer 8 support HTML 5?

IE8 beta 2 supports two APIs from HTML5: cross-document messaging and non-SQL storage.

IE8 beta 2 doesn’t implement the HTML5 parsing algorithm or the new elements (no <canvas> or <video> support).

There are also bug fixes that align IE8 better with HTML5.

How to use bluetooth to connect two iPhone?

If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.

I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:

http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes

You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

How do I create an average from a Ruby array?

class Array
  def sum 
    inject( nil ) { |sum,x| sum ? sum+x : x }
  end

  def mean 
    sum.to_f / size.to_f
  end
end

[0,4,8,2,5,0,2,6].mean

Remove HTML tags from a String

If you're writing for Android you can do this...

android.text.HtmlCompat.fromHtml(instruction, HtmlCompat.FROM_HTML_MODE_LEGACY).toString()

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

How to save an image to localStorage and display it on the next page?

I wanted to store a user's uploaded image into localStorage, so I can provide a solution for this situation. I got this to work with a combination of the accepted answer, James H. Kelly's comment, and with reference to the Mozilla docs.

I first stored the uploaded image as a Base64 string using a FileReader object:

// get user's uploaded image
const imgPath = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();

reader.addEventListener("load", function () {
    // convert image file to base64 string and save to localStorage
    localStorage.setItem("image", reader.result);
}, false);

if (imgPath) {
    reader.readAsDataURL(imgPath);
}

Then, to read the image back in from localStorage, I simply did the following:

let img = document.getElementById('image');
img.src = localStorage.getItem('image');

How to disassemble a binary executable in Linux to get the assembly code?

ht editor can disassemble binaries in many formats. It is similar to Hiew, but open source.

To disassemble, open a binary, then press F6 and then select elf/image.

Remove Datepicker Function dynamically

Well I had the same issue and tried "destroy" but that not worked for me. Then I found following work around My HTML was:

<input placeholder="Select Date" id="MyControlId" class="form-control datepicker" type="text" />

Jquery That work for me:

$('#MyControlId').data('datepicker').remove();

Where does linux store my syslog?

syslog() generates a log message, which will be distributed by syslogd.

The file to configure syslogd is /etc/syslog.conf. This file will tell your where the messages are logged.

How to change options in this file ? Here you go http://www.bo.infn.it/alice/alice-doc/mll-doc/duix/admgde/node74.html

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

how to move elasticsearch data from one server to another

You can take a snapshot of the complete status of your cluster (including all data indices) and restore them (using the restore API) in the new cluster or server.

Proper way to handle multiple forms on one page in Django

Based on this answer by @ybendana:

Again, we use is_bound to check if the form is capable of validation. See this section of the documentation:

Bound and unbound forms

A Form instance is either bound to a set of data, or unbound.

  • If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
  • If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.

We use a list of tuples for form objects and their details allowing for more extensibility and less repetition.

However, instead of overriding get(), we override get_context_data() to make inserting a new, blank instance of the form (with prefix) into the response the default action for any request. In the context of a POST request, we override the post() method to:

  1. Use the prefix to check if each form has been submitted
  2. Validate the forms that have been submitted
  3. Process the valid forms using the cleaned_data
  4. Return any invalid forms to the response by overwriting the context data
# views.py

class MultipleForms(TemplateResponseMixin, ContextMixin, View):

    form_list = [ # (context_key, formcls, prefix)
        ("form_a", FormA, "prefix_a"),
        ("form_b", FormB, "prefix_b"),
        ("form_c", FormC, "prefix_c"),
        ...
        ("form_x", FormX, "prefix_x"),
    ]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Add blank forms to context with prefixes
        for context_key, formcls, prefix in self.form_list:
            context[context_key] = formcls(prefix=prefix)
        return context

    def post(self, request, *args, **kwargs):
        # Get object and context
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        # Process forms
        for context_key, formcls, prefix in self.form_list:
            if prefix in request.POST:
                # Get the form object with prefix and pass it the POST data to \
                # validate and clean etc.
                form = formcls(request.POST, prefix=prefix)
                if form.is_bound:
                    # If the form is bound (i.e. it is capable of validation)  \
                    # check the validation
                    if form.is_valid():
                        # call the form's save() method or do whatever you     \
                        # want with form.cleaned_data
                        form.save()
                    else:
                        # overwrite context data for this form so that it is   \
                        # returned to the page with validation errors
                        context[context_key] = form
        # Pass context back to render_to_response() including any invalid forms
        return self.render_to_response(context)
        

This method allows repeated form entries on the same page, something I found did not work with @ybendana's answer.

I believe it wouldn't be masses more work to fold this method into a Mixin class, taking the form_list object as an attribute and hooking get_context_data() and post() as above.

Edit: This already exists. See this repository.

NB: This method required TemplateResponseMixin for render_to_response() and ContextMixin for get_context_data() to work. Either use these Mixins or a CBV that descends from them.

How can I avoid ResultSet is closed exception in Java?

make sure you have closed all your statments and resultsets before running rs.next. Finaly guarantees this

public boolean flowExists( Integer idStatusPrevious, Integer idStatus, Connection connection ) {
    LogUtil.logRequestMethod();

    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = connection.prepareStatement( Constants.SCRIPT_SELECT_FIND_FLOW_STATUS_BY_STATUS );
        ps.setInt( 1, idStatusPrevious );
        ps.setInt( 2, idStatus );

        rs = ps.executeQuery();

        Long count = 0L;

        if ( rs != null ) {
            while ( rs.next() ) {
                count = rs.getLong( 1 );
                break;
            }
        }

        LogUtil.logSuccessMethod();

        return count > 0L;
    } catch ( Exception e ) {
        String errorMsg = String
            .format( Constants.ERROR_FINALIZED_METHOD, ( e.getMessage() != null ? e.getMessage() : "" ) );
        LogUtil.logError( errorMsg, e );

        throw new FatalException( errorMsg );
    } finally {
        rs.close();
        ps.close();
    }

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

What's the difference between align-content and align-items?

Well I have examined them on my browser.

align-content can change a line's height for row direction or width for column when it's value is stretch, or add empty space between or around the lines for space-between, space-around, flex-start, flex-end values.

align-items can change items height or position inside the line's area. When items are not wrapped they have only one line which it's area is always stretched to the flex-box area (even if the items overflow), and align-content has no effect on a single line. So it has no effect on items that are not wrapped and only align-items can change items position or stretch them when all of them are on a single line.

However, if they are wrapped you have multiple lines and items inside each line. And if all items of each line have the same height (for row direction) that line's height will be equal to those items height and you don't see any effect by changing align-items value.

So if you want to affect items by align-items when your items are wrapped and have the same height (for row direction) first you have to use align-content with stretch value in order to expand the lines area.

In which conda environment is Jupyter executing?

The following commands will add the env in the jupyter notebook directly.

conda create --name test_env
conda activate test_env
conda install -c anaconda ipykernel
python -m ipykernel install --user --name=test_env

Now It should say, "Python [test_env]" if the language is Python and it's using an environment called test_env.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

The resolution to this problem for me, was to notify the sender that he did use the Public key that I sent them but rather someone elses. You should see the key that they used. Tell them to use the correct one.

How to get Android application id?

Else you can get id of process your application runs in:

final static int android.os.Process.myPid()
Returns the identifier of this process, which can be used with killProcess(int) and sendSignal(int, int).

Using AJAX to pass variable to PHP and retrieve those using AJAX again

Use dataType:"json" for json data

$.ajax({
     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){
         console.log(data);
     }
});  

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

Also in PHP

<?php
  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  
?>

How to retrieve a file from a server via SFTP?

Though answers above were very helpful, I've spent a day to make them work, facing various exceptions like "broken channel", "rsa key unknown" and "packet corrupt".

Below is a working reusable class for SFTP FILES UPLOAD/DOWNLOAD using JSch library.

Upload usage:

SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png", /path/to/destinationfile.png");

Download usage:

SFTPFileCopy download = new SFTPFileCopy(false, "/path/to/sourcefile.png", "/path/to/destinationfile.png");

The class code:

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import menue.Menue;

public class SFTPFileCopy1 {

    public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;
        try {
            JSch jsch = new JSch();
            //jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
            session = jsch.getSession("login", "mysite.com", 22);
            session.setPassword("password");

            UserInfo ui = new MyUserInfo() {
                public void showMessage(String message) {

                    JOptionPane.showMessageDialog(null, message);

                }

                public boolean promptYesNo(String message) {

                    Object[] options = {"yes", "no"};

                    int foo = JOptionPane.showOptionDialog(null,
                            message,
                            "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE,
                            null, options, options[0]);

                    return foo == 0;

                }
            };
            session.setUserInfo(ui);

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            sftpChannel = (ChannelSftp) channel;

            if (upload) { // File upload.
                byte[] bufr = new byte[(int) new File(sourcePath).length()];
                FileInputStream fis = new FileInputStream(new File(sourcePath));
                fis.read(bufr);
                ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);
                sftpChannel.put(fileStream, destPath);
                fileStream.close();
            } else { // File download.
                byte[] buffer = new byte[1024];
                BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
                OutputStream os = new FileOutputStream(new File(destPath));
                BufferedOutputStream bos = new BufferedOutputStream(os);
                int readCount;
                while ((readCount = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, readCount);
                }
                bis.close();
                bos.close();
            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (sftpChannel != null) {
                sftpChannel.exit();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    public static abstract class MyUserInfo
            implements UserInfo, UIKeyboardInteractive {

        public String getPassword() {
            return null;
        }

        public boolean promptYesNo(String str) {
            return false;
        }

        public String getPassphrase() {
            return null;
        }

        public boolean promptPassphrase(String message) {
            return false;
        }

        public boolean promptPassword(String message) {
            return false;
        }

        public void showMessage(String message) {
        }

        public String[] promptKeyboardInteractive(String destination,
                String name,
                String instruction,
                String[] prompt,
                boolean[] echo) {

            return null;
        }
    }
}

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

Eclipse has an error log. There you will see the complete stack trace. In my case it seems to be caused by a bad jar file combined with the java.util.zip libs not throwing a proper exception, just a NullPointerException.

Java getting the Enum name given the Enum Value

Try below code

public enum SalaryHeadMasterEnum {

    BASIC_PAY("basic pay"),
    MEDICAL_ALLOWANCE("Medical Allowance");

    private String name;

    private SalaryHeadMasterEnum(String stringVal) {
        name=stringVal;
    }
    public String toString(){
        return name;
    }

    public static String getEnumByString(String code){
        for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
            if(e.name.equals(code)) return e.name();
        }
        return null;
    }
}

Now you can use below code to retrieve the Enum by Value

SalaryHeadMasterEnum.getEnumByString("Basic Pay")

Use Below code to get ENUM as String

SalaryHeadMasterEnum.BASIC_PAY.name()

Use below code to get string Value for enum

SalaryHeadMasterEnum.BASIC_PAY.toString()

python: how to check if a line is an empty line

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

Image, saved to sdcard, doesn't appear in Android's Gallery app

Here I am sharing code that can load image in form of bitmap from and save that image on sdcard gallery in app name folder. You should follow these steps

  1. Download Image Bitmap first



     private Bitmap loadBitmap(String url) {
        try {
            InputStream in = new java.net.URL(url).openStream();
            return BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
       }


  1. Please also provide following permission in your AndroidManifest.xml file.


    uses-permission android:name="android.permission.INTERNET" 
    uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"


  1. Here is whole code that is written in Activty in which we want to perform this task.



     void saveMyImage(String appName, String imageUrl, String imageName) {

            Bitmap bmImg = loadBitmap(imageUrl);
            File filename;
            try {
                String path1 = android.os.Environment.getExternalStorageDirectory()
                        .toString();
                File file = new File(path1 + "/" + appName);
                if (!file.exists())
                    file.mkdirs();
                filename = new File(file.getAbsolutePath() + "/" + imageName
                        + ".jpg");
                FileOutputStream out = new FileOutputStream(filename);
                bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                ContentValues image = new ContentValues();
                image.put(Images.Media.TITLE, appName);
                image.put(Images.Media.DISPLAY_NAME, imageName);
                image.put(Images.Media.DESCRIPTION, "App Image");
                image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
                image.put(Images.Media.MIME_TYPE, "image/jpg");
                image.put(Images.Media.ORIENTATION, 0);
                File parent = filename.getParentFile();
                image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
                        .toLowerCase().hashCode());
                image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
                        .toLowerCase());
                image.put(Images.Media.SIZE, filename.length());
                image.put(Images.Media.DATA, filename.getAbsolutePath());
                Uri result = getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
                Toast.makeText(getApplicationContext(),
                        "File is Saved in  " + filename, Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


  1. Hope that it can solve your whole problem.

Create Windows service from executable

Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.

Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable to the system.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Convert UTC dates to local time in PHP

Answer

Convert the UTC datetime to America/Denver

// create a $dt object with the UTC timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));

// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('America/Denver'));

// format the datetime
$dt->format('Y-m-d H:i:s T');

Notes

time() returns the unix timestamp, which is a number, it has no timezone.

date('Y-m-d H:i:s T') returns the date in the current locale timezone.

gmdate('Y-m-d H:i:s T') returns the date in UTC

date_default_timezone_set() changes the current locale timezone

to change a time in a timezone

// create a $dt object with the America/Denver timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('America/Denver'));

// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('UTC'));

// format the datetime
$dt->format('Y-m-d H:i:s T');

here you can see all the available timezones

https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

here are all the formatting options

http://php.net/manual/en/function.date.php

Update PHP timezone DB (in linux)

sudo pecl install timezonedb

FtpWebRequest Download File

    private static DataTable ReadFTP_CSV()
    {
        String ftpserver = "ftp://servername/ImportData/xxxx.csv";
        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));

        reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();

        // use the stream to read file from FTP 
        StreamReader sr = new StreamReader(responseStream);
        DataTable dt_csvFile = new DataTable();

        #region Code
        //Add Code Here To Loop txt or CSV file
        #endregion

        return dt_csvFile;

    }

I hope it can help you.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

If your git was already set to something and you only copied that folder to some other location, simply run:

git config --global http.proxy ""

And git will set itself straight, after what, you can pull again :)

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Converting JSON to XML in Java

Transforming with XSLT 3.0 is the only proper way to do it, as far as I can tell. It is guaranteed to produce valid XML, and a nice structure at that. https://www.w3.org/TR/xslt/#json

Asynchronously wait for Task<T> to complete with timeout

Using Stephen Cleary's excellent AsyncEx library, you can do:

TimeSpan timeout = TimeSpan.FromSeconds(10);

using (var cts = new CancellationTokenSource(timeout))
{
    await myTask.WaitAsync(cts.Token);
}

TaskCanceledException will be thrown in the event of a timeout.

Understanding "VOLUME" instruction in DockerFile

I don't consider the use of VOLUME good in any case, except if you are creating an image for yourself and no one else is going to use it.

I was impacted negatively due to VOLUME exposed in base images that I extended and only came up to know about the problem after the image was already running, like wordpress that declares the /var/www/html folder as a VOLUME, and this meant that any files added or changed during the build stage aren't considered, and live changes persist, even if you don't know. There is an ugly workaround to define web directory in another place, but this is just a bad solution to a much simpler one: just remove the VOLUME directive.

You can achieve the intent of volume easily using the -v option, this not only make it clear what will be the volumes of the container (without having to take a look at the Dockerfile and parent Dockerfiles), but this also gives the consumer the option to use the volume or not.

It's also bad to use VOLUMES due to the following reasons, as said by this answer:

However, the VOLUME instruction does come at a cost.

  • Users might not be aware of the unnamed volumes being created, and continuing to take up storage space on their Docker host after containers are removed.
  • There is no way to remove a volume declared in a Dockerfile. Downstream images cannot add data to paths where volumes exist.

The latter issue results in problems like these.

Having the option to undeclare a volume would help, but only if you know the volumes defined in the dockerfile that generated the image (and the parent dockerfiles!). Furthermore, a VOLUME could be added in newer versions of a Dockerfile and break things unexpectedly for the consumers of the image.

Another good explanation (about the oracle image having VOLUME, which was removed): https://github.com/oracle/docker-images/issues/640#issuecomment-412647328

More cases in which VOLUME broke stuff for people:

A pull request to add options to reset properties the parent image (including VOLUME), was closed and is being discussed here (and you can see several cases of people affected adversely due to volumes defined in dockerfiles), which has a comment with a good explanation against VOLUME:

Using VOLUME in the Dockerfile is worthless. If a user needs persistence, they will be sure to provide a volume mapping when running the specified container. It was very hard to track down that my issue of not being able to set a directory's ownership (/var/lib/influxdb) was due to the VOLUME declaration in InfluxDB's Dockerfile. Without an UNVOLUME type of option, or getting rid of it altogether, I am unable to change anything related to the specified folder. This is less than ideal, especially when you are security-aware and desire to specify a certain UID the image should be ran as, in order to avoid a random user, with more permissions than necessary, running software on your host.

The only good thing I can see about VOLUME is about documentation, and I would consider it good if it only did that (without any side effects).

TL;DR

I consider that the best use of VOLUME is to be deprecated.

Interfaces — What's the point?

In this case, you could ( and probably would ) just define a Pizza base class and inherit from them. However, there are two reasons where Interfaces allow you to do things that cannot be achieved in other ways:

  1. A class can implement multiple interfaces. It just defines features that the class must have. Implementing a range of interfaces means that a class can fulfil multiple functions in different places.

  2. An interface can be defined in a hogher scope than the class or the caller. This means that you can separate the functionality, separate the project dependency, and keep the functionality in one project or class, and the implementation of this elsewhere.

One implication of 2 is that you can change the class that is being used, just requiring that it implements the appropriate interface.

ValueError: unsupported format character while forming strings

You might have a typo.. In my case I was saying %w where I meant to say %s.

How do I programmatically change file permissions?

For Windows 7 with NIO 2:

public static void main(String[] args) throws IOException {
    Path file = Paths.get("c:/touch.txt");
    AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
    System.out.println(aclAttr.getOwner());
    for (AclEntry aclEntry : aclAttr.getAcl()) {
        System.out.println(aclEntry);
    }
    System.out.println();
    
    UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
    UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
    AclEntry.Builder builder = AclEntry.newBuilder();       
    builder.setPermissions( EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE, 
            AclEntryPermission.READ_ACL, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS,
            AclEntryPermission.WRITE_ACL, AclEntryPermission.DELETE
    ));
    builder.setPrincipal(user);
    builder.setType(AclEntryType.ALLOW);
    aclAttr.setAcl(Collections.singletonList(builder.build()));
}

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

The problem was the MySQL56 service was running and it has occupied the port of WAMP MySQL.After MySQL56 service stopped the WAMP server started successfully.

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

How to add a Try/Catch to SQL Stored Procedure

See TRY...CATCH (Transact-SQL)

 CREATE PROCEDURE [dbo].[PL_GEN_PROVN_NO1]        
       @GAD_COMP_CODE  VARCHAR(2) =NULL, 
       @@voucher_no numeric =null output 
       AS         
   BEGIN  

     begin try 
         -- your proc code
     end try

     begin catch
          -- what you want to do in catch
     end catch    
  END -- proc end

How to set a ripple effect on textview or imageview on Android?

try this. This is worked for me.

android:clickable="true"
    android:focusable="true"
    android:background="?android:attr/selectableItemBackground"

Random String Generator Returning Same String

Another sample (tested in vs2013):

    Random R = new Random();
    public static string GetRandomString(int Length)
    {
        char[] ArrRandomChar = new char[Length];
        for (int i = 0; i < Length; i++)
            ArrRandomChar[i] = (char)('a' + R.Next(0, 26));
        return new string(ArrRandomChar);
    }

    string D = GetRandomString(12);

Implemented by myself.

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

In chrome to set the value you need to do YYYY-MM-DD i guess because this worked : http://jsfiddle.net/HudMe/6/

So to make it work you need to set the date as 2012-10-01

Is there an alternative sleep function in C to milliseconds?

Alternatively to usleep(), which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep():

nanosleep - high resolution sleep

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Strtotime() doesn't work with dd/mm/YYYY format

If you know it's in dd/mm/YYYY, you can do:

    $regex = '#([/d]{1,2})/([/d]{1,2})/([/d]{2,4})#';
    $match = array();
    if (preg_match($regex, $date, $match)) {
        if (strlen($match[3]) == 2) {
            $match[3] = '20' . $match[3];
        }
        return mktime(0, 0, 0, $match[2], $match[1], $match[3]);
    }
    return strtotime($date);

It will match dates in the form d/m/YY or dd/mm/YYYY (or any combination of the two)...

If you want to support more separators than just /, you can change the regex to:

    $regex = '#([\d]{1,2})[/-]([\d]{1,2})[/-]([\d]{2,4})#';

And then add any characters you want into the [/-] bit (Note, the - character needs to be last)

How to plot vectors in python using matplotlib

This may also be achieved using matplotlib.pyplot.quiver, as noted in the linked answer;

plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()

mpl output

how to pass this element to javascript onclick function and add a class to that clicked element

Use this html to get the clicked element:

<div class="row" style="padding-left:21px;">
    <ul class="nav nav-tabs" style="padding-left:40px;">
        <li class="active filter"><a href="#month" onclick="Data('month', this)">This Month</a></li>
        <li class="filter"><a href="#year" onclick="Data('year', this)">Year</a></li>
        <li class="filter"><a href="#last60" onclick="Data('last60', this)">60 Days</a></li>
        <li class="filter"><a href="#last90" onclick="Data('last90', this)">90 Days</a></li>
    </ul> 
</div>

Script:

 function Data(string, el)
 {
     $('.filter').removeClass('active');
     $(el).parent().addClass('active');
 } 

SQL Developer with JDK (64 bit) cannot find JVM

For Windows Users: If anyone downloaded a non-jre version and faced issue, then later trying with the JRE version and still facing the issue, you need to delete SQLDeveloper folder inside "%AppData%\sqldeveloper". After deleting try opening sqldeveloper.exe again.

How can I run a directive after the dom has finished rendering?

there is a ngcontentloaded event, I think you can use it

.directive('directiveExample', function(){
   return {
       restrict: 'A',
       link: function(scope, elem, attrs){

                $$window = $ $window


                init = function(){
                    contentHeight = elem.outerHeight()
                    //do the things
                }

                $$window.on('ngcontentloaded',init)

       }
   }
});

Oracle Convert Seconds to Hours:Minutes:Seconds

The following is Yet Another Way (tm) - still involves a little calculation but provides an example of using EXTRACT to pull the individual fields out of an INTERVAL:

DECLARE 
  SUBTYPE BIG_INTERVAL IS INTERVAL DAY(9) TO SECOND;

  i        BIG_INTERVAL;
  nSeconds NUMBER := 86400000;

  FUNCTION INTERVAL_TO_HMS_STRING(inv IN BIG_INTERVAL)
    RETURN VARCHAR2
  IS
    nHours    NUMBER;
    nMinutes  NUMBER;
    nSeconds  NUMBER;
    strHour_format  VARCHAR2(10) := '09';
    workInv   INTERVAL DAY(9) TO SECOND(9);
  BEGIN
    nHours := EXTRACT(HOUR FROM inv) + (EXTRACT(DAY FROM inv) * 24);
    strHour_format := TRIM(RPAD(' ', LENGTH(TRIM(TO_CHAR(ABS(nHours)))), '0') || '9');

    nMinutes := ABS(EXTRACT(MINUTE FROM inv));
    nSeconds := ABS(EXTRACT(SECOND FROM inv));

    RETURN TRIM(TO_CHAR(nHours, strHour_format)) || ':' ||
           TRIM(TO_CHAR(nMInutes, '09')) || ':' ||
           TRIM(TO_CHAR(nSeconds, '09'));
  END INTERVAL_TO_HMS_STRING;

BEGIN
  i := NUMTODSINTERVAL(nSeconds, 'SECOND');

  DBMS_OUTPUT.PUT_LINE('i (fields) = ' || INTERVAL_TO_HMS_STRING(i));
END;

The code which extracts the fields, etc, still has to contain a calculation to convert the DAY field to equivalent hours, and is not the prettiest, but wrapped up neatly in a procedure it's not too bad to use.

Share and enjoy.

LINQ - Full Outer Join

I don't know if this covers all cases, logically it seems correct. The idea is to take a left outer join and right outer join then take the union of the results.

var firstNames = new[]
{
    new { ID = 1, Name = "John" },
    new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
    new { ID = 1, Name = "Doe" },
    new { ID = 3, Name = "Smith" },
};
var leftOuterJoin =
    from first in firstNames
    join last in lastNames on first.ID equals last.ID into temp
    from last in temp.DefaultIfEmpty()
    select new
    {
        first.ID,
        FirstName = first.Name,
        LastName = last?.Name,
    };
var rightOuterJoin =
    from last in lastNames
    join first in firstNames on last.ID equals first.ID into temp
    from first in temp.DefaultIfEmpty()
    select new
    {
        last.ID,
        FirstName = first?.Name,
        LastName = last.Name,
    };
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);

This works as written since it is in LINQ to Objects. If LINQ to SQL or other, the query processor might not support safe navigation or other operations. You'd have to use the conditional operator to conditionally get the values.

i.e.,

var leftOuterJoin =
    from first in firstNames
    join last in lastNames on first.ID equals last.ID into temp
    from last in temp.DefaultIfEmpty()
    select new
    {
        first.ID,
        FirstName = first.Name,
        LastName = last != null ? last.Name : default,
    };

Getting the button into the top right corner inside the div box

#button {
    line-height: 12px;
    width: 18px;
    font-size: 8pt;
    font-family: tahoma;
    margin-top: 1px;
    margin-right: 2px;
    position: absolute;
    top: 0;
    right: 0;
}

Location of ini/config files in linux/unix?

  1. Generally system/global config is stored somewhere under /etc.
  2. User-specific config is stored in the user's home directory, often as a hidden file, sometimes as a hidden directory containing non-hidden files (and possibly more subdirectories).

Generally speaking, command line options will override environment variables which will override user defaults which will override system defaults.

How can I stop redis-server?

Type SHUTDOWN in the CLI

or

if your don't care about your data in memory, you may also type SHUTDOWN NOSAVE to force shutdown the server.

Laravel 5 - redirect to HTTPS

The answers above didn't work for me, but it appears that Deniz Turan rewrote the .htaccess in a way that works with Heroku's load balancer here: https://www.jcore.com/2017/01/29/force-https-on-heroku-using-htaccess/

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Convert Enum to String

Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString(), which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.

Paraphrasing from the xml snippet,

Passing a boxed enum to string.Format() or any other function can result in enum.ToString() being called. This will cause problems when Dotfuscating. You should not use enum.ToString(), enum.GetNames(), enum.GetName(), enum.Format() or enum.Parse() to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.

Combining two Series into a DataFrame in pandas

A simplification of the solution based on join():

df = a.to_frame().join(b)

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

One-liner if statements, how to convert this if-else-statement

return (expression) ? value1 : value2;

If value1 and value2 are actually true and false like in your example, you may as well just

return expression;

Disable cross domain web security in Firefox

While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.

For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.

phantomjs.exe --web-security=no script.js

See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes

An existing connection was forcibly closed by the remote host

I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)

java.lang.RuntimeException: Unable to start activity ComponentInfo

Your Manifest Must Change like this Activity name must Specified like ".YourActivityname"

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
     android:minSdkVersion="8" android:targetSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MainTabPanel"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MyBookActivity"  >            
    </activity>
</application>

Best way to check if a URL is valid

public function testing($Url=''){
    $ch = curl_init($Url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode >= 200 && $httpcode <= 301){
        $this->output->set_header('Access-Control-Allow-Origin: *');
        $this->output->set_content_type('application/json', 'utf-8');
        $this->output->set_status_header(200);
        $this->output->set_output(json_encode('VALID URL', JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        return;
    }else{
        $this->output->set_header('Access-Control-Allow-Origin: *');
        $this->output->set_content_type('application/json', 'utf-8');
        $this->output->set_status_header(200);
        $this->output->set_output(json_encode('INVALID URL', JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        return;
    }
}

"cannot be used as a function error"

You are using growthRate both as a variable name and a function name. The variable hides the function, and then you are trying to use the variable as if it was the function - that is not valid.

Rename the local variable.

How to connect to remote Oracle DB with PL/SQL Developer?

I am facing to this problem so many times till I have 32bit PL/SQL Developer and 64bit Oracle DB or Oracle Client.

The solution is:

  1. install a 32bit client.
  2. set PLSQL DEV-Tools-Preferencies-Oracle Home to new 32bit client Home
  3. set PLSQL DEV-Tools-Preferencies-OCI to new 32 bit home /bin/oci.dll For example: c:\app\admin\product\11.2.0\client_1\BIN\oci.dll
  4. Save and restart PLSQL DEV.

Edit or create a TNSNAMES.ORA file in c:\app\admin\product\11.2.0\client_1\NETWORK\admin folder like mentioned above.

Try with TNSPING in console like

C:>tnsping ORCL

If still have problem, set the TNS_ADMIN Enviroment properties value pointing to the folder where the TNSNAMES.ORA located, like: c:\app\admin\product\11.2.0\client_1\network\admin

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

In my case I only need to add to project's build.gradle file:

android {
  packagingOptions {
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
  }

   ...
}

Get individual query parameters from Uri

You can use:

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

MSDN

Android SeekBar setOnSeekBarChangeListener

Override all methods

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {


    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {


    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {


    }

How to catch an Exception from a thread

That's because exceptions are local to a thread, and your main thread doesn't actually see the run method. I suggest you read more about how threading works, but to quickly summarize: your call to start starts up a different thread, totally unrelated to your main thread. The call to join simply waits for it to be done. An exception that is thrown in a thread and never caught terminates it, which is why join returns on your main thread, but the exception itself is lost.

If you want to be aware of these uncaught exceptions you can try this:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Caught " + e);
    }
});

More information about uncaught exception handling can be found here.

Get JavaScript object from array of objects by value of property

I don't know why you are against a for loop (presumably you meant a for loop, not specifically for..in), they are fast and easy to read. Anyhow, here's some options.

For loop:

function getByValue(arr, value) {

  for (var i=0, iLen=arr.length; i<iLen; i++) {

    if (arr[i].b == value) return arr[i];
  }
}

.filter

function getByValue2(arr, value) {

  var result  = arr.filter(function(o){return o.b == value;} );

  return result? result[0] : null; // or undefined

}

.forEach

function getByValue3(arr, value) {

  var result = [];

  arr.forEach(function(o){if (o.b == value) result.push(o);} );

  return result? result[0] : null; // or undefined

}

If, on the other hand you really did mean for..in and want to find an object with any property with a value of 6, then you must use for..in unless you pass the names to check.

Example

function getByValue4(arr, value) {
  var o;

  for (var i=0, iLen=arr.length; i<iLen; i++) {
    o = arr[i];

    for (var p in o) {
      if (o.hasOwnProperty(p) && o[p] == value) {
        return o;
      }
    }
  }
}

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Be careful on:

 Header add Access-Control-Allow-Origin "*"

This is not judicious at all to grant access to everybody. It's preferable to allow a list of know trusted host only...

Header add Access-Control-Allow-Origin "http://aaa.example"
Header add Access-Control-Allow-Origin "http://bbb.example"
Header add Access-Control-Allow-Origin "http://ccc.example"

Regards,

How to retry after exception?

for _ in range(5):
    try:
        # replace this with something that may fail
        raise ValueError("foo")

    # replace Exception with a more specific exception
    except Exception as e:
        err = e
        continue

    # no exception, continue remainder of code
    else:
        break

# did not break the for loop, therefore all attempts
# raised an exception
else:
    raise err

My version is similar to several of the above, but doesn't use a separate while loop, and re-raises the latest exception if all retries fail. Could explicitly set err = None at the top, but not strictly necessary as it should only execute the final else block if there was an error and therefore err is set.

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid and grab them via:

var uids = $(".uid").map(function() {
    return this.value;
}).get();

Demo: http://jsfiddle.net/karim79/FtcnJ/

EDIT: say your output looks like the following (notice, IDs have changed to classes)

<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>

You can target the 'uid' relative to the clicked anchor like this:

$("a.aaf").click(function() {
    alert($(this).next('.uid').val());
});

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

How do you get the magnitude of a vector in Numpy?

Yet another alternative is to use the einsum function in numpy for either arrays:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 3.86 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 15.6 µs per loop

In [5]: %timeit np.sqrt(np.einsum('ij,ij->i',a,a))
100000 loops, best of 3: 8.71 µs per loop

or vectors:

In [5]: a = np.arange(100000)

In [6]: %timeit np.sqrt(a.dot(a))
10000 loops, best of 3: 80.8 µs per loop

In [7]: %timeit np.sqrt(np.einsum('i,i', a, a))
10000 loops, best of 3: 60.6 µs per loop

There does, however, seem to be some overhead associated with calling it that may make it slower with small inputs:

In [2]: a = np.arange(100)

In [3]: %timeit np.sqrt(a.dot(a))
100000 loops, best of 3: 3.73 µs per loop

In [4]: %timeit np.sqrt(np.einsum('i,i', a, a))
100000 loops, best of 3: 4.68 µs per loop

Make REST API call in Swift

Here is the complete code for REST API requests using NSURLSession in swift

For GET Request

 let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)


    let urlString = NSString(format: "your URL here")

    print("get wallet balance url string is \(urlString)")
    //let url = NSURL(string: urlString as String)
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString) as String)
    request.HTTPMethod = "GET"
    request.timeoutInterval = 30

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let dataTask = session.dataTaskWithRequest(request) {
        (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in

        // 1: Check HTTP Response for successful GET request
        guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
            else {
                print("error: not a valid http response")
                return
        }

        switch (httpResponse.statusCode)
        {
        case 200:

            let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
            print("response is \(response)")


            do {
                let getResponse = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments)

                EZLoadingActivity .hide()

               // }
            } catch {
                print("error serializing JSON: \(error)")
            }

            break
        case 400:

            break
        default:
            print("wallet GET request got response \(httpResponse.statusCode)")
        }
    }
    dataTask.resume()

For POST request ...

let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    let params = ["username":bindings .objectForKey("username"), "provider":"walkingcoin", "securityQuestion":securityQuestionField.text!, "securityAnswer":securityAnswerField.text!] as Dictionary<String, AnyObject>

    let urlString = NSString(format: “your URL”);
    print("url string is \(urlString)")
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 30
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")      
    request.HTTPBody  = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

    let dataTask = session.dataTaskWithRequest(request)
        {
            (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
            // 1: Check HTTP Response for successful GET request
            guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
                else {
                    print("error: not a valid http response")
                    return
            }

            switch (httpResponse.statusCode)
            {
            case 200:

                let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)


                if response == "SUCCESS"
                {

                }

            default:
                print("save profile POST request got response \(httpResponse.statusCode)")
            }
    }
    dataTask.resume()

I hope it works.

How do I check if the mouse is over an element in jQuery?

You can use is(':visible'); in jquery And for $('.item:hover') it is working in Jquery also.

this is a htm code snnipet :

    <li class="item-109 deeper parent">
<a class="root" href="/Comsopolis/index.php/matiers"><span>Matiers</span></a>
<ul>
<li class="item-110 noAff">
<a class=" item sousMenu" href="/Comsopolis/index.php/matiers/tsdi">
<span>Tsdi</span>
</a>
</li>
<li class="item-111 noAff">
<a class="item" href="/Comsopolis/index.php/matiers/reseaux">
<span>Réseaux</span>
</a>
</li>
</ul>
</li>

and this is the JS Code :

$('.menutop > li').hover(function() {//,.menutop li ul

    $(this).find('ul').show('fast');

},function() {
    if($(this).find('ul').is(':hover'))
    $(this).hide('fast');

});

 $('.root + ul').mouseleave(function() {
    if($(this).is(':visible'))
    $(this).hide('fast');

});

this what i was talking about :)

Use RSA private key to generate public key?

In most software that generates RSA private keys, including openssl's, the private key is represented as a PKCS#1 RSAPrivatekey object or some variant thereof:

A.1.2 RSA private key syntax

An RSA private key should be represented with the ASN.1 type
RSAPrivateKey:

  RSAPrivateKey ::= SEQUENCE {
      version           Version,
      modulus           INTEGER,  -- n
      publicExponent    INTEGER,  -- e
      privateExponent   INTEGER,  -- d
      prime1            INTEGER,  -- p
      prime2            INTEGER,  -- q
      exponent1         INTEGER,  -- d mod (p-1)
      exponent2         INTEGER,  -- d mod (q-1)
      coefficient       INTEGER,  -- (inverse of q) mod p
      otherPrimeInfos   OtherPrimeInfos OPTIONAL
  }

As you can see, this format has a number of fields including the modulus and public exponent and thus is a strict superset of the information in an RSA public key.

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

MacFreak's answer was extremely helpful to me. Here's some hands-on code in case it helps you.

PROBLEM - applying touchend means every time you scroll your finger over an element, it responds as if you've pressed it, even if you were just trying to scroll past.

I'm creating an effect with jQuery which fades up a line under some buttons to "highlight" the hovered button. I do not want this to mean you have to press the button twice on touch devices to follow the link.

Here are the buttons:

<a class="menu_button" href="#">
    <div class="menu_underline"></div>
</a>

I want the "menu_underline" div to fade up on mouseover and fade out on mouseout. BUT I want touch devices to be able to follow the link on one single click, not two.

SOLUTION - Here's the jQuery to make it work:

//Mouse Enter
$('.menu_button').bind('touchstart mouseenter', function(){
    $(this).find(".menu_underline").fadeIn();
});

//Mouse Out   
$('.menu_button').bind('mouseleave touchmove click', function(){
    $(this).find(".menu_underline").fadeOut();
});

Many thanks for your help on this MacFreak.

How do I assign a port mapping to an existing Docker container?

For Windows & Mac Users, there is another pretty easy and friendly way to change the mapping port:

  1. download kitematic

  2. go to the settings page of the container, on the ports tab, you can directly modify the published port there.

  3. start the container again

Convert List(of object) to List(of string)

Can you do the string conversion while the List(of object) is being built? This would be the only way to avoid enumerating the whole list after the List(of object) was created.

Ignore outliers in ggplot2 boxplot

Ipaper::geom_boxplot2 is just what you want.

# devtools::install_github('kongdd/Ipaper')
library(Ipaper)
library(ggplot2)
p <- ggplot(mpg, aes(class, hwy))
p + geom_boxplot2(width = 0.8, width.errorbar = 0.5)

enter image description here

JavaScript hard refresh of current page

Try to use:

location.reload(true);

When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info:

Call one constructor from another

If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.

public class Sample
{
    private readonly int _intField;
    public int IntProperty => _intField; 

    private void setupStuff(ref int intField, int newValue) => intField = newValue;

    public Sample(string theIntAsString)
    {
        int i = int.Parse(theIntAsString);
        setupStuff(ref _intField,i);
    }

    public Sample(int theInt) => setupStuff(ref _intField, theInt);
}

Move all files except one

If you use bash and have the extglob shell option set (which is usually the case):

mv ~/Linux/Old/!(Tux.png) ~/Linux/New/

C fopen vs open

Depends also on what flags are required to open. With respect to usage for writing and reading (and portability) f* should be used, as argued above.

But if basically want to specify more than standard flags (like rw and append flags), you will have to use a platform specific API (like POSIX open) or a library that abstracts these details. The C-standard does not have any such flags.

For example you might want to open a file, only if it exits. If you don't specify the create flag the file must exist. If you add exclusive to create, it will only create the file if it does not exist. There are many more.

For example on Linux systems there is a LED interface exposed through sysfs. It exposes the brightness of the led through a file. Writing or reading a number as a string ranging from 0-255. Of course you don't want to create that file and only write to it if it exists. The cool thing now: Use fdopen to read/write this file using the standard calls.

Alternate output format for psql

Also be sure to check out \H, which toggles HTML output on/off. Not necessarily easy to read at the console, but interesting for dumping into a file (see \o) or pasting into an editor/browser window for viewing, especially with multiple rows of relatively complex data.

What's the source of Error: getaddrinfo EAI_AGAIN?

The OP's error specifies a host (my-store.myshopify.com). The error I encountered is the same in all respects except that no domain is specified.

My solution may help others who are drawn here by the title "Error: getaddrinfo EAI_AGAIN"

I encountered the error when trying to serve a NodeJs & VueJs app from a different VM from where the code was developed originally.

The file vue.config.js read :

 module.exports = {
   devServer: {
     host: 'tstvm01',
     port: 3030,
   },
 };

When served on the original machine the start up output is :

App running at:
- Local:   http://tstvm01:3030/ 
- Network: http://tstvm01:3030/

Using the same settings on a VM tstvm07 got me a very similar error to the one the OP describes:

 INFO  Starting development server...
 10% building modules 1/1 modules 0 activeevents.js:183                              
      throw er; // Unhandled 'error' event
      ^

Error: getaddrinfo EAI_AGAIN
    at Object._errnoException (util.js:1022:11)
    at errnoException (dns.js:55:15)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)

If it ain't already obvious, changing vue.config.js to read ...

 module.exports = {
   devServer: {
     host: 'tstvm07',
     port: 3030,
   },
 };

... solved the problem.

How can I show the table structure in SQL Server query?

I was trying 'DESC table_name' but then this worked for me in psql:

select * 
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name'; 

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

jQuery UI Dialog with ASP.NET button postback

Move the dialog the right way, but you should do it only in the button opening the dialog. Here is some additional code in jQuery UI sample:

$('#create-user').click(function() {
    $("#dialog").parent().appendTo($("form:first"))
    $('#dialog').dialog('open');
})

Add your asp:button inside the dialog, and it runs well.

Note: you should change the <button> to <input type=button> to prevent postback after you click the "create user" button.

How to reset / remove chrome's input highlighting / focus border?

The simpliest way is to use something like this but note that it may not be that good.

input {
  outline: none;
}

I hope you find this useful.

Tab separated values in awk

Make sure they're really tabs! In bash, you can insert a tab using C-v TAB

$ echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED

HTML5 input type range show range value

version with editable input:

<form>
    <input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
    <input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>

http://jsfiddle.net/Xjxe6/

When do you use the "this" keyword?

I don't mean this to sound snarky, but it doesn't matter.

Seriously.

Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.

It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.

I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.

How do you count the lines of code in a Visual Studio solution?

I used Ctrl+Shift+F. Next, put a \n in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.

You can use [^\n\s]\r\n to skip blank and space-only lines (credits to Zach in the comments).

When to use single quotes, double quotes, and backticks in MySQL

(There are good answers above regarding the SQL nature of your question, but this may also be relevant if you are new to PHP.)

Perhaps it is important to mention that PHP handles single and double quoted strings differently...

Single-quoted strings are 'literals' and are pretty much WYSIWYG strings. Double-quoted strings are interpreted by PHP for possible variable-substitution (backticks in PHP are not exactly strings; they execute a command in the shell and return the result).

Examples:

$foo = "bar";
echo 'there is a $foo'; // There is a $foo
echo "there is a $foo"; // There is a bar
echo `ls -l`; // ... a directory list

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

How to get the number of threads in a Java process

java.lang.Thread.activeCount()

It will return the number of active threads in the current thread's thread group.

docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#activeCount()

A CORS POST request works from plain JavaScript, but why not with jQuery?

UPDATE: As TimK pointed out, this isn't needed with jquery 1.5.2 any more. But if you want to add custom headers or allow the use of credentials (username, password, or cookies, etc), read on.


I think I found the answer! (4 hours and a lot of cursing later)

//This does not work!!
Access-Control-Allow-Headers: *

You need to manually specify all the headers you will accept (at least that was the case for me in FF 4.0 & Chrome 10.0.648.204).

jQuery's $.ajax method sends the "x-requested-with" header for all cross domain requests (i think its only cross domain).

So the missing header needed to respond to the OPTIONS request is:

//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with

If you are passing any non "simple" headers, you will need to include them in your list (i send one more):

//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by

So to put it all together, here is my PHP:

// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: http://www.example.com');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
{
  header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  header('Access-Control-Max-Age: 604800');
  //if you need special headers
  header('Access-Control-Allow-Headers: x-requested-with');
  exit(0);
}

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I got this error when I was messing around with string and dictionary.

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required

So what you actually got to do to get dict from string is:

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}

Or in matter of security we can use literal_eval

from ast import literal_eval

Java 8 Iterable.forEach() vs foreach loop

The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)

  • The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential

  • If you want your loop to be executed in parallel you could simply write

     joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
    

    You will have to write some extra code for thread handling etc.

Note: For my answer I assumed joins implementing the java.util.Stream interface. If joins implements only the java.util.Iterable interface this is no longer true.

Android, How to limit width of TextView (and add three dots at the end of text)?

You need to add following lines into your layout for the textview

android:maxLines="1"
android:ellipsize="end"
android:singleLine="true"

Hope this works for you.

border-radius not working

For my case, I have a dropdown list in my div container, so I can not use overflow: hidden or my dropdown list will be hidden.

Inspired by this discussion: https://twitter.com/siddharthkp/status/1094821277452234752 I use border-bottom-left-radius and border-bottom-right-radius in the child element to fix this issue.

make sure you add it the correct value for each child separately

enter image description here

Get Application Name/ Label via ADB Shell or Terminal

A shell script to accomplish this:

#!/bin/bash

# Remove whitespace
function remWS {
    if [ -z "${1}" ]; then
        cat | tr -d '[:space:]'
    else
        echo "${1}" | tr -d '[:space:]'
    fi
}

for pkg in $(adb shell pm list packages -3 | cut -d':' -f2); do
    apk_loc="$(adb shell pm path $(remWS $pkg) | cut -d':' -f2 | remWS)"
    apk_name="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 $'application-label:\'(.+)\'' | remWS)"
    apk_info="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 '\b(package: .+)')"

    echo "$apk_name v$(echo $apk_info | pcregrep -io1 -e $'\\bversionName=\'(.+?)\'')"
done

Mocking member variables of a class using Mockito

You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).

If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).

Pandas: Creating DataFrame from Series

I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
Out[136]: 
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

Then you can do:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
Out[138]: 
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

Connecting to MySQL from Android with JDBC

You can't access a MySQL DB from Android natively. EDIT: Actually you may be able to use JDBC, but it is not recommended (or may not work?) ... see Android JDBC not working: ClassNotFoundException on driver

See

http://www.helloandroid.com/tutorials/connecting-mysql-database

http://www.basic4ppc.com/forum/basic4android-getting-started-tutorials/8339-connect-android-mysql-database-tutorial.html

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

http://codeoncloud.blogspot.com/2012/03/android-mysql-client.html

For most [good] users this might be fine. But imagine you get a hacker that gets a hold of your program. I've decompiled my own applications and its scary what I've seen. What if they get your username / password to your database and wreak havoc? Bad.

How do I prevent a form from being resized by the user?

There is an option in vb.net that lets you do all this.

Set <code>lock = false</code> to <code>locked = true</code>

The user wont be able to re-size the form or move it around, although there are other ways, this I think is the best.

How can I decrease the size of Ratingbar?

The original link I posted is now broken (there's a good reason why posting links only is not the best way to go). You have to style the RatingBar with either ratingBarStyleSmall or a custom style inheriting from Widget.Material.RatingBar.Small (assuming you're using Material Design in your app).

Option 1:

<RatingBar
    android:id="@+id/ratingBar"
    style="?android:attr/ratingBarStyleSmall"
    ... />

Option 2:

// styles.xml
<style name="customRatingBar"   
    parent="android:style/Widget.Material.RatingBar.Small">
    ... // Additional customizations
</style>

// layout.xml
<RatingBar
    android:id="@+id/ratingBar"
    style="@style/customRatingBar"
    ... />

How to fix missing dependency warning when using useEffect React Hook?

Just pass the function as the argument in the array of useEffect...

useEffect(() => {
   functionName()
}, [functionName])

add controls vertically instead of horizontally using flow layout

I used a BoxLayout and set its second parameter as BoxLayout.Y_AXIS and it worked for me:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

Changing every value in a hash in Ruby

In Ruby 2.1 and higher you can do

{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h

How to Detect if I'm Compiling Code with a particular Visual Studio version?

This is a little old but should get you started:

//******************************************************************************
// Automated platform detection
//******************************************************************************

// _WIN32 is used by
// Visual C++
#ifdef _WIN32
#define __NT__
#endif

// Define __MAC__ platform indicator
#ifdef macintosh
#define __MAC__
#endif

// Define __OSX__ platform indicator
#ifdef __APPLE__
#define __OSX__
#endif

// Define __WIN16__ platform indicator 
#ifdef _Windows_
#ifndef __NT__
#define __WIN16__
#endif
#endif

// Define Windows CE platform indicator
#ifdef WIN32_PLATFORM_HPCPRO
#define __WINCE__
#endif

#if (_WIN32_WCE == 300) // for Pocket PC
#define __POCKETPC__
#define __WINCE__
//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)
//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon)  
//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)
#endif

Laravel whereIn OR whereIn

You have a orWhereIn function in Laravel. It takes the same parameters as the whereIn function.

It's not in the documentation but you can find it in the laravel API. http://laravel.com/api/4.1/

That should give you this:

$query-> orWhereIn('products.value', $f);

How to compare two colors for similarity/difference

Kotlin version with how much percent do you want to match.

Method call with percent optional argument

isMatchingColor(intColor1, intColor2, 95) // should match color if 95% similar

Method body

private fun isMatchingColor(intColor1: Int, intColor2: Int, percent: Int = 90): Boolean {
    val threadSold = 255 - (255 / 100f * percent)

    val diffAlpha = abs(Color.alpha(intColor1) - Color.alpha(intColor2))
    val diffRed = abs(Color.red(intColor1) - Color.red(intColor2))
    val diffGreen = abs(Color.green(intColor1) - Color.green(intColor2))
    val diffBlue = abs(Color.blue(intColor1) - Color.blue(intColor2))

    if (diffAlpha > threadSold) {
        return false
    }

    if (diffRed > threadSold) {
        return false
    }

    if (diffGreen > threadSold) {
        return false
    }

    if (diffBlue > threadSold) {
        return false
    }

    return true
}

What is the difference between a data flow diagram and a flow chart?

Data flow diagram: A modeling notation that represents a functional decomposition of a system.

Flow chart: Step by step flow of a programe.

Create a asmx web service in C# using visual studio 2013

on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.

Ctrl+click doesn't work in Eclipse Juno

For my situation I solved this problem by going to the project properties, select "Java Build Path", and then removing source folders that does not exist anymore.

In Python, how do I convert all of the items in a list to floats?

I had to extract numbers first from a list of float strings:

   df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')

then each convert to a float:

   ad=[]
   for z in range(len(df4)):
      ad.append([float(i) for i in df4['sscore'][z]])

in the end assign all floats to a dataframe as float64:

   df4['fscore'] = np.array(ad,dtype=float)

GridView sorting: SortDirection always Ascending

Old string, but maybe my answer will help somebody.

First get your SqlDataSource as a DataView:

Private Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As DataGridSortCommandEventArgs) Handles grid1.SortCommand
    Dim dataView As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
    dataView.Sort = e.SortExpression + dataView.FieldSortDirection(Session, e.SortExpression)

    grid1.DataSourceID = Nothing
    grid1.DataSource = dataView
    grid1.DataBind()

End Sub

Then use an extension method for the sort (kind of a cheep shot, but a good start):

public static class DataViewExtensions
{
    public static string FieldSortDirection(this DataView dataView, HttpSessionState session, string sortExpression)
    {
        const string SORT_DIRECTION = "SortDirection";
        var identifier = SORT_DIRECTION + sortExpression;

        if (session[identifier] != null)
        {
            if ((string) session[identifier] == " ASC")
                session[identifier] = " DESC";
            else if ((string) session[identifier] == " DESC")
                session[identifier] = " ASC";
        }
        else
            session[identifier] = " ASC";

        return (string) session[identifier];
    }
}

How to backup MySQL database in PHP?

Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.

Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.

MySQLDump-PHP is the only library that supports:

  • output binary blobs as hex.
  • resolves view dependencies (using Stand-In tables).
  • output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
  • dumps stored procedures.
  • dumps events.
  • does extended-insert and/or complete-insert.
  • supports virtual columns from MySQL 5.7.

You can install it using composer, or just download the php file, and it is as easy as doing:

use Ifsnop\Mysqldump as IMysqldump;

try {
    $dump = new IMysqldump\Mysqldump('database', 'username', 'password');
    $dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

All the options are explained at the github page, but more or less are auto-explicative:

$dumpSettingsDefault = array(
    'include-tables' => array(),
    'exclude-tables' => array(),
    'compress' => Mysqldump::NONE,
    'init_commands' => array(),
    'no-data' => array(),
    'reset-auto-increment' => false,
    'add-drop-database' => false,
    'add-drop-table' => false,
    'add-drop-trigger' => true,
    'add-locks' => true,
    'complete-insert' => false,
    'databases' => false,
    'default-character-set' => Mysqldump::UTF8,
    'disable-keys' => true,
    'extended-insert' => true,
    'events' => false,
    'hex-blob' => true, /* faster than escaped content */
    'net_buffer_length' => self::MAXLINESIZE,
    'no-autocommit' => true,
    'no-create-info' => false,
    'lock-tables' => true,
    'routines' => false,
    'single-transaction' => true,
    'skip-triggers' => false,
    'skip-tz-utc' => false,
    'skip-comments' => false,
    'skip-dump-date' => false,
    'skip-definer' => false,
    'where' => '',
    /* deprecated */
    'disable-foreign-keys-check' => true
);

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html

What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).

How to disable action bar permanently

Below are the steps for hiding the action bar permanently:

  1. Open app/res/values/styles.xml.
  2. Look for the style element that is named "apptheme". Should look similar to <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">.
  3. Now replace the parent with any other theme that contains "NoActionBar" in its name.

    a. You can also check how a theme looks by switching to the design tab of activity_main.xml and then trying out each theme provided in the theme drop-down list of the UI.

  4. If your MainActivity extends AppCompatActivity, make sure you use an AppCompat theme.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

How to pretty print XML from Java?

Just to note that top rated answer requires the use of xerces.

If you don't want to add this external dependency then you can simply use the standard jdk libraries (which actually are built using xerces internally).

N.B. There was a bug with jdk version 1.5 see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446 but it is resolved now.,

(Note if an error occurs this will return the original text)

package com.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class XmlTest {
    public static void main(String[] args) {
        XmlTest t = new XmlTest();
        System.out.println(t.formatXml("<a><b><c/><d>text D</d><e value='0'/></b></a>"));
    }

    public String formatXml(String xml){
        try{
            Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            //serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            //serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", "2");
            Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
            StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
            serializer.transform(xmlSource, res);
            return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
        }catch(Exception e){
            //TODO log error
            return xml;
        }
    }

}

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

Leave out quotes when copying from cell

  • if formula having multi line (means having line break in formula) then copy paste will work in that way
  • if can remove multi line then no quotes will appear while copy paste.
  • else use CLEAN function as said by @greg in previous answer

String or binary data would be truncated. The statement has been terminated

In my case, I was getting this error because my table had

varchar(50)

but I was injecting 67 character long string, which resulted in thi error. Changing it to

varchar(255)

fixed the problem.

Setting TIME_WAIT TCP

A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).

The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).

So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.

That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.

That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

Init array of structs in Go

Adding this just as an addition to @jimt's excellent answer:

one common way to define it all at initialization time is using an anonymous struct:

var opts = []struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}{
    {'a', "multiple", "Usage for a", false},
    {
        shortnm: 'b',
        longnm:  "b-option",
        needArg: false,
        help:    "Usage for b",
    },
}

This is commonly used for testing as well to define few test cases and loop through them.

How to run a Command Prompt command with Visual Basic code?

You need to use CreateProcess [ http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx ]

For ex:

LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\Program Files\MyApp\" -L -S")); CreateProcess(NULL, szCmdline, /.../);

How to get size of mysql database?

First login to MySQL using

mysql -u username -p

Command to Display the size of a single Database along with its table in MB.

SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "database_name"
ORDER BY (data_length + index_length) DESC;

Change database_name to your Database

Command to Display all the Databases with its size in MB.

SELECT table_schema AS "Database", 
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" 
FROM information_schema.TABLES 
GROUP BY table_schema;

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Try the code below. It will work if you enter multiple lines in a single column.

create table  products (prod_id number , prod_desc varchar2(50));

insert into products values(1,'test first

test second

test third');

select replace(replace(prod_desc,chr(10),' '),chr(13),' ') from products  where prod_id=2; 

Output :test first test second test third

Change Image of ImageView programmatically in Android

In your XML for the image view, where you have android:background="@drawable/thumbs_down change this to android:src="@drawable/thumbs_down"

Currently it is placing that image as the background to the view and not the actual image in it.

Loop code for each file in a directory

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}

How to bind a List<string> to a DataGridView control?

This is common issue, another way is to use DataTable object

DataTable dt = new DataTable();
dt.Columns.Add("column name");

dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item 2" });
dt.Rows.Add(new object[] { "Item 3" });

This problem is described in detail here: http://www.psworld.pl/Programming/BindingListOfString

How to enable external request in IIS Express?

Combining answers in this thread, this is how I fixed it(Visual Studio 2019):

  1. Start Visual Studio as an Administrator and Run your Web Service as you normally do.

  2. Find IIS Express icon on the taskbar, right click on it then click "Show All Applications".

  3. Select your Web Service and note the config path displayed below. Click on the config file to open it for editing.

  4. Find your web service(example search for your port) in this config file then find a line like this: *:yourport:localhost

  5. Add a new line after that like this:

    :yourport:*

In this case no need to create bindings with specific ip address which could change in the future.

I hope this helps someone out there.

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

How to set the default value of an attribute on a Laravel model

You should set default values in migrations:

$table->tinyInteger('role')->default(1);

Eclipse, regular expression search and replace

Yes, ( ) captures a group. You can use it again with $i where i is the i'th capture group.

So:

search: (\w+\.someMethod\(\))

replace: ((TypeName)$1)

Hint: Ctrl + Space in the textboxes gives you all kinds of suggestions for regular expression writing.

Git clone without .git directory

Alternatively, if you have Node.js installed, you can use the following command:

npx degit GIT_REPO

npx comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit globally using npm i -g degit).

Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...

How to run eclipse in clean mode? what happens if we do so?

For clean mode: start the platform like

eclipse -clean

That's all. The platform will clear some cached OSGi bundle information, it helps or is recommended if you install new plugins manually or remove unused plugins.

It will not affect any workspace related data.

How to move all files including hidden files into parent directory via *

Alternative simpler solution is to use rsync utility:

sudo rsync -vuar --delete-after --dry-run path/subfolder/ path/

Note: Above command will show what is going to be changed. To execute the actual changes, remove --dry-run.

The advantage is that the original folder (subfolder) would be removed as well as part of the command, and when using mv examples here you still need to clean up your folders, not to mention additional headache to cover hidden and non-hidden files in one single pattern.

In addition rsync provides support of copying/moving files between remotes and it would make sure that files are copied exactly as they originally were (-a).

The used -u parameter would skip existing newer files, -r recurse into directories and -v would increase verbosity.

Should I use `import os.path` or `import os`?

As per PEP-20 by Tim Peters, "Explicit is better than implicit" and "Readability counts". If all you need from the os module is under os.path, import os.path would be more explicit and let others know what you really care about.

Likewise, PEP-20 also says "Simple is better than complex", so if you also need stuff that resides under the more-general os umbrella, import os would be preferred.

How to send and retrieve parameters using $state.go toParams and $stateParams?

I've spent a good deal of time fighting with Ionic / Angular's $state & $stateParams;

To utilize $state.go() and $stateParams you must have certain things setup and other parameters must not be present.

In my app.config() I've included $stateProvider and defined within it several states:

$stateProvider
    .state('home', {
        templateUrl: 'home',
        controller:  'homeController'
    })
    .state('view', {
        templateUrl: 'overview',
        params:      ['index', 'anotherKey'],
        controller:  'overviewController'
    })

The params key is especially important. As well, notice there are NO url keys present... utilizing stateParams and URLs do NOT mix. They are mutually exclusive to each other.

In the $state.go() call, define it as such:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })

The index and anotherKey $stateParams variables will ONLY be populated if they are first listed in the $stateController params defining key.

Within the controller, include $stateParams as illustrated:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams.index;
    var anotherKey = $stateParams.anotherKey;
});

The passed variables should be available!

Add property to an array of objects

I came up against this problem too, and in trying to solve it I kept crashing the chrome tab that was running my app. It looks like the spread operator for objects was the culprit.

With a little help from adrianolsk’s comment and sidonaldson's answer above, I used Object.assign() the output of the spread operator from babel, like so:

this.options.map(option => {
  // New properties to be added
  const newPropsObj = {
    newkey1:value1,
    newkey2:value2
  };

  // Assign new properties and return
  return Object.assign(option, newPropsObj);
});

How do I see the commit differences between branches in git?

You can easily do that with

git log master..branch-X

That will show you commits that branch-X has but master doesn't.

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

What is a superfast way to read large files line-by-line in VBA?

'you can modify above and read full file in one go and then display each line as shown below

Option Explicit

Public Function QuickRead(FName As String) As Variant
    Dim i As Integer
    Dim res As String
    Dim l As Long
    Dim v As Variant

    i = FreeFile
    l = FileLen(FName)
    res = Space(l)
    Open FName For Binary Access Read As #i
    Get #i, , res
    Close i
    'split the file with vbcrlf
    QuickRead = Split(res, vbCrLf)
End Function

Sub Test()
    ' you can replace file for "c:\writename.txt to any file name you desire
    Dim strFilePathName As String: strFilePathName = "C:\writename.txt"
    Dim strFileLine As String
    Dim v As Variant
    Dim i As Long
    v = QuickRead(strFilePathName)
    For i = 0 To UBound(v)
        MsgBox v(i)
    Next
End Sub

How to open a folder in Windows Explorer from VBA?

The easiest way is

Application.FollowHyperlink [path]

Which only takes one line!

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

If you look at the code for the $.click function, I'll bet there is a conditional statement that checks to see if the element has listeners registered for theclick event before it proceeds. Why not just get the href attribute from the link and manually change the page location?

 window.location.href = $('a').attr('href');

Here is why it doesn't click through. From the trigger function, jQuery source for version 1.3.2:

 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
 if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
     event.result = false;

 // Trigger the native events (except for clicks on links)
 if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
     this.triggered = true;
     try {
         elem[ type ]();
         // Prevent Internet Explorer from throwing an error for some hidden elements
     }
     catch (e)
     {
     }
 }

After it calls handlers (if there are any), jQuery triggers an event on the object. However it only calls native handlers for click events if the element is not a link. I guess this was done purposefully for some reason. This should be true though whether an event handler is defined or not, so I'm not sure why in your case attaching an event handler caused the native onClick handler to be called. You'll have to do what I did and step through the execution to see where it is being called.

How to disable CSS in Browser for testing purposes

The Web Developer plugin for Firefox and Chrome is able to do this

Once you have installed the plugin the option is available in the CSS menu. For example, CSS > Disable Styles > Disable All Styles

Alternatively with the developer toolbar enabled you can press Alt+Shift+A.

How can I change the date format in Java?

tl;dr

LocalDate.parse( 
    "23/01/2017" ,  
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)

2017/01/23

Avoid legacy date-time classes

The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

Using java.time

Parse the input string as a date-time object, then generate a new String object in the desired format.

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK );  // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );

Define another formatter for the output.

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

2017/01/23

By the way, consider using standard ISO 8601 formats for strings representing date-time values.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.

For fun, here is his code adapted for using the Joda-Time library.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );

Dump to console…

System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );

When run…

localDate: 2010-08-12
newDateString: 2010/08/12

Could pandas use column as index?

You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.

Here is my solution:

  1. Firstly, import pandas as pd: import pandas as pd

  2. Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.

    df = pd.read_excel('testexcel.xlsx', index_col=0)

    At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd.

  3. For visual inspection, read the dataframe using df.head() which will print the following output sc

  4. Now you can fetch the values of the desired columns of the dataframe and print it

    sc2

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

Java: How to convert String[] to List or Set

java.util.Arrays.asList(new String[]{"a", "b"})

How to permanently export a variable in Linux?

A particular example: I have Java 7 and Java 6 installed, I need to run some builds with 6, others with 7. Therefore I need to dynamically alter JAVA_HOME so that maven picks up what I want for each build. I did the following:

  • created j6.sh script which simply does export JAVA_HOME=... path to j6 install...
  • then, as suggested by one of the comments above, whenever I need J6 for a build, I run source j6.sh in that respective command terminal. By default, my JAVA_HOME is set to J7.

Hope this helps.

What is the problem with shadowing names defined in outer scopes?

I like to see a green tick in the top right corner in PyCharm. I append the variable names with an underscore just to clear this warning so I can focus on the important warnings.

data = [4, 5, 6]

def print_data(data_):
    print(data_)

print_data(data)

How can I install MacVim on OS X?

  1. Download the latest build from https://github.com/macvim-dev/macvim/releases

  2. Expand the archive.

  3. Put MacVim.app into /Applications/.

Done.

How can I calculate the difference between two dates?

NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // in seconds

where date1 and date2 are NSDate's.

Also, note the definition of NSTimeInterval:

typedef double NSTimeInterval;

Why check both isset() and !empty()

isset($vars[1]) AND !empty($vars[1]) is equivalent to !empty($vars[1]).

I prepared simple code to show it empirically.

Last row is undefined variable.

+-----------+---------+---------+----------+---------------------+
| Var value | empty() | isset() | !empty() | isset() && !empty() |
+-----------+---------+---------+----------+---------------------+
| ''        | true    | true    | false    | false               |
| ' '       | false   | true    | true     | true                |
| false     | true    | true    | false    | false               |
| true      | false   | true    | true     | true                |
| array ()  | true    | true    | false    | false               |
| NULL      | true    | false   | false    | false               |
| '0'       | true    | true    | false    | false               |
| 0         | true    | true    | false    | false               |
| 0.0       | true    | true    | false    | false               |
| undefined | true    | false   | false    | false               |
+-----------+---------+---------+----------+---------------------+

And code

$var1 = "";
$var2 = " ";
$var3 = FALSE;
$var4 = TRUE;
$var5 = array();
$var6 = null;
$var7 = "0";
$var8 = 0;
$var9 = 0.0;

function compare($var)
{
    print(var_export($var, true) . "|" .
        var_export(empty($var), true) . "|" .
        var_export(isset($var), true) . "|" .
        var_export(!empty($var), true) . "|" .
        var_export(isset($var) && !empty($var), true) . "\n");
}

for ($i = 1; $i <= 9; $i++) {
    $var = 'var' . $i;
    compare($$var);
}

@print(var_export($var10, true) . "|" .
    var_export(empty($var10), true) . "|" .
    var_export(isset($var10), true) . "|" .
    var_export(!empty($var10), true) . "|" .
    var_export(isset($var10) && !empty($var10), true) . "\n");

Undefined variable must be evaluated outside function, because function itself create temporary variable in the scope itself.

How to preview git-pull without doing fetch?

I think git fetch is what your looking for.

It will pull the changes and objects without committing them to your local repo's index.

They can be merged later with git merge.

Man Page

Edit: Further Explination

Straight from the Git- SVN Crash Course link

Now, how do you get any new changes from a remote repository? You fetch them:

git fetch http://host.xz/path/to/repo.git/ 

At this point they are in your repository and you can examine them using:

git log origin 

You can also diff the changes. You can also use git log HEAD..origin to see just the changes you don't have in your branch. Then if would like to merge them - just do:

git merge origin

Note that if you don't specify a branch to fetch, it will conveniently default to the tracking remote.

Reading the man page is honestly going to give you the best understanding of options and how to use it.

I'm just trying to do this by examples and memory, I don't currently have a box to test out on. You should look at:

git log -p //log with diff

A fetch can be undone with git reset --hard (link) , however all uncommitted changes in your tree will be lost as well as the changes you've fetched.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

It is late to answer this question but I thought It will add to the explanation.

It is happening because any where in your code you are returning two elements simultaneously.

e.g

return(
    <div id="div1"></div>
    <div id="div1"></div>
  )

It should be wrapped in a parent element. e.g

 return(
      <div id="parent">
        <div id="div1"></div>
        <div id="div1"></div>
      </div>
      )

**More Detailed Explanation**

Your below jsx code get transformed

class App extends React.Component {
  render(){
    return (
      <div>
        <h1>Welcome to React</h1>
      </div>
    );
  }
}

into this

_createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
        'div',
        null,
        React.createElement(
          'h1',
          null,
          'Welcome to React'
        )
      );
    }
  }]);

But if you do this

class App extends React.Component {
  render(){
    return (
        <h1>Welcome to React</h1>
        <div>Hi</div>
    );
  }
}

this gets converted into this(Just for illustration purpose, actually you will get error : Adjacent JSX elements must be wrapped in an enclosing tag)

_createClass(App, [{
    key: 'render',
    value: function render() {
      return React.createElement(
        'div',
        null,
       'Hi'
      ); 
    return React.createElement(
          'h1',
          null,
          'Welcome to React'
        )
    }
  }]);

In the above code you can see that you are trying to return twice from a method call, which is obviously wrong.

Edit- Latest changes in React 16 and own-wards:

If you do not want to add extra div to wrap around and want to return more than one child components you can go with React.Fragments.

React.Fragments (<React.Fragments>)are little bit faster and has less memory usage (no need to create an extra DOM node, less cluttered DOM tree).

e.g (In React 16.2.0)

render() {
  return (
    <>
       React fragments.
      <h2>A heading</h2>
      More React fragments.
      <h2>Another heading</h2>
      Even more React fragments.
    </>
  );
}

or

render() {
  return (
    <React.Fragments>
       React fragments.
      <h2>A heading</h2>
      More React fragments.
      <h2>Another heading</h2>
      Even more React fragments.
    </React.Fragments>
  );
}

or

render() {
 return [
  "Some text.",
  <h2 key="heading-1">A heading</h2>,
  "More text.",
  <h2 key="heading-2">Another heading</h2>,
  "Even more text."
 ];
}

Lightweight XML Viewer that can handle large files

TextPad has a free xmltidy plugin that pretty-prints your XML. Nice and fast, although TextPad is shareware.

How to serialize an object to XML without getting xmlns="..."?

Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is obj and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.

In VB like this:

Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")

Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True

Using ms As New MemoryStream(), _
    sw As XmlWriter = XmlWriter.Create(ms, settings), _
    sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using

in C# like this:

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

Android: Test Push Notification online (Google Cloud Messaging)

Found a very easy way to do this.

Open http://phpfiddle.org/

Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.

Press F9 or click Run.

Have fun ;)

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

For FCM, google url would be: https://fcm.googleapis.com/fcm/send

For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send

Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).

In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN

Some response codes:

Following is the description of some response codes you may receive from server.

{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id 
{ "error": "NotRegistered"} - Application was uninstalled from the device

REST vs JSON-RPC?

The fundamental problem with RPC is coupling. RPC clients become tightly coupled to service implementation in several ways and it becomes very hard to change service implementation without breaking clients:

  • Clients are required to know procedure names;
  • Procedure parameters order, types and count matters. It's not that easy to change procedure signatures(number of arguments, order of arguments, argument types etc...) on server side without breaking client implementations;
  • RPC style doesn't expose anything but procedure endpoints + procedure arguments. It's impossible for client to determine what can be done next.

On the other hand in REST style it's very easy to guide clients by including control information in representations(HTTP headers + representation). For example:

  • It's possible (and actually mandatory) to embed links annotated with link relation types which convey meanings of these URIs;
  • Client implementations do not need to depend on particular procedure names and arguments. Instead, clients depend on message formats. This creates possibility to use already implemented libraries for particular media formats (e.g. Atom, HTML, Collection+JSON, HAL etc...)
  • It's possible to easily change URIs without breaking clients as far as they only depend on registered (or domain specific) link relations;
  • It's possible to embed form-like structures in representations, giving clients the possibility to expose these descriptions as UI capabilities if the end user is human;
  • Support for caching is additional advantage;
  • Standardised status codes;

There are many more differences and advantages on the REST side.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

(HTML) Download a PDF file instead of opening them in browser when clicked

you can add the following code

_x000D_
_x000D_
<a href='http://v2.immo-facile.com/catalog/admin-v2/product_info.pdf' class='btnPdf' title='pdf'  target='_blank' type='application/pdf' >Télécharger la fiche du bien</a>
_x000D_
_x000D_
_x000D_

Loop through checkboxes and count each one checked or unchecked

You can loop through all of the checkboxes by writing $(':checkbox').each(...).

If I understand your question correctly, you're looking for the following code:

var str = "";

$(':checkbox').each(function() {
    str += this.checked ? "1," : "0,";
});

str = str.substr(0, str.length - 1);    //Remove the trailing comma

This code will loop through all of the checkboxes and add either 1, or 0, to a string.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

You can also create a writable string from a string constant by calling strdup().

For instance, this code generates a warning:

putenv("DEBUG=1");

However, the following code does not (it makes a copy of the string on the heap before passing it to putenv):

putenv(strdup("DEBUG=1"));

In this case (and perhaps in most others) turning off the warning is a bad idea -- it's there for a reason. The other alternative (making all strings writable by default) is potentially inefficient.

Listen to what the compiler is telling you!

How can I change the user on Git Bash?

Check what git remote -v returns: the account used to push to an http url is usually embedded into the remote url itself.

https://[email protected]/...

If that is the case, put an url which will force Git to ask for the account to use when pushing:

git remote set-url origin https://github.com/<user>/<repo>

Or one to use the Fre1234 account:

git remote set-url origin https://[email protected]/<user>/<repo>

Also check if you installed your Git For Windows with or without a credential helper as in this question.


The OP Fre1234 adds in the comments:

I finally found the solution.
Go to: Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to Github,
Click on them and click "Remove".

That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper output (it should be manager)

mysql server port number

This is a PDO-only visualization, as the mysql_* library is deprecated.

<?php
    // Begin Vault (this is in a vault, not actually hard-coded)
    $host="hostname";
    $username="GuySmiley";
    $password="thePassword";
    $dbname="dbname";
    $port="3306";
    // End Vault

    try {
        $dbh = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8", $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "I am connected.<br/>";

        // ... continue with your code

        // PDO closes connection at end of script
    } catch (PDOException $e) {
        echo 'PDO Exception: ' . $e->getMessage();
        exit();
    }
?>

Note that this OP Question appeared not to be about port numbers afterall. If you are using the default port of 3306 always, then consider removing it from the uri, that is, remove the port=$port; part.

If you often change ports, consider the above port usage for more maintainability having changes made to the $port variable.

Some likely errors returned from above:

PDO Exception: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
PDO Exception: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known.

In the below error, we are at least getting closer, after changing our connect information:

PDO Exception: SQLSTATE[HY000] [1045] Access denied for user 'GuySmiley'@'localhost' (using password: YES)

After further changes, we are really close now, but not quite:

PDO Exception: SQLSTATE[HY000] [1049] Unknown database 'mustard'

From the Manual on PDO Connections:

'mvn' is not recognized as an internal or external command,

Add maven directory /bin to System variables under the name Path.

To check this, you can echo %PATH%

Asynchronous Process inside a javascript for loop

_x000D_
_x000D_
var i = 0;_x000D_
var length = 10;_x000D_
_x000D_
function for1() {_x000D_
  console.log(i);_x000D_
  for2();_x000D_
}_x000D_
_x000D_
function for2() {_x000D_
  if (i == length) {_x000D_
    return false;_x000D_
  }_x000D_
  setTimeout(function() {_x000D_
    i++;_x000D_
    for1();_x000D_
  }, 500);_x000D_
}_x000D_
for1();
_x000D_
_x000D_
_x000D_

Here is a sample functional approach to what is expected here.

How do I truncate a .NET string?

Because performance testing is fun: (using linqpad extension methods)

var val = string.Concat(Enumerable.Range(0, 50).Select(i => i % 10));

foreach(var limit in new[] { 10, 25, 44, 64 })
    new Perf<string> {
        { "newstring" + limit, n => new string(val.Take(limit).ToArray()) },
        { "concat" + limit, n => string.Concat(val.Take(limit)) },
        { "truncate" + limit, n => val.Substring(0, Math.Min(val.Length, limit)) },
        { "smart-trunc" + limit, n => val.Length <= limit ? val : val.Substring(0, limit) },
        { "stringbuilder" + limit, n => new StringBuilder(val, 0, Math.Min(val.Length, limit), limit).ToString() },
    }.Vs();

The truncate method was "significantly" faster. #microoptimization

Early

  • truncate10 5788 ticks elapsed (0.5788 ms) [in 10K reps, 5.788E-05 ms per]
  • smart-trunc10 8206 ticks elapsed (0.8206 ms) [in 10K reps, 8.206E-05 ms per]
  • stringbuilder10 10557 ticks elapsed (1.0557 ms) [in 10K reps, 0.00010557 ms per]
  • concat10 45495 ticks elapsed (4.5495 ms) [in 10K reps, 0.00045495 ms per]
  • newstring10 72535 ticks elapsed (7.2535 ms) [in 10K reps, 0.00072535 ms per]

Late

  • truncate44 8835 ticks elapsed (0.8835 ms) [in 10K reps, 8.835E-05 ms per]
  • stringbuilder44 13106 ticks elapsed (1.3106 ms) [in 10K reps, 0.00013106 ms per]
  • smart-trunc44 14821 ticks elapsed (1.4821 ms) [in 10K reps, 0.00014821 ms per]
  • newstring44 144324 ticks elapsed (14.4324 ms) [in 10K reps, 0.00144324 ms per]
  • concat44 174610 ticks elapsed (17.461 ms) [in 10K reps, 0.0017461 ms per]

Too Long

  • smart-trunc64 6944 ticks elapsed (0.6944 ms) [in 10K reps, 6.944E-05 ms per]
  • truncate64 7686 ticks elapsed (0.7686 ms) [in 10K reps, 7.686E-05 ms per]
  • stringbuilder64 13314 ticks elapsed (1.3314 ms) [in 10K reps, 0.00013314 ms per]
  • newstring64 177481 ticks elapsed (17.7481 ms) [in 10K reps, 0.00177481 ms per]
  • concat64 241601 ticks elapsed (24.1601 ms) [in 10K reps, 0.00241601 ms per]

Yarn: How to upgrade yarn version using terminal?

For macOS users, if you installed yarn via brew, you can upgrade it using the below command:

brew upgrade yarn

On Linux, just run the below command at the terminal:

$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

On Windows, upgrade with Chocolatey

choco upgrade yarn

Credits: Added answers with the help of the below answers

Install opencv for Python 3.3

Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:

import cv2 as cv

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It fails "when trying to execute the function manually" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.

Import Error: No module named numpy

After trying many suggestions from various sites and similar questions, what worked for me was to uninstall all Python stuff and reinstall Anaconda only (see https://stackoverflow.com/a/38330088/1083292)

The previous Python installation I had was not only redundant but only caused me trouble.

Django - how to create a file and save it to a model's FileField?

Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.

Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).

Django 1.4.1

Python 2.7.3

#Model
class MonthEnd(models.Model):
    report = models.FileField(db_index=True, upload_to='not_used')

import csv
from os.path import join

#build and store the file
def write_csv():
    path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
    f = open(path, "w+b")

    #wipe the existing content
    f.truncate()

    csv_writer = csv.writer(f)
    csv_writer.writerow(('col1'))

    for num in range(3):
        csv_writer.writerow((num, ))

    month_end_file = MonthEnd()
    month_end_file.report.name = path
    month_end_file.save()

from my_app.models import MonthEnd

#serve it up as a download
def get_report(request):
    month_end = MonthEnd.objects.get(file_criteria=criteria)

    response = HttpResponse(month_end.report, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=report.csv'

    return response

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you've accidentally or not mixed integers with text data you should at first execute below update command (if not above alter table will fail):

UPDATE the_table SET col_name = replace(col_name, 'some_string', '');

Hexadecimal string to byte array in C

As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:

#include <stdio.h>

int main(int argc, char **argv) {
    const char hexstring[] = "DEadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];

     /* WARNING: no sanitization or error-checking whatsoever */
    for (size_t count = 0; count < sizeof val/sizeof *val; count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2;
    }

    printf("0x");
    for(size_t count = 0; count < sizeof val/sizeof *val; count++)
        printf("%02x", val[count]);
    printf("\n");

    return 0;
}

Edit

As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string "f00f5" will be evaluated as {0xf0, 0x0f, 0x05} erroneously by the above example, instead of the proper {0x0f, 0x00, 0xf5}.

Amended the example a little bit to address the comment from @MassimoCallegari

ConfigurationManager.AppSettings - How to modify and save?

I know I'm late :) But this how i do it:

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

For more information look at MSDN

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

These names refers to different ways to encode pixel image data (JPG and JPEG are the same thing, and TIFF may just enclose a jpeg with some additional metadata).

These image formats may use different compression algorithms, different color representations, different capability in carrying additional data other than the image itself, and so on.

For web applications, I'd say jpeg or gif is good enough. Jpeg is used more often due to its higher compression ratio, and gif is typically used for light weight animation where a flash (or something similar) is an over kill, or places where transparent background is desired. PNG can be used too, but I don't have much experience with that. BMP and TIFF probably are not good candidates for web applications.

Parsing huge logfiles in Node.js - read in line-by-line

I searched for a solution to parse very large files (gbs) line by line using a stream. All the third-party libraries and examples did not suit my needs since they processed the files not line by line (like 1 , 2 , 3 , 4 ..) or read the entire file to memory

The following solution can parse very large files, line by line using stream & pipe. For testing I used a 2.1 gb file with 17.000.000 records. Ram usage did not exceed 60 mb.

First, install the event-stream package:

npm install event-stream

Then:

var fs = require('fs')
    , es = require('event-stream');

var lineNr = 0;

var s = fs.createReadStream('very-large-file.csv')
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        lineNr += 1;

        // process line here and call s.resume() when rdy
        // function below was for logging memory usage
        logMemoryUsage(lineNr);

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(err){
        console.log('Error while reading file.', err);
    })
    .on('end', function(){
        console.log('Read entire file.')
    })
);

enter image description here

Please let me know how it goes!

ToggleButton in C# WinForms

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).

I end up setting the FlatStyle to flat and wrote a new Paint event handler.

 private void checkbox_paint(object sender, PaintEventArgs e)
        {
            CheckBox myCheckbox = (CheckBox)sender;
            Rectangle borderRectangle = myCheckbox.ClientRectangle;
            if (myCheckbox.Checked)
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Sunken);
            }
            else
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Raised);
            }
        }

I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.