Programs & Examples On #Notification area

for questions about the system notification area (which is often called the system tray), on topics such as examining or adjusting the tray icons in the notification area, and issuing or capturing notification messages handled by the notification area. For questions about creating or modifying a single tray icon use the trayicon tag instead.

MySQL: How to reset or change the MySQL root password?

I had to go this route on Ubuntu 16.04.1 LTS. It is somewhat of a mix of some of the other answers above - but none of them helped. I spent an hour or more trying all other suggestions from MySql website to everything on SO, I finally got it working with:

Note: while it showed Enter password for user root, I didnt have the original password so I just entered the same password to be used as the new password.

Note: there was no /var/log/mysqld.log only /var/log/mysql/error.log

Also note this did not work for me:
sudo dpkg-reconfigure mysql-server-5.7

Nor did:
sudo dpkg-reconfigure --force mysql-server-5.5

Make MySQL service directory.
sudo mkdir /var/run/mysqld

Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld

Then:

  1. kill the current mysqld pid
  2. run mysqld with sudo /usr/sbin/mysqld &
  3. run /usr/bin/mysql_secure_installation

    Output from mysql_secure_installation

    root@myServer:~# /usr/bin/mysql_secure_installation

    Securing the MySQL server deployment.

    Enter password for user root:

    VALIDATE PASSWORD PLUGIN can be used to test passwords and improve security. It checks the strength of password and allows the users to set only those passwords which are secure enough. Would you like to setup VALIDATE PASSWORD plugin?

    Press y|Y for Yes, any other key for No: no Using existing password for root. Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

    New password:

    Re-enter new password: By default, a MySQL installation has an anonymous user, allowing anyone to log into MySQL without having to have a user account created for them. This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment.

    Remove anonymous users? (Press y|Y for Yes, any other key for No) : y Success.

    Normally, root should only be allowed to connect from 'localhost'. This ensures that someone cannot guess at the root password from the network.

    Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y Success.

    By default, MySQL comes with a database named 'test' that anyone can access. This is also intended only for testing, and should be removed before moving into a production environment.

    Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y

    • Dropping test database... Success.

    • Removing privileges on test database... Success.

    Reloading the privilege tables will ensure that all changes made so far will take effect immediately.

    Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y Success.

    All done!

How to tag docker image with docker-compose

you can try:

services:
  nameis:
    container_name: hi_my
    build: .
    image: hi_my_nameis:v1.0.0

How to copy a row from one SQL Server table to another

As long as there are no identity columns you can just

INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]

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

The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

Initial size for the ArrayList

if you want to use Collections.fill(list, obj); in order to fill the list with a repeated object alternatively you can use

ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0));

the line copies 10 times 0 in to your ArrayList

How to define an empty object in PHP

to access data in a stdClass in similar fashion you do with an asociative array just use the {$var} syntax.

$myObj = new stdClass;
$myObj->Prop1 = "Something";
$myObj->Prop2 = "Something else";

// then to acces it directly

echo $myObj->{'Prop1'};
echo $myObj->{'Prop2'};

// or what you may want

echo $myObj->{$myStringVar};

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

Create intermediate folders if one doesn't exist

Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

Should have subtitle controller already set Mediaplayer error Android

A developer recently added subtitle support to VideoView.

When the MediaPlayer starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set. It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.

Short answer: Don't care about this "Exception".


Edit :

Still present in Lollipop,

If MediaPlayer is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController to the MediaPlayer.

It should not be used in production environment and may have some side effects.

static MediaPlayer getMediaPlayer(Context context){

    MediaPlayer mediaplayer = new MediaPlayer();

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
        return mediaplayer;
    }

    try {
        Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
        Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
        Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
        Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );

        Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});

        Object subtitleInstance = constructor.newInstance(context, null, null);

        Field f = cSubtitleController.getDeclaredField("mHandler");

        f.setAccessible(true);
        try {
            f.set(subtitleInstance, new Handler());
        }
        catch (IllegalAccessException e) {return mediaplayer;}
        finally {
            f.setAccessible(false);
        }

        Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);

        setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
        //Log.e("", "subtitle is setted :p");
    } catch (Exception e) {}

    return mediaplayer;
}

This code is trying to do the following from the hidden API

SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)

how to open a url in python

You have to read the data too.

Check out : http://www.doughellmann.com/PyMOTW/urllib2/ to understand it.

response = urllib2.urlopen(..)
headers = response.info()
data = response.read()

Of course, what you want is to render it in browser and aaronasterling's answer is what you want.

How to check all checkboxes using jQuery?

    <p id="checkAll">Check All</p>
<hr />
<input type="checkbox" class="checkItem">Item 1
<input type="checkbox" class="checkItem">Item 2
<input type="checkbox" class="checkItem">Item3

And jquery

$(document).on('click','#checkAll',function () {
     $('.checkItem').not(this).prop('checked', this.checked);
 });

Why do I get a "permission denied" error while installing a gem?

I had the same problem using rvm on Ubuntu, was fixed by setting the source on my terminal as a short-term solution:

source $HOME/.rvm/scripts/rvm

or

source /home/$USER/.rvm/scripts/rvm

and configure a default Ruby Version, 2.3.3 in my case.

rvm use 2.3.3 --default


And a long-term Solution is to add your source to your .bashrc file to permanently make Ubuntu look in .rvm for all the Ruby files.

Add:

source .rvm/scripts/rvm

into

$HOME/.bashrc file.

How do you format an unsigned long long int using printf?

In addition to what people wrote years ago:

  • you might get this error on gcc/mingw:

main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]

printf("%llu\n", k);

Then your version of mingw does not default to c99. Add this compiler flag: -std=c99.

How to build minified and uncompressed bundle with webpack?

Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.

Installation

npm install --save-dev unminified-webpack-plugin

Usage

var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'library.min.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^

Getting all names in an enum as a String[]

Here`s an elegant solution using Apache Commons Lang 3:

EnumUtils.getEnumList(State.class)

Although it returns a List, you can convert the list easily with list.toArray()

import error: 'No module named' *does* exist

I set the PYTHONPATH to '.' and that solved it for me.

export PYTHONPATH='.'

For a one-liner you could as easily do:

PYTHONPATH='.' your_python_script

These commands are expected to be run in a terminal

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

I've a same problem. After move machine from restore of Time Machine, on another host. There problem it's that ssh key for vagrant it's not your key, it's a key on Homestead directory.

Solution for me:

  • Use vagrant / vagrant for access ti VM of Homestead
  • vagrant ssh-config for see config of ssh

run on terminal

vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile "/Users/MYUSER/.vagrant.d/insecure_private_key"
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes

Create a new pair of SSH keys

ssh-keygen -f /Users/MYUSER/.vagrant.d/insecure_private_key

Copy content of public key

cat /Users/MYUSER/.vagrant.d/insecure_private_key.pub

On other shell in Homestead VM Machine copy into authorized_keys

vagrant@homestad:~$ echo 'CONTENT_PASTE_OF_PRIVATE_KEY' >> ~/.ssh/authorized_keys

Now can access with vagrant ssh

console.log showing contents of array object

The console object is available in Internet Explorer 8 or newer, but only if you open the Developer Tools window by pressing F12 or via the menu.

It stays available even if you close the Developer Tools window again until you close your IE.

Chorme and Opera always have an available console, at least in the current versions. Firefox has a console when using Firebug, but it may also provide one without Firebug.

In any case it is a save approach to make the use of console output optional. Here are some examples on how to do that:

if (console) {
    console.log('Hello World!');
}

if (console) console.debug('value of someVar: ' + someVar);

Count number of occurrences by month

I would add another column on the data sheet with equation =month(A2), then run the countif on that column... If you still wanted to use text month('APRIL'), you would need a lookup table to reference the name to the month number. Otherwise, just use 4 instead of April on your metric sheet.

Azure SQL Database "DTU percentage" metric

A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.

Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.

The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.

From down toward the bottom of this announcement:

For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.

As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.

Browse files and subfolders in Python

Use newDirName = os.path.abspath(dir) to create a full directory path name for the subdirectory and then list its contents as you have done with the parent (i.e. newDirList = os.listDir(newDirName))

You can create a separate method of your code snippet and call it recursively through the subdirectory structure. The first parameter is the directory pathname. This will change for each subdirectory.

This answer is based on the 3.1.1 version documentation of the Python Library. There is a good model example of this in action on page 228 of the Python 3.1.1 Library Reference (Chapter 10 - File and Directory Access). Good Luck!

How do I share variables between different .c files?

if the variable is :

int foo;

in the 2nd C file you declare:

extern int foo;

Find the directory part (minus the filename) of a full path in access 97

That's about it. There is no magic built-in function...

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

Detect if the device is iPhone X

I rely on the Status Bar Frame height to detect if it's an iPhone X :

if UIApplication.shared.statusBarFrame.height >= CGFloat(44) {
    // It is an iPhone X
}

This is for application un portrait. You could also check the size according to the device orientation. Also, on other iPhones, the Status Bar may be hidden, so the frame height is 0. On iPhone X, the Status Bar is never hidden.

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

it seems for some reason jQuery UI will try to run all code defined in buttons at definition time. It is crazy but I had the same issue and it stoped once I made this change.

if ($(this).dialog.isOpen === true) { 
    $(this).dialog("close");
}

How to clear mysql screen console in windows?

For Window 10

Use the command system cls and this will clear the MYSQL Command Line window in Windows

Launch Minecraft from command line - username and password as prefix

Those are all ways to start the standard minecraft launcher with those credentials in the text boxes.

There used to be a way to login to minecraft without the launcher using the command line, but it has since been patched.

If you want to make a custom launcher using the command line then good luck, the only way to login to the minecraft jar(IE: the way the launcher does it) is to send a post request to https://login.minecraft.net/ with the username,password,launcher version, and a RSA key. It then parses the pseudo Json, and uses the session token from that to authenticate the jar from the command line with a load of arguments.

If you are trying to make a minecraft launcher and you have no knowledge of java,http requests or json then you have no chance.

Swift

mysql query: SELECT DISTINCT column1, GROUP BY column2

Replacing FROM tablename with FROM (SELECT DISTINCT * FROM tablename) should give you the result you want (ignoring duplicated rows) for example:

SELECT name, COUNT(*)
FROM (SELECT DISTINCT * FROM Table1) AS T1
GROUP BY name

Result for your test data:

dave 2
mark 2

Trying to Validate URL Using JavaScript

var RegExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?$/);

how to change text in Android TextView

@Zordid @Iambda answer is great, but I found that if I put

mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);

in the run() method and

mHandler.postDelayed(mUpdateUITimerTask, 0);

in the onCreate method make the thing keep updating.

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

Java: Retrieving an element from a HashSet

If you know the order of elements in your Set, you can retrieve them by converting the Set to an Array. Something like this:

Set mySet = MyStorageObject.getMyStringSet();
Object[] myArr = mySet.toArray();
String value1 = myArr[0].toString();
String value2 = myArr[1].toString();

How do I kill background processes / jobs when my shell script exits?

A nice version that works under Linux, BSD and MacOS X. First tries to send SIGTERM, and if it doesn't succeed, kills the process after 10 seconds.

KillJobs() {
    for job in $(jobs -p); do
            kill -s SIGTERM $job > /dev/null 2>&1 || (sleep 10 && kill -9 $job > /dev/null 2>&1 &)

    done
}

TrapQuit() {
    # Whatever you need to clean here
    KillJobs
}

trap TrapQuit EXIT

Please note that jobs does not include grand children processes.

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

You can go to the Start Menu and search the Node.js icon and open the shell and then install anything with

install <packagename> -g

How to get Android application id?

If the whole purpose is to communicate data with some other application, use Intent's sendBroadcast methods.

How to handle an IF STATEMENT in a Mustache template?

Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}

how to read value from string.xml in android?

Only for future references.

In the String resources documentation it says:

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will >retain any rich text styling applied to the string.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

In my case:

  1. /etc/init.d/mysql stop
  2. mysqld_safe --skip-grant-tables &

(in new window)

  1. mysql -u root
  2. mysql> use mysql;
  3. mysql> update user set authentication_string=password('password') where user='root';
  4. mysql>flush privileges;
  5. mysql> quit
  6. /etc/init.d/mysql restart

A non-blocking read on a subprocess.PIPE in Python

Try the asyncproc module. For example:

import os
from asyncproc import Process
myProc = Process("myprogram.app")

while True:
    # check to see if process has ended
    poll = myProc.wait(os.WNOHANG)
    if poll != None:
        break
    # print any new output
    out = myProc.read()
    if out != "":
        print out

The module takes care of all the threading as suggested by S.Lott.

Track a new remote branch created on GitHub

If you don't have an existing local branch, it is truly as simple as:

git fetch
git checkout <remote-branch-name>

For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page, just do this:

git checkout feature/Main_Page

This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:

git checkout -t <remote>/<remote-branch-name>

If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.

Instagram API: How to get all user media?

In June 2016 Instagram made most of the functionality of their API available only to applications that have passed a review process. They still however provide JSON data through the web interface, and you can add the parameter __a=1 to a URL to only include the JSON data.

max=
while :;do
  c=$(curl -s "https://www.instagram.com/username/?__a=1&max_id=$max")
  jq -r '.user.media.nodes[]?|.display_src'<<<"$c"
  max=$(jq -r .user.media.page_info.end_cursor<<<"$c")
  jq -e .user.media.page_info.has_next_page<<<"$c">/dev/null||break
done

Edit: As mentioned in the comment by alnorth29, the max_id parameter is now ignored. Instagram also changed the format of the response, and you need to perform additional requests to get the full-size URLs of images in the new-style posts with multiple images per post. You can now do something like this to list the full-size URLs of images on the first page of results:

c=$(curl -s "https://www.instagram.com/username/?__a=1")
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename!="GraphSidecar").display_url'<<<"$c"
jq -r '.graphql.user.edge_owner_to_timeline_media.edges[]?|.node|select(.__typename=="GraphSidecar")|.shortcode'<<<"$c"|while read l;do
  curl -s "https://www.instagram.com/p/$l?__a=1"|jq -r '.graphql.shortcode_media|.edge_sidecar_to_children.edges[]?.node|.display_url'
done

To make a list of the shortcodes of each post made by the user whose profile is opened in the frontmost tab in Safari, I use a script like this:

sjs(){ osascript -e'{on run{a}','tell app"safari"to do javascript a in document 1',end} -- "$1";}

while :;do
  sjs 'o="";a=document.querySelectorAll(".v1Nh3 a");for(i=0;e=a[i];i++){o+=e.href+"\n"};o'>>/tmp/a
  sjs 'window.scrollBy(0,window.innerHeight)'
  sleep 1
done

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

how to do file upload using jquery serialization

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            

        }
    });        

});

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

How to select distinct rows in a datatable and store into an array

objds.Table1.Select(r => r.ProcessName).AsEnumerable().Distinct();

How to change the href for a hyperlink using jQuery

The simple way to do so is :

Attr function (since jQuery version 1.0)

$("a").attr("href", "https://stackoverflow.com/") 

or

Prop function (since jQuery version 1.6)

$("a").prop("href", "https://stackoverflow.com/")

Also, the advantage of above way is that if selector selects a single anchor, it will update that anchor only and if selector returns a group of anchor, it will update the specific group through one statement only.

Now, there are lot of ways to identify exact anchor or group of anchors:

Quite Simple Ones:

  1. Select anchor through tag name : $("a")
  2. Select anchor through index: $("a:eq(0)")
  3. Select anchor for specific classes (as in this class only anchors with class active) : $("a.active")
  4. Selecting anchors with specific ID (here in example profileLink ID) : $("a#proileLink")
  5. Selecting first anchor href: $("a:first")

More useful ones:

  1. Selecting all elements with href attribute : $("[href]")
  2. Selecting all anchors with specific href: $("a[href='www.stackoverflow.com']")
  3. Selecting all anchors not having specific href: $("a[href!='www.stackoverflow.com']")
  4. Selecting all anchors with href containing specific URL: $("a[href*='www.stackoverflow.com']")
  5. Selecting all anchors with href starting with specific URL: $("a[href^='www.stackoverflow.com']")
  6. Selecting all anchors with href ending with specific URL: $("a[href$='www.stackoverflow.com']")

Now, if you want to amend specific URLs, you can do that as:

For instance if you want to add proxy website for all the URLs going to google.com, you can implement it as follows:

$("a[href^='http://www.google.com']")
   .each(function()
   { 
      this.href = this.href.replace(/http:\/\/www.google.com\//gi, function (x) {
        return "http://proxywebsite.com/?query="+encodeURIComponent(x);
    });
   });

Defining static const integer members in class definition

C++ allows static const members to be defined inside a class

Nope, 3.1 §2 says:

A declaration is a definition unless it declares a function without specifying the function's body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification (7.5) and neither an initializer nor a functionbody, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), or a using-directive (7.3.4).

How to unset a JavaScript variable?

Note that delete returns true when it was successful.

Update 2021: tested on Chrome 88 and Firefox 84:

implicit_global = 1;
delete implicit_global; // true

window.explicit_global = 1;
delete explicit_global; // true

const _object = {property: 1};
delete _object.property; // true

function_set = function() {};
delete function_set; // true

function function_declaration() {};
delete function_declaration; // false

(function () {
    var _var = 1;
    console.log(delete _var); // false
    console.log(_var); // 1
})()

(function () {
    let _let = 1;
    console.log(delete _let); // false
    console.log(_let); // 1
})()

(function () {
    const _const = 1;
    console.log(delete _const); // false
    console.log(_const); // 1
})()

Original answer is no longer relevant. tested in 2015 on Chrome 52:

implicit_global = 1;
window.explicit_global = 1;
function_set = function() {};
function function_dec() { };
var declared_variable = 1;

delete implicit_global; // true, tested on Chrome 52
delete window.explicit_global; // true, tested on Chrome 52
delete function_set; // true, tested on Chrome 52
delete function_dec; // true, tested on Chrome 52
delete declared_variable; // true, tested on Chrome 52

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Handling exceptions from Java ExecutorService tasks

WARNING: It should be noted that this solution will block the calling thread.


If you want to process exceptions thrown by the task, then it is generally better to use Callable rather than Runnable.

Callable.call() is permitted to throw checked exceptions, and these get propagated back to the calling thread:

Callable task = ...
Future future = executor.submit(task);
try {
   future.get();
} catch (ExecutionException ex) {
   ex.getCause().printStackTrace();
}

If Callable.call() throws an exception, this will be wrapped in an ExecutionException and thrown by Future.get().

This is likely to be much preferable to subclassing ThreadPoolExecutor. It also gives you the opportunity to re-submit the task if the exception is a recoverable one.

SQL select join: is it possible to prefix all columns as 'prefix.*'?

It seems the answer to your question is no, however one hack you can use is to assign a dummy column to separate each new table. This works especially well if you're looping through a result set for a list of columns in a scripting language such as Python or PHP.

SELECT '' as table1_dummy, table1.*, '' as table2_dummy, table2.*, '' as table3_dummy, table3.* FROM table1
JOIN table2 ON table2.table1id = table1.id
JOIN table3 ON table3.table1id = table1.id

I realize this doesn't answer your question exactly, but if you're a coder this is a great way to separate tables with duplicate column names. Hope this helps somebody.

Send JSON via POST in C# and Receive the JSON returned?

I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.

(Edit: Adding JSON from question for clarity)

{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

With two classes representing the JSON-Structure you posted that may look like this:

public class Credentials
{
    [JsonProperty("agent")]
    public Agent Agent { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }
}

public class Agent
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("version")]
    public int Version { get; set; }
}

you could have a method like this, which would do your POST request:

var payload = new Credentials { 
    Agent = new Agent { 
        Name = "Agent Name",
        Version = 1 
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
};

// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);

    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();

        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
}

Detecting negative numbers

Can be easily achieved with a ternary operator.

$is_negative = $profitloss < 0 ? true : false;

How to do vlookup and fill down (like in Excel) in R?

You could use mapvalues() from the plyr package.

Initial data:

dat <- data.frame(HouseType = c("Semi", "Single", "Row", "Single", "Apartment", "Apartment", "Row"))

> dat
  HouseType
1      Semi
2    Single
3       Row
4    Single
5 Apartment
6 Apartment
7       Row

Lookup / crosswalk table:

lookup <- data.frame(type_text = c("Semi", "Single", "Row", "Apartment"), type_num = c(1, 2, 3, 4))
> lookup
  type_text type_num
1      Semi        1
2    Single        2
3       Row        3
4 Apartment        4

Create the new variable:

dat$house_type_num <- plyr::mapvalues(dat$HouseType, from = lookup$type_text, to = lookup$type_num)

Or for simple replacements you can skip creating a long lookup table and do this directly in one step:

dat$house_type_num <- plyr::mapvalues(dat$HouseType,
                                      from = c("Semi", "Single", "Row", "Apartment"),
                                      to = c(1, 2, 3, 4))

Result:

> dat
  HouseType house_type_num
1      Semi              1
2    Single              2
3       Row              3
4    Single              2
5 Apartment              4
6 Apartment              4
7       Row              3

How can I return the difference between two lists?

Here is a generic solution for this problem.

public <T> List<T> difference(List<T> first, List<T> second) {
    List<T> toReturn = new ArrayList<>(first);
    toReturn.removeAll(second);
    return toReturn;
}

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

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

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

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

  render () {
    const children = [];

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

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

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

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

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

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

Setting an int to Infinity in C++

You can also use INT_MAX:

http://www.cplusplus.com/reference/climits/

it's equivalent to using numeric_limits.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

You can use this function instead if curl is installed on your system:

function get_url_contents($url){  
  if (function_exists('file_get_contents')) {  
    $result = @file_get_contents($url);  
  }  
  if ($result == '') {  
    $ch = curl_init();  
    $timeout = 30;  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
    $result = curl_exec($ch);  
    curl_close($ch);  
  }  

  return $result;  
}

Import Android volley to Android Studio

After putting compile 'com.android.volley:volley:1.0.0' into your build.gradle (Module) file under dependencies, it will not work immediately, you will have to restart Android Studio first!

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

Input Type image submit form value?

To submit a form you could use:

<input type="submit">

or

<input type="button"> + Javascript 

I never heard of such a crazy guy to try to send a form using a image or a checkbox as you want :))

How to change sa password in SQL Server 2008 express?

This may help you to reset your sa password for SQL 2008 and 2012

EXEC sp_password NULL, 'yourpassword', 'sa'

Adding two numbers concatenates them instead of calculating the sum

  <input type="text" name="num1" id="num1" onkeyup="sum()">
  <input type="text" name="num2" id="num2" onkeyup="sum()">
  <input type="text" name="num2" id="result">

  <script>
     function sum()
     {

        var number1 = document.getElementById('num1').value;
        var number2 = document.getElementById('num2').value;

        if (number1 == '') {
           number1 = 0
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }
        else if(number2 == '')
        {
           number2 = 0;
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }
        else
        {
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }

     }
  </script>

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

Read Numeric Data from a Text File in C++

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

Using ALTER to drop a column if it exists in MySQL

For MySQL, there is none: MySQL Feature Request.

Allowing this is arguably a really bad idea, anyway: IF EXISTS indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.

But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.

MariaDB also supports the following starting with 10.0.2:

DROP [COLUMN] [IF EXISTS] col_name 

i. e.

ALTER TABLE my_table DROP IF EXISTS my_column;

But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

Storage permission error in Marshmallow

Before starting your download check your runtime permissions and if you don't have permission the request permissions like this method

requestStoragePermission()

private void requestStoragePermission(){
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
                android.Manifest.permission.READ_EXTERNAL_STORAGE))
        {

        }

        ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            STORAGE_PERMISSION_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, 
                @NonNull String[] permissions, 
                @NonNull int[] grantResults) {

    if(requestCode == STORAGE_PERMISSION_CODE){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        }
        else{
            Toast.makeText(this,
                           "Oops you just denied the permission", 
                           Toast.LENGTH_LONG).show();
        }
    }
}

How to parse freeform street/postal address out of text, and into components

libpostal: an open-source library to parse addresses, training with data from OpenStreetMap, OpenAddresses and OpenCage.

https://github.com/openvenues/libpostal (more info about it)

Other tools/services:

How to open every file in a folder

The code below reads for any text files available in the directory which contains the script we are running. Then it opens every text file and stores the words of the text line into a list. After store the words we print each word line by line

import os, fnmatch

listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        _fileName = open(entry,"r")
        if _fileName.mode == "r":
            content = _fileName.read()
            contentList = content.split(" ")
            for i in contentList:
                if i != '\n' and i != "\r\n":
                    store.append(i)

for i in store:
    print(i)

What is the difference between utf8mb4 and utf8 charsets in MySQL?

MySQL added this utf8mb4 code after 5.5.3, Mb4 is the most bytes 4 meaning, specifically designed to be compatible with four-byte Unicode. Fortunately, UTF8MB4 is a superset of UTF8, except that there is no need to convert the encoding to UTF8MB4. Of course, in order to save space, the general use of UTF8 is enough.

The original UTF-8 format uses one to six bytes and can encode 31 characters maximum. The latest UTF-8 specification uses only one to four bytes and can encode up to 21 bits, just to represent all 17 Unicode planes. UTF8 is a character set in Mysql that supports only a maximum of three bytes of UTF-8 characters, which is the basic multi-text plane in Unicode.

To save 4-byte-long UTF-8 characters in Mysql, you need to use the UTF8MB4 character set, but only 5.5. After 3 versions are supported (View version: Select version ();). I think that in order to get better compatibility, you should always use UTF8MB4 instead of UTF8. For char type data, UTF8MB4 consumes more space and, according to Mysql's official recommendation, uses VARCHAR instead of char.

In MariaDB utf8mb4 as the default CHARSET when it not set explicitly in the server config, hence COLLATE utf8mb4_unicode_ci is used.

Refer MariaDB CHARSET & COLLATE Click

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ASP.NET MVC ActionLink and post method

Calling $.post() won't work as it is Ajax based. So a hybrid method needs to be used for this purpose.

Following is the solution which is working for me.

Steps: 1. Create URL for href which calls the a method with url and parameter 2. Call normal POST using JavaScript method

Solution:

In .cshtml:

<a href="javascript:(function(){$.postGo( '@Url.Action("View")', { 'id': @receipt.ReceiptId  } );})()">View</a>

Note: the anonymous method should be wrapped in (....)() i.e.

(function() {
    //code...
})();

postGo is defined as below in JavaScript. Rest are simple..

@Url.Action("View") creates url for the call

{ 'id': @receipt.ReceiptId } creates parameters as object which is in-turn converted to POST fields in postGo method. This can be any parameter as you require

In JavaScript:

(function ($) {
    $.extend({
        getGo: function (url, params) {
            document.location = url + '?' + $.param(params);
        },
        postGo: function (url, params) {
            var $form = $("<form>")
                .attr("method", "post")
                .attr("action", url);
            $.each(params, function (name, value) {
                $("<input type='hidden'>")
                    .attr("name", name)
                    .attr("value", value)
                    .appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);

Reference URLs which I have used for postGo

Non-ajax GET/POST using jQuery (plugin?)

http://nuonical.com/jquery-postgo-plugin/

Getting Chrome to accept self-signed localhost certificate

  1. Add the CA certificate in the trusted root CA Store.

  2. Go to chrome and enable this flag!

chrome://flags/#allow-insecure-localhost

At last, simply use the *.me domain or any valid domains like *.com and *.net and maintain them in the host file. For my local devs, I use *.me or *.com with a host file maintained as follows:

  1. Add to host. C:/windows/system32/drivers/etc/hosts

    127.0.0.1 nextwebapp.me

Note: If the browser is already opened when doing this, the error will keep on showing. So, please close the browser and start again. Better yet, go incognito or start a new session for immediate effect.

How to send 500 Internal Server Error error from a PHP script

You can just put:

header("HTTP/1.0 500 Internal Server Error");

inside your conditions like:

if (that happened) {
    header("HTTP/1.0 500 Internal Server Error");
}

As for the database query, you can just do that like this:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

You should remember that you have to put this code before any html tag (or output).

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

.NET Format a string with fixed spaces

You've been shown PadLeft and PadRight. This will fill in the missing PadCenter.

public static class StringUtils
{
    public static string PadCenter(this string s, int width, char c)
    {
        if (s == null || width <= s.Length) return s;

        int padding = width - s.Length;
        return s.PadLeft(s.Length + padding / 2, c).PadRight(width, c);
    }
}

Note to self: don't forget to update own CV: "One day, I even fixed Joel Coehoorn's code!" ;-D -Serge

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Conversion failed when converting date and/or time from character string while inserting datetime

This is how to easily convert from an ISO string to a SQL-Server datetime:

INSERT INTO time_data (ImportateDateTime) VALUES (CAST(CONVERT(datetimeoffset,'2019-09-13 22:06:26.527000') AS datetime))

Source https://www.sqlservercurry.com/2010/04/convert-character-string-iso-date-to.html

What does the ??!??! operator do in C?

Well, why this exists in general is probably different than why it exists in your example.

It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.

This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:

{ | } ~ 

The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.

Your example is actually two of ??!, each meaning |, so the result is ||.

However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.

It sure worked, it led to a wildly popular SO question.

ASR-33 Teletype

                                            ASR-33 Teletype


1. For that matter, the trigraphs were invented by the ANSI committee, which first met after C become a runaway success, so none of the original C code or coders would have used them.

What is the difference between POST and GET?

If you are working RESTfully, GET should be used for requests where you are only getting data, and POST should be used for requests where you are making something happen.

Some examples:

  • GET the page showing a particular SO question

  • POST a comment

  • Send a POST request by clicking the "Add to cart" button.

Syntax for a for loop in ruby

What? From 2010 and nobody mentioned Ruby has a fine for /in loop (it's just nobody uses it):

ar = [1,2,3,4,5,6]
for item in ar
  puts item
end

Adding placeholder attribute using Jquery

you just need to put this

($('#{{ form.email.id_for_label }}').attr("placeholder","Work email address"));

($('#{{ form.password1.id_for_label }}').attr("placeholder","Password"));

MVC [HttpPost/HttpGet] for Action

In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution

[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
   // Login logic
}

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

TypeError: worker() takes 0 positional arguments but 1 was given

You forgot to add self as a parameter to the function worker() in the class KeyStatisticCollection.

How to get the currently logged in user's user id in Django?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

The current user is in request object, you can get it by:

def sample_view(request):
    current_user = request.user
    print current_user.id

request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

Spring RestTemplate timeout

Here is a really simple way to set the timeout:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 5000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
      new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}

Is it possible to get the index you're sorting over in Underscore.js?

I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.

In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:

var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });

0 I
1 like
2 pancakes
3 a
4 lot
5 .

On the other hand, if the list argument is an object the iteratee will take a list element and a key:

var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });

name mike
lastname doe
age 21

For reference this is the _.each() code from Underscore.js 1.8.3

_.each = _.forEach = function(obj, iteratee, context) {
   iteratee = optimizeCb(iteratee, context);
   var i, length;
   if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
         iteratee(obj[i], i, obj);
      }
   } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
         iteratee(obj[keys[i]], keys[i], obj);
      }
   }
   return obj;
};

Angular routerLink does not navigate to the corresponding component

For anyone having this error after spliting modules check your routes, the following happened to me:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '**', redirectTo: 'home' } // ? This was my mistake
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Move { path: '**', redirectTo: 'home' } to your AppRoutingModule:

public-routing.module.ts:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'home', component: HomeComponent },
    { path: 'privacy-policy', component: PrivacyPolicyComponent },
    { path: 'credits', component: CreditsComponent },
    { path: 'contact', component: ContactComponent },
    { path: 'news', component: NewsComponent },
    { path: 'presentation', component: PresentationComponent }
]

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class PublicRoutingModule { }

app-routing.module.ts:

const routes: Routes = [
    { path: '**', redirectTo: 'home' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

How can I match on an attribute that contains a certain string?

I came here searching solution for Ranorex Studio 9.0.1. There is no contains() there yet. Instead we can use regex like:

div[@class~'atag']

Android emulator: could not get wglGetExtensionsStringARB error

When you create the emulator, you need to choose properties CPU/ABI is Intel Atom (installed it in SDK manager )

How to pause for specific amount of time? (Excel/VBA)

Use the Wait method:

Application.Wait Now + #0:00:01#

or (for Excel 2010 and later):

Application.Wait Now + #12:00:01 AM#

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Python Library Path

You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:

import sys
sys.path.append('/home/user/python-libs')

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

How to add Active Directory user group as login in SQL Server

Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.

Script to get the HTTP status code of a list of urls?

This relies on widely available wget, present almost everywhere, even on Alpine Linux.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

The explanations are as follow :

--quiet

Turn off Wget's output.

Source - wget man pages

--spider

[ ... ] it will not download the pages, just check that they are there. [ ... ]

Source - wget man pages

--server-response

Print the headers sent by HTTP servers and responses sent by FTP servers.

Source - wget man pages

What they don't say about --server-response is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.

The output sent to standard input, we can pipe it to awk to extract the HTTP status code. That code is :

  • the second ($2) non-blank group of characters: {$2}
  • on the very first line of the header: NR==1

And because we want to print it... {print $2}.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

CSS Transition doesn't work with top, bottom, left, right

Something that is not relevant for the OP, but maybe for someone else in the future:

For pixels (px), if the value is "0", the unit can be omitted: right: 0 and right: 0px both work.

However I noticed that in Firefox and Chrome this is not the case for the seconds unit (s). While transition: right 1s ease 0s works, transition: right 1s ease 0 (missing unit s for last value transition-delay) does not (it does work in Edge however).

In the following example, you'll see that right works for both 0px and 0, but transition only works for 0s and it doesn't work with 0.

_x000D_
_x000D_
#box {_x000D_
    border: 1px solid black;_x000D_
    height: 240px;_x000D_
    width: 260px;_x000D_
    margin: 50px;_x000D_
    position: relative;_x000D_
}_x000D_
.jump {_x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    color: white;_x000D_
    padding: 5px;_x000D_
}_x000D_
#jump1 {_x000D_
    background-color: maroon;_x000D_
    top: 0px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump2 {_x000D_
    background-color: green;_x000D_
    top: 60px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0s;_x000D_
}_x000D_
#jump3 {_x000D_
    background-color: blue;_x000D_
    top: 120px;_x000D_
    right: 0px;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#jump4 {_x000D_
    background-color: gray;_x000D_
    top: 180px;_x000D_
    right: 0;_x000D_
    transition: right 1s ease 0;_x000D_
}_x000D_
#box:hover .jump {_x000D_
    right: 50px;_x000D_
}
_x000D_
<div id="box">_x000D_
  <div class="jump" id="jump1">right: 0px<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump2">right: 0<br>transition: right 1s ease 0s</div>_x000D_
  <div class="jump" id="jump3">right: 0px<br>transition: right 1s ease 0</div>_x000D_
  <div class="jump" id="jump4">right: 0<br>transition: right 1s ease 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make layout with View fill the remaining space?

In case if < TEXT VIEW > is placed in LinearLayout, set the Layout_weight proprty of < and > to 0 and 1 for TextView.
In case of RelativeLayout align < and > to left and right and set "Layout to left of" and "Layout to right of" property of TextView to ids of < and >

CORS Access-Control-Allow-Headers wildcard being ignored?

Those CORS headers do not support * as value, the only way is to replace * with this:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Example (CORS Included):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

F.A.Q:

  • Why Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methods values are super long?

    Those do not support the * syntax, so I've collected the most common (and exotic) headers from around the web, in various formats #1 #2 #3 (and I will update the list from time to time)

  • Why do you use Header unset ______ syntax?

    GoDaddy servers (which my website is hosted on..) have a weird bug where if the headers are already set, the previous value will join the existing one.. (instead of replacing it) this way I "pre-clean" existing values (really just a a quick && dirty solution)

  • Is it safe for me to use 'as-is'?

    Well.. mostly the answer would be YES since the .htaccess is limiting the headers to the scripts (PHP, HTML, ...) and resources (.JPG, .JS, .CSS) served from the following "folder"-location. You optionally might want to remove the Access-Control-Allow-Methods lines. Also Connection, Time-Zone, Keep-Alive and DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Options and X-Xss-Protection are just a suggestion I'm using for my online-service.. feel free to remove those too...

taken from my comment above

Table scroll with HTML and CSS

Adds a fading gradient to an overflowing HTML table element to better indicate there is more content to be scrolled.

  • Table with fixed header
  • Overflow scroll gradient
  • Custom scrollbar

See the live example below:

_x000D_
_x000D_
$("#scrolltable").html("<table id='cell'><tbody></tbody></table>");_x000D_
$("#cell").append("<thead><tr><th><div>First col</div></th><th><div>Second col</div></th></tr></thead>");_x000D_
_x000D_
for (var i = 0; i < 40; i++) {_x000D_
  $("#scrolltable > table > tbody").append("<tr><td>" + "foo" + "</td><td>" + "bar" + "</td></tr>");_x000D_
}
_x000D_
/* Table with fixed header */_x000D_
_x000D_
table,_x000D_
thead {_x000D_
  width: 100%;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
#scrolltable {_x000D_
  margin-top: 50px;_x000D_
  height: 120px;_x000D_
  overflow: auto;_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#scrolltable table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
#scrolltable tr:nth-child(even) {_x000D_
  background: #EEE;_x000D_
}_x000D_
_x000D_
#scrolltable th div {_x000D_
  position: absolute;_x000D_
  margin-top: -30px;_x000D_
}_x000D_
_x000D_
_x000D_
/* Custom scrollbar */_x000D_
_x000D_
::-webkit-scrollbar {_x000D_
  width: 8px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-track {_x000D_
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);_x000D_
  border-radius: 10px;_x000D_
}_x000D_
_x000D_
::-webkit-scrollbar-thumb {_x000D_
  border-radius: 10px;_x000D_
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
_x000D_
/* Overflow scroll gradient */_x000D_
_x000D_
.overflow-scroll-gradient {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.overflow-scroll-gradient::after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 240px;_x000D_
  height: 25px;_x000D_
  background: linear-gradient( rgba(255, 255, 255, 0.001), white);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="overflow-scroll-gradient">_x000D_
  <div id="scrolltable">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

Flutter Circle Design

I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.

To create circles

  new BoxDecoration(
    color: effectiveBackgroundColor,
    image: backgroundImage != null
      ? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
      : null,
    shape: BoxShape.circle,
  ),

and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.

How to keep :active css style after click a button

In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.

You should be able to add this code:

<script>
 $( ".et-pb-icon" ).click(function() {
 $( this ).toggleClass( "active" );
 });
</script>

into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.

Then, you should be able to style your class to what ever you need.

How do I get the day month and year from a Windows cmd.exe script?

The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file

Wscript.Echo("set Year=" & DatePart("yyyy", Date))
Wscript.Echo("set Month=" & DatePart("m", Date))
Wscript.Echo("set Day=" & DatePart("d", Date))

and this batch snippet

for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
echo %Year%-%Month%-%Day%

should work, though.

While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

ES6 modules implementation, how to load a json file

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28

How can I stop .gitignore from appearing in the list of untracked files?

This seems to only work for your current directory to get Git to ignore all files from the repository.

update this file

.git/info/exclude 

with your wild card or filename

*pyc
*swp
*~

Check if a value is in an array (C#)

    public static bool Contains(Array a, object val)
    {
        return Array.IndexOf(a, val) != -1;
    }

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

These are identical for printf but different for scanf. For printf, both %d and %i designate a signed decimal integer. For scanf, %d and %i also means a signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal.

Perl: function to trim string leading and trailing whitespace

I also use a positive lookahead to trim repeating spaces inside the text:

s/^\s+|\s(?=\s)|\s+$//g

What does AND 0xFF do?

The byte1 & 0xff ensures that only the 8 least significant bits of byte1 can be non-zero.

if byte1 is already an unsigned type that has only 8 bits (e.g., char in some cases, or unsigned char in most) it won't make any difference/is completely unnecessary.

If byte1 is a type that's signed or has more than 8 bits (e.g., short, int, long), and any of the bits except the 8 least significant is set, then there will be a difference (i.e., it'll zero those upper bits before oring with the other variable, so this operand of the or affects only the 8 least significant bits of the result).

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

Hope it helps someone on earth. In my case jQuery and $ were available but not when the plugin bootstrapped so I wrapped everything inside a setTimeout. Wrapping inside setTimeout helped me fix the error:

setTimeout(() => {
    /** Your code goes here */

    !function(t, e) {

    }(window);

})

Print the data in ResultSet along with column names

For what you are trying to do, instead of PreparedStatement you can use Statement. Your code may be modified as-

String sql = "SELECT column_name from information_schema.columns where table_name='suppliers';";

Statement s  = connection.createStatement();
ResultSet rs = s.executeQuery(sql);

Hope this helps.

Python base64 data decode

Well, I assume you are not on Interactive Mode and you used this code to decode your string:

import base64
your_string = 'Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH3ES2lxFDlgfuRIuPbEOWB/9EA9SqQ5YIEUIFJtxDlggjAAAAAEOWCDVDDMm3Q5YIR0N5wOtDlghZQ4GkeEOWCGtDD0CbQ5YIfQAAAABDlgiOAAAAAEOWCKAAAAAAQ5YIsgAAAABDlob5AAAAAEOWhwsAAAAAQ5aHHQAAAABDlocvAAAAAEOWh0FBC+dQQ5aHU0NJ9WdDlodlQ9RK6kOWh3dEDRdFQ5aHiUQARjZDloebQ5xn3kOWh61C1TYMQ5aHvwAAAABDlofRAAAAAEOWh+MAAAAAQ5aH9QAAAABDnFl9AAAAAEOcWZAAAAAAQ5xZpAAAAABDnFm3AAAAAEOcWctDH72jQ5xZ3kNDentDnFnxQ0QCp0OcWgVDK52XQ5xaGEMDUuNDnFosAAAAAEOcWj8AAAAAQ5xaUwAAAABDnFpmAAAAAEOcWnkAAAAAQ5xajQAAAABDnFqgAAAAAEOcWrRBnlHwQ5xax0MvO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YpAAAAAAERFin4AAAAAREWKvAAAAABERYr6AAAAAERFjiAAAAAAREWOXgAAAABERY6cAAAAAERFjtoAAAAAREWPGEK9GuBERY9WQ2Ml50RFj5RDoK7UREWP0kOl+WhERZAQQ22uP0RFkE5Coc28REWQjAAAAABERZDKAAAAAERFkQgAAAAAREWRRgAAAABER8aUAAAAAERHxtQAAAAAREfHEwAAAABER8dTAAAAAERHx5JDh8FaREfH0UO9DJBER8gRQ9bfKERHyFBDzkoWREfIkEOuMHxER8jPAAAAAERHyQ4AAAAAREfJTgAAAABER8mNAAAAAERIbk4AAAAAREhujgAAAABESG7OAAAAAERIbw4AAAAAREhvTkMM9UlESG+NQ083Y0RIb81DOgL9REhwDUK2XghESHBNAAAAAERIcI0AAAAAREhwzQAAAABESHEMAAAAAERKh+IAAAAAREqIIwAAAABESohkAAAAAERKiKYAAAAAREqI50Lh96RESokoQ35MV0RKiWlDnMTYREqJqkNxeg9ESonrQr2M/kRKii0AAAAAREqKbgAAAABESoqvAAAAAERKivAAAAAAREvFtwAAAABES8X5AAAAAERLxjsAAAAAREvGfQAAAABES8a/QwTfiURLxwFDcL+ZREvHQ0OJfrJES8eFQ2HTSURLx8dDAQzpREvICQAAAABES8hLAAAAAERLyI0AAAAAREvIzwAAAABES8wpAAAAAERLzGsAAAAAREvMrQAAAABES8zvAAAAAERLzTFC78e2REvNc0NWbJ9ES821Q5QpeERLzfdDbnPBREvOOUJOhwhES857AAAAAERLzrwAAAAAREvO/gAAAABES89AAAAAAERMDGoAAAAAREwMrQAAAABETAzvAAAAAERMDTEAAAAAREwNc0MbaL1ETA21Q4XDPkRMDfdDlMa4REwOOkNYuqFETA58QoUC7kRMDr4AAAAAREwPAAAAAABETA9CAAAAAERMD4QAAAAARE+u2AAAAABET68dAAAAAERPr2EAAAAARE+vpgAAAABET6/qQyyLhURPsC9DWN/HRE+wc0NkY0tET7C4QxkM20RPsPwAAAAARE+xQQAAAABET7GFAAAAAERPscoAAAAARFAOCQAAAABEUA5OAAAAAERQDpMAAAAARFAO1wAAAABEUA8cQwDAqURQD2FDdvAjRFAPpkOL1RJEUA/qQ0OKJURQEC9CXTp0RFAQdAAAAABEUBC5AAAAAERQEP4AAAAARFARQgAAAABEVcuoAAAAAERVy/AAAAAARFXMOQAAAABEVcyCAAAAAERVzMpCzsoORFXNE0NaGXFEVc1bQ3R5C0RVzaRDKbY/RFXN7QAAAABEVc41AAAAAERVzn4AAAAARFXOxwAAAABEV5BlAAAAAERXkK4AAAAARFeQ+AAAAABEV5FCAAAAAERXkYxDKSu1RFeR1kNbVSFEV5IgQ1lH20RXkmlDOlYfRFeSs0M4QDVEV5L9Q0YP/0RXk0dDMzG5RFeTkQAAAABEV5PaAAAAAERXlCQAAAAARFeUbgAAAABEV6FpAAAAAERXobMAAAAARFeh/QAAAABEV6JHAAAAAERXopFDDVORRFei20NxGSNEV6MlQ22aoURXo25C9lnCRFejuAAAAABEV6QCAAAAAERXpEwAAAAARFeklgAAAABEV6W9AAAAAERXpgcAAAAARFemUQAAAABEV6abAAAAAERXpuVDLnHjRFenL0M9OBdEV6d5QxBdL0RXp8MAAAAARFeoDQAAAABEV6hWAAAAAERXqKAAAAAARF33JAAAAABEXfdzAAAAAERd98EAAAAARF34DwAAAABEXfheQy+tTURd+KxDS93XRF34+kM42jtEXflIQswuZkRd+ZcAAAAARF355QAAAABEXfozAAAAAERd+oEAAAAARF5M4QAAAABEXk0wAAAAAEReTX4AAAAARF5NzQAAAABEXk4bQrksMkReTmpDvnVcRF5OuEQoL11EXk8HREPcqkReT1VEI/uQRF5PpEPTigZEXk/zQ4LN9kReUEFDX7PhRF5QkAAAAABEXlDeAAAAAEReUS0AAAAARF5RewAAAABEXo0MAAAAAERejVsAAAAARF6NqQAAAABEXo34AAAAAERejkdDA7iRRF6OlUOCrD5EXo7kQ8vYCkRejzND56FuRF6PgUO0Y8BEXo/QQyOz3URekB8AAAAARF6QbgAAAABEXpC8AAAAAERekQsAAAAARF7MvgAAAABEXs0NAAAAAERez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AAAAESC4JMAAAAARILgyQAAAABEguEAQykld0SC4TZDdX0HRILhbENFmp9EguGjQb3PWESC4dkAAAAARILiEAAAAABEguJGAAAAAESC4n0AAAAARILldwAAAABEguWtAAAAAESC5eMAAAAARILmGgAAAABEguZQQwBjuUSC5odDV6cNRILmvUM6wtdEgub0QqvdxESC5yoAAAAARILnYQAAAABEgueXAAAAAESC580AAAAARIQHrQAAAABEhAflAAAAAESECBwAAAAARIQIVAAAAABEhAiLQ6u3TESECMJDwF2mRIQI+kO6QMBEhAkxQ4fEYkSECWlC/e2yRIQJoAAAAABEhAnXAAAAAESECg8AAAAARIQKRgAAAABEhkcTAAAAAESGR00AAAAARIZHhgAAAABEhke/AAAAAESGR/lDLs0JRIZIMkNUEF9EhkhrQ0uXC0SGSKRDHr1tRIZI3gAAAABEhkkXAAAAAESGSVAAAAAARIZJikL/SApEhknDQ2n1HUSGSfxDaNZfRIZKNULoybBEhkpvAAAAAESGSqgAAAAARIZK4QAAAABEhksbAAAAAESKp1YAAAAARIqnkwAAAABEiqfQAAAAAESKqA0AAAAARIqoSkOZccZEiqiHQ8OX8ESKqMRD0uwsRIqpAUPBGSZEiqk+Q4aumESKqXsAAAAARIqpuAAAAABEiqn1AAAAAESKqjMAAAAARIsHRgAAAABEiweEAAAAAESLB8EAAAAARIsH/gAAAABEiwg8QRzZQESLCHlDOZ21RIsIt0NpEt9Eiwj0Qxy7mUSLCTIAAAAARIsJbwAAAABEiwmsAAAAAESLCepC1l7iRIsKJ0NKJGFEiwplQ2VGDUSLCqJDI96fRIsK3wAAAABEiwsdAAAAAESLC1oAAAAARIsLmAAAAABEi6aPAAAAAESLps0AAAAARIunCgAAAABEi6dIAAAAAESLp4ZDAlSPRIunxEN89OlEi6gCQ36+10SLqEBDKC6nRIuofgAAAABEi6i8AAAAAESLqPoAAAAARIupOAAAAABEi6l2AAAAAESLqbQAAAAARIup8kMy0NNEi6owQ4TQBkSLqm5DkiguRIuqrENtXpdEi6rqQtiDoESLqygAAA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UNwUU9EpKjjQ0nNC0SkqTpDL+FvRKSpkAAAAABEpKnmAAAAAESkqjwAAAAARKSqkgAAAABEqfuwAAAAAESp/AwAAAAARKn8aAAAAABEqfzEAAAAAESp/SBDNOW9RKn9e0NlYU9Eqf3XQ0R360Sp/jNCwDr2RKn+jwAAAABEqf7rAAAAAESp/0YAAAAARKn/ogAAAABErEarAAAAAESsRwoAAAAARKxHaAAAAABErEfGAAAAAESsSCVCE4y4RKxIg0NICpdErEjhQ4IvIkSsSUBDKx7dRKxJngAAAABErEn8AAAAAESsSloAAAAARKxKuQAAAABEtQkRAAAAAES1CXkAAAAARLUJ4QAAAABEtQpKAAAAAES1CrJDJhD9RLULGkN2IZtEtQuCQ0j6M0S1C+pCqdwmRLUMUgAAAABEtQy6AAAAAES1DSMAAAAARLUNiwAAAABEt1aPAAAAAES3VvkAAAAARLdXZAAAAABEt1fPAAAAAES3WDpDesoPRLdYpUPA01ZEt1kPQ9YeGkS3WXpDvpdCRLdZ5UOX1rpEt1pQAAAAAES3WrsAAAAARLdbJgAAAABEt1uQAAAAAETFGvIAAAAARMUbbQAAAABExRvpAAAAAETFHGQAAAAARMUc30JvoHRExR1bQ31mOUTFHdZDt+aSRMUeUkPAB3pExR7NQ6mPcETFH0lDgLBwRMUfxEMHHK9ExSBAAAAAAETFILsAAAAARMUhNwAAAABExSGyAAAAAETHFHgAAAAARMcU9gAAAABExxV0AAAAAETHFfIAAAAARMcWcEM1n/lExxbuQ1u19UTHF2xDRxs7RMcX6kLjC6ZExxhoAAAAAETHGOYAAAAARMcZZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'
base64.b64decode(your_string)

Well first of all you need to assign the finished product to a variable to be able to be printed out:

code_string = base64.b64decode(your_string)

Then like any beginner programmer would know, you would print the results out: Python 2.7x:

print code_string

Python 3.x:

print(code_string)

After the successful decoding, you will get a string about the size of the not yet decoded string. I hope this helps you!

Correct way to load a Nib for a UIView subclass

MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]

I'm using this to initialise the reusable custom views I have.


Note that you can use "firstObject" at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.

Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
}

Normally, in the TopArea.xib, you would click on File Owner and set the file owner to YourClass. Then actually in YourClass.h you would have IBOutlet properties. In TopArea.xib, you can drag controls to those outlets.

Don't forget that in TopArea.xib, you may have to click on the View itself and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)

Remove carriage return from string

How about:

string s = orig.Replace("\n","").Replace("\r","");

which should handle the common line-endings.

Alternatively, if you have that string hard-coded or are assembling it at runtime - just don't add the newlines in the first place.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

Something like gunzip using the -r flag?....

Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).

http://www.computerhope.com/unix/gzip.htm

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

Why is setState in reactjs Async instead of Sync?

Yes, setState() is asynchronous.

From the link: https://reactjs.org/docs/react-component.html#setstate

  • React does not guarantee that the state changes are applied immediately.
  • setState() does not always immediately update the component.
  • Think of setState() as a request rather than an immediate command to update the component.

Because they think
From the link: https://github.com/facebook/react/issues/11527#issuecomment-360199710

... we agree that setState() re-rendering synchronously would be inefficient in many cases

Asynchronous setState() makes life very difficult for those getting started and even experienced unfortunately:
- unexpected rendering issues: delayed rendering or no rendering (based on program logic)
- passing parameters is a big deal
among other issues.

Below example helped:

// call doMyTask1 - here we set state
// then after state is updated...
//     call to doMyTask2 to proceed further in program

constructor(props) {
    // ..

    // This binding is necessary to make `this` work in the callback
    this.doMyTask1 = this.doMyTask1.bind(this);
    this.doMyTask2 = this.doMyTask2.bind(this);
}

function doMyTask1(myparam1) {
    // ..

    this.setState(
        {
            mystate1: 'myvalue1',
            mystate2: 'myvalue2'
            // ...
        },    
        () => {
            this.doMyTask2(myparam1); 
        }
    );
}

function doMyTask2(myparam2) {
    // ..
}

Hope that helps.

Convert Data URI to File then append to FormData

The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:

function dataURItoBlob (dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab],{type: mimeString});
}

CSS: Force float to do a whole new line

This is what I did. Seems to work in forcing a new line, but I'm not an html/css guru by any measure.

<p>&nbsp;</p>

How to convert a boolean array to an int array

I know you asked for non-looping solutions, but the only solutions I can come up with probably loop internally anyway:

map(int,y)

or:

[i*1 for i in y]

or:

import numpy
y=numpy.array(y)
y*1

Add multiple items to already initialized arraylist in java

I believe the answer above is incorrect, the proper way to initialize with multiple values would be this...

int[] otherList ={1,2,3,4,5};

so the full answer with the proper initialization would look like this

int[] otherList ={1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));

What is the OAuth 2.0 Bearer Token exactly?

A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.

Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

How to draw a circle with text in the middle?

Some of solutions here didn't work well for me on small circles. So I made this solution using ol absolute position.

Using SASS will look like this:

.circle-text {
    position: relative;
    display: block;
    text-align: center;
    border-radius: 50%;
    > .inner-text {
        display: block;
        @extend .center-align;
    }
}

.center-align {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: auto;
    -webkit-transform: translateX(-50%) translateY(-50%);
    -ms-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}

@mixin circle-text($size) {
    width: $size;
    height: $size;
    @extend .circle-text;
}

And can be used like

#red-circle {
    background-color: red;
    border: 1px solid black;
    @include circle-text(50px);
}

#green-circle {
    background-color: green;
    border: 1px solid black;
    @include circle-text(150px);
}

See demo on https://codepen.io/matheusrufca/project/editor/DnYPMK

See the snippet to view output CSS

_x000D_
_x000D_
.circle-text {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  min-width: 50px;_x000D_
  min-height: 50px;_x000D_
}_x000D_
_x000D_
.center-align {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: auto;_x000D_
  -webkit-transform: translateX(-50%) translateY(-50%);_x000D_
  -ms-transform: translateX(-50%) translateY(-50%);_x000D_
  transform: translateX(-50%) translateY(-50%);_x000D_
}
_x000D_
<div id="red-circle" class="circle-text">_x000D_
  <span class="inner-text center-align">Hey</span>_x000D_
</div>_x000D_
_x000D_
<div id="green-circle" class="circle-text">_x000D_
  <span class="inner-text center-align">Big size circle</span>_x000D_
  <div>_x000D_
    <style>_x000D_
      #red-circle {_x000D_
        background-color: red;_x000D_
        border: 1px solid black;_x000D_
        width: 60px;_x000D_
        height: 60px;_x000D_
      }_x000D_
      _x000D_
      #green-circle {_x000D_
        background-color: green;_x000D_
        border: 1px solid black;_x000D_
        width: 150px;_x000D_
        height: 150px;_x000D_
      }_x000D_
    </style>
_x000D_
_x000D_
_x000D_

How to disable HTML links

I've ended up with the solution below, which can work with either an attribute, <a href="..." disabled="disabled">, or a class <a href="..." class="disabled">:

CSS Styles:

a[disabled=disabled], a.disabled {
    color: gray;
    cursor: default;
}

a[disabled=disabled]:hover, a.disabled:hover {
    text-decoration: none;
}

Javascript (in jQuery ready):

$("a[disabled], a.disabled").on("click", function(e){

    var $this = $(this);
    if ($this.is("[disabled=disabled]") || $this.hasClass("disabled"))
        e.preventDefault();
})

How do I output text without a newline in PowerShell?

I cheated, but I believe this is the only answer that addresses every requirement. Namely, this avoids the trailing CRLF, provides a place for the other operation to complete in the meantime, and properly redirects to stdout as necessary.

$c_sharp_source = @"
using System;
namespace StackOverflow
{
   public class ConsoleOut
   {
      public static void Main(string[] args)
      {
         Console.Write(args[0]);
      }
   }
}
"@
$compiler_parameters = New-Object System.CodeDom.Compiler.CompilerParameters
$compiler_parameters.GenerateExecutable = $true
$compiler_parameters.OutputAssembly = "consoleout.exe"
Add-Type -TypeDefinition $c_sharp_source -Language CSharp -CompilerParameters $compiler_parameters

.\consoleout.exe "Enabling feature XYZ......."
Write-Output 'Done.'

Import data.sql MySQL Docker Container

Import using docker-compose

cat dump.sql | docker-compose exec -T <mysql_container> mysql -u <db-username> -p<db-password> <db-name>

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

This seems to be old post but still I wanted to share how this issue got fixed for me.

For users, who do not have admin access and when they open a command prompt, it runs under the user privilege. It means, you may have path like C:\Users\

so when trying C:\Users\XYZ>mvn --version , it actually search the JAVA_HOME path from user variables not system variables in Environment Variables.

So, In order to fix this, we need to create a environment variable for JAVA_HOME in user variables.

Hope, this helps someone.

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

Run PostgreSQL queries from the command line

I also noticed that the query

SELECT * FROM tablename;

gives an error on the psql command prompt and

SELECT * FROM "tablename";

runs fine, really strange, so don't forget the double quotes. I always liked databases :-(

batch file to check 64bit or 32bit OS

Here's my personal favorite, a logical bomb :)

::32/64Bit Switch
ECHO %PROCESSOR_ARCHITECTURE%|FINDSTR AMD64>NUL && SET ARCH=AMD64 || SET ARCH=x86
ECHO %ARCH%
PAUSE

With the AND's (&&) and OR's (||) this is a IF THEN ELSE Batch Construct.

How to drop all stored procedures at once in SQL Server database?

By mixing the cursor and system procedure, we would have a optimized solution, as follow:

DECLARE DelAllProcedures CURSOR
FOR
    SELECT name AS procedure_name 
    FROM sys.procedures;
OPEN DelAllProcedures
DECLARE @ProcName VARCHAR(100)
FETCH NEXT 
FROM DelAllProcedures
INTO @ProcName
WHILE @@FETCH_STATUS!=-1
BEGIN 
    DECLARE @command VARCHAR(100)
    SET @command=''
    SET @command=@command+'DROP PROCEDURE '+@ProcName
    --DROP PROCEDURE  @ProcName
    EXECUTE (@command)
    FETCH NEXT 
    FROM DelAllProcedures
    INTO @ProcName
END
CLOSE DelAllProcedures
DEALLOCATE DelAllProcedures

How to check if a string is a number?

if ( strlen(str) == strlen( itoa(atoi(str)) ) ) {
    //its an integer
}

As atoi converts string to number skipping letters other than digits, if there was no other than digits its string length has to be the same as the original. This solution is better than innumber() if the check is for integer.

Disable future dates after today in Jquery Ui Datepicker

In my case, I have given this attribute to the input tag

data-date-start-date="0d" data-date-end-date="0d"

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

Laravel Eloquent LEFT JOIN WHERE NULL

use Illuminate\Database\Eloquent\Builder;

$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
     $query = $query->where('orders.customer_id', 'NULL') 
});
    $query = $query->get();

How do I determine the dependencies of a .NET application?

http://www.amberfish.net/

ChkAsm will show you all the dependencies of a particular assembly at once, including the versions, and easily let you search for assemblies in the list. Works much better for this purpose than ILSpy (http://ilspy.net/), which is what I used to use for this task.

Add querystring parameters to link_to

If you want the quick and dirty way and don't worry about XSS attack, use params.merge to keep previous parameters. e.g.

<%= link_to 'Link', params.merge({:per_page => 20}) %>

see: https://stackoverflow.com/a/4174493/445908

Otherwise , check this answer: params.merge and cross site scripting

java.lang.OutOfMemoryError: GC overhead limit exceeded

For the record, we had the same problem today. We fixed it by using this option:

-XX:-UseConcMarkSweepGC

Apparently, this modified the strategy used for garbage collection, which made the issue disappear.

Set focus on TextBox in WPF from view model

None of these worked for me exactly, but for the benefit of others, this is what I ended up writing based on some of the code already provided here.

Usage would be as follows:

<TextBox ... h:FocusBehavior.IsFocused="True"/>

And the implementation would be as follows:

/// <summary>
/// Behavior allowing to put focus on element from the view model in a MVVM implementation.
/// </summary>
public static class FocusBehavior
{
    #region Dependency Properties
    /// <summary>
    /// <c>IsFocused</c> dependency property.
    /// </summary>
    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
            typeof(FocusBehavior), new FrameworkPropertyMetadata(IsFocusedChanged));
    /// <summary>
    /// Gets the <c>IsFocused</c> property value.
    /// </summary>
    /// <param name="element">The element.</param>
    /// <returns>Value of the <c>IsFocused</c> property or <c>null</c> if not set.</returns>
    public static bool? GetIsFocused(DependencyObject element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        return (bool?)element.GetValue(IsFocusedProperty);
    }
    /// <summary>
    /// Sets the <c>IsFocused</c> property value.
    /// </summary>
    /// <param name="element">The element.</param>
    /// <param name="value">The value.</param>
    public static void SetIsFocused(DependencyObject element, bool? value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        element.SetValue(IsFocusedProperty, value);
    }
    #endregion Dependency Properties

    #region Event Handlers
    /// <summary>
    /// Determines whether the value of the dependency property <c>IsFocused</c> has change.
    /// </summary>
    /// <param name="d">The dependency object.</param>
    /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
    private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // Ensure it is a FrameworkElement instance.
        var fe = d as FrameworkElement;
        if (fe != null && e.OldValue == null && e.NewValue != null && (bool)e.NewValue)
        {
            // Attach to the Loaded event to set the focus there. If we do it here it will
            // be overridden by the view rendering the framework element.
            fe.Loaded += FrameworkElementLoaded;
        }
    }
    /// <summary>
    /// Sets the focus when the framework element is loaded and ready to receive input.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    private static void FrameworkElementLoaded(object sender, RoutedEventArgs e)
    {
        // Ensure it is a FrameworkElement instance.
        var fe = sender as FrameworkElement;
        if (fe != null)
        {
            // Remove the event handler registration.
            fe.Loaded -= FrameworkElementLoaded;
            // Set the focus to the given framework element.
            fe.Focus();
            // Determine if it is a text box like element.
            var tb = fe as TextBoxBase;
            if (tb != null)
            {
                // Select all text to be ready for replacement.
                tb.SelectAll();
            }
        }
    }
    #endregion Event Handlers
}

How can I check for "undefined" in JavaScript?

Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined

Input type=password, don't let browser remember the password

seeing as autocomplete=off is deprecated, I suggest a more recent solution.

Set your password field to a normal text field, and mask your input with "discs" using CSS. the code should look like this:

<input type="text" class="myPassword" /> 

input .myPassword{
    text-security:disc;
    -webkit-text-security:disc;
    -mox-text-security:disc;
}

Please note that this may not work propely on firefox browsers, and an additional walkaround is needed. Read more about it here :https://stackoverflow.com/a/49304708/5477548.

The solution was taken from this link, but to comply with SO "no-hotlinks" i summarized it here.

jQuery Dialog Box

My solution: remove some init options (ex. show), because constructor doesnt yield if something is not working (ex slide effect). My function without dynamic html insertion:

function ySearch(){ console.log('ysearch');
    $( "#aaa" ).dialog({autoOpen: true,closeOnEscape: true, dialogClass: "ysearch-dialog",modal: false,height: 510, width:860
    });
    $('#aaa').dialog("open");

    console.log($('#aaa').dialog("isOpen"));
    return false;
}

MongoDB: update every document on one field

This code will be helpful for you

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  

Right HTTP status code to wrong input

404 - Not Found - can be used for The URI requested is invalid or the resource requested such as a user, does not exists.

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

Algorithm to find Largest prime factor of a number

Here is my attempt in Clojure. Only walking the odds for prime? and the primes for prime factors ie. sieve. Using lazy sequences help producing the values just before they are needed.

;; Sieve of Eratosthenes
(defn sieve [[i & is :as ps] n]
    (let [q (quot n i)
          r (mod n i)]
    (cond (zero? r)     (lazy-seq (cons i (sieve ps q)))
          (> (* i i) n) (when (> n 1) (lazy-seq [n]))
          :else         (recur is n))))

(defn prime? 
  ([n]
    (let [oddNums (iterate #(+ % 2) 3)
          is      (cons 2 oddNums)]
    (prime? n is)))
  ([n [i & is]]
    (let [q (quot n i)
          r (mod n i)]
    (cond (< n 2)       false
          (zero? r)     false
          (> (* i i) n) true
          :else         (recur n is)))))

(def primes 
  (let [oddNums (iterate #(+ % 2) 3)]
  (lazy-seq (cons 2 (filter prime? oddNums)))))

(defn max-prime-factor [n]
  (last (sieve primes n)))

How to round up with excel VBA round()?

I am introducing Two custom library functions to be used in vba, which will serve the purpose of rounding the double value instead of using WorkSheetFunction.RoundDown and WorkSheetFunction.RoundUp

Function RDown(Amount As Double, digits As Integer) As Double
    RDown = Int((Amount + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function

Function RUp(Amount As Double, digits As Integer) As Double
    RUp = RDown(Amount + (5 / (10 ^ (digits + 1))), digits)
End Function

Thus function Rdown(2878.75 * 31.1,2) will return 899529.12 and function RUp(2878.75 * 31.1,2) will return 899529.13 Whereas The function Rdown(2878.75 * 31.1,-3) will return 89000 and function RUp(2878.75 * 31.1,-3) will return 90000

Invalid URI: The format of the URI could not be determined

It may help to use a different constructor for Uri.

If you have the server name

string server = "http://www.myserver.com";

and have a relative Uri path to append to it, e.g.

string relativePath = "sites/files/images/picture.png"

When creating a Uri from these two I get the "format could not be determined" exception unless I use the constructor with the UriKind argument, i.e.

// this works, because the protocol is included in the string
Uri serverUri = new Uri(server);

// needs UriKind arg, or UriFormatException is thrown
Uri relativeUri = new Uri(relativePath, UriKind.Relative); 

// Uri(Uri, Uri) is the preferred constructor in this case
Uri fullUri = new Uri(serverUri, relativeUri);

How to remove components created with Angular-CLI

version control is your friend here, do a diff or equivalent and you should see what's been added/modified.

In fact, removing the component folder might not be enough; with Angular-CLI v1.0, the command ng generate component my-new-component also edits your app.module.ts file by adding the respective import line and the component to the providers array.

submitting a GET form with query string params and hidden params disappear

Isn't that what hidden parameters are for to start with...?

<form action="http://www.example.com" method="GET">
  <input type="hidden" name="a" value="1" /> 
  <input type="hidden" name="b" value="2" /> 
  <input type="hidden" name="c" value="3" /> 
  <input type="submit" /> 
</form>

I wouldn't count on any browser retaining any existing query string in the action URL.

As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:

If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.

Maybe one could percent-encode the action-URL to embed the question mark and the parameters, and then cross one's fingers to hope all browsers would leave that URL as it (and validate that the server understands it too). But I'd never rely on that.

By the way: it's not different for non-hidden form fields. For POST the action URL could hold a query string though.

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

How to make the window full screen with Javascript (stretching all over the screen)

Try screenfull.js. It's a nice cross-browser solution that should work for Opera browser as well.

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.

Demo.

How to execute a file within the python interpreter?

For Python 3:

>>> exec(open("helloworld.py").read())

Make sure that you're in the correct directory before running the command.

To run a file from a different directory, you can use the below command:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

How to view .img files?

OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .

All these work well on .img files

Delete the 'first' record from a table in SQL Server, without a WHERE condition

depends on your DBMS (people don't seem to know what that is nowadays)

-- MYSql:
DELETE FROM table LIMIT 1;
-- Postgres:
DELETE FROM table LIMIT 1;
-- MSSql:
DELETE TOP(1) FROM table;
-- Oracle:
DELETE FROM table WHERE ROWNUM = 1;

Using jQuery to compare two arrays of Javascript objects

Convert both array to string and compare

if (JSON.stringify(array1) == JSON.stringify(array2))
{
    // your code here
}

Passing ArrayList through Intent

if you using Generic Array List with Class instead of specific type like

EX:

private ArrayList<Model> aListModel = new ArrayList<Model>();

Here, Model = Class

Receiving Intent Like :

aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);

MUST REMEMBER:

Here Model-class must be implemented like: ModelClass implements Serializable

How to convert a byte array to Stream

I am using as what John Rasch said:

Stream streamContent = taxformUpload.FileContent;

check the null terminating character in char*

You have used '/0' instead of '\0'. This is incorrect: the '\0' is a null character, while '/0' is a multicharacter literal.

Moreover, in C it is OK to skip a zero in your condition:

while (*(forward++)) {
    ...
}

is a valid way to check character, integer, pointer, etc. for being zero.

Remove icon/logo from action bar on android

go to your manifest an find the application tag

  android:icon="@android:color/transparent"// simply add this on place of your icon

..... ... ...

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

I want to collaborate a little with the solution for the server side. So, the server is saying it does not support DSA, this is because the openssh client does not activate it by default:

OpenSSH 7.0 and greater similarly disable the ssh-dss (DSA) public key algorithm. It too is weak and we recommend against its use.

So, to fix this this in the server side I should activate other Key algorithms like RSA o ECDSA. I just had this problem with a server in a lan. I suggest the following:

Update the openssh:

yum update openssh-server

Merge new configurations in the sshd_config if there is a sshd_config.rpmnew.

Verify there are hosts keys at /etc/ssh/. If not generate new ones, see man ssh-keygen.

$ ll /etc/ssh/
total 580
-rw-r--r--. 1 root root     553185 Mar  3  2017 moduli
-rw-r--r--. 1 root root       1874 Mar  3  2017 ssh_config
drwxr-xr-x. 2 root root       4096 Apr 17 17:56 ssh_config.d
-rw-------. 1 root root       3887 Mar  3  2017 sshd_config
-rw-r-----. 1 root ssh_keys    227 Aug 30 15:33 ssh_host_ecdsa_key
-rw-r--r--. 1 root root        162 Aug 30 15:33 ssh_host_ecdsa_key.pub
-rw-r-----. 1 root ssh_keys    387 Aug 30 15:33 ssh_host_ed25519_key
-rw-r--r--. 1 root root         82 Aug 30 15:33 ssh_host_ed25519_key.pub
-rw-r-----. 1 root ssh_keys   1675 Aug 30 15:33 ssh_host_rsa_key
-rw-r--r--. 1 root root        382 Aug 30 15:33 ssh_host_rsa_key.pub

Verify in the /etc/ssh/sshd_config the HostKey configuration. It should allow the configuration of RSA and ECDSA. (If all of them are commented by default it will allow too the RSA, see in man sshd_config the part of HostKey).

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

For the client side, create a key for ssh (not a DSA like in the question) by just doing this:

ssh-keygen

After this, because there are more options than ssh-dss(DSA) the client openssh (>=v7) should connect with RSA or better algorithm.

Here another good article.

This is my first question answered, I welcome suggestions :D .

How to get everything after a certain character?

I use strrchr(). For instance to find the extension of a file I use this function:

$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns ".jpg"

beyond top level package error in relative import

EDIT: There are better/more coherent answers to this question in other questions:


Why doesn't it work? It's because python doesn't record where a package was loaded from. So when you do python -m test_A.test, it basically just discards the knowledge that test_A.test is actually stored in package (i.e. package is not considered a package). Attempting from ..A import foo is trying to access information it doesn't have any more (i.e. sibling directories of a loaded location). It's conceptually similar to allowing from ..os import path in a file in math. This would be bad because you want the packages to be distinct. If they need to use something from another package, then they should refer to them globally with from os import path and let python work out where that is with $PATH and $PYTHONPATH.

When you use python -m package.test_A.test, then using from ..A import foo resolves just fine because it kept track of what's in package and you're just accessing a child directory of a loaded location.

Why doesn't python consider the current working directory to be a package? NO CLUE, but gosh it would be useful.

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Subclass UIButton

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat spacing = 6.0;
    CGSize imageSize = self.imageView.image.size;
    CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake(self.frame.size.width, self.frame.size.height - (imageSize.height + spacing))];
    self.imageView.frame = CGRectMake((self.frame.size.width - imageSize.width)/2, (self.frame.size.height - (imageSize.height+spacing+titleSize.height))/2, imageSize.width, imageSize.height);
    self.titleLabel.frame = CGRectMake((self.frame.size.width - titleSize.width)/2, CGRectGetMaxY(self.imageView.frame)+spacing, titleSize.width, titleSize.height);
}

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

How to increment a datetime by one day?

Most Simplest solution

from datetime import timedelta, datetime
date = datetime(2003,8,1,12,4,5)
for i in range(5):
    date += timedelta(days=1)
    print(date)

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

if you're using the compiled bootstrap, one of the ways of fixing it is by editing the bootstrap.min.js before the line

$next[0].offsetWidth 

force reflow Change to

if (typeof $next == 'object' && $next.length) $next[0].offsetWidth // force reflow

How to know if docker is already logged in to a docker registry server

If you want a simple true/false value, you can pipe your docker.json to jq.

is_logged_in() {
  cat ~/.docker/config.json | jq -r --arg url "${REPOSITORY_URL}" '.auths | has($url)'
}

if [[ "$(is_logged_in)" == "false" ]]; then
  # do stuff, log in
fi

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

How can I create an Asynchronous function in Javascript?

This page walks you through the basics of creating an async javascript function.

Since ES2017, asynchronous javacript functions are much easier to write. You should also read more on Promises.

What is Python Whitespace and how does it work?

Whitespace just means characters which are used for spacing, and have an "empty" representation. In the context of python, it means tabs and spaces (it probably also includes exotic unicode spaces, but don't use them). The definitive reference is here: http://docs.python.org/2/reference/lexical_analysis.html#indentation

I'm not sure exactly how to use it.

Put it at the front of the line you want to indent. If you mix spaces and tabs, you'll likely see funky results, so stick with one or the other. (The python community usually follows PEP8 style, which prescribes indentation of four spaces).

You need to create a new indent level after each colon:

for x in range(0, 50):
    print x
    print 2*x

print x

In this code, the first two print statements are "inside" the body of the for statement because they are indented more than the line containing the for. The third print is outside because it is indented less than the previous (nonblank) line.

If you don't indent/unindent consistently, you will get indentation errors. In addition, all compound statements (i.e. those with a colon) can have the body supplied on the same line, so no indentation is required, but the body must be composed of a single statement.

Finally, certain statements, like lambda feature a colon, but cannot have a multiline block as the body.

Formatting Decimal places in R

Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.

Adding an onclicklistener to listview (android)

listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = prestListView.getItemAtPosition(position);
        prestationEco str = (prestationEco)o; //As you are using Default String Adapter
        Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
    }
});

How to automatically reload a page after a given period of inactivity

I have built a complete javascript solution as well that does not require jquery. Might be able to turn it into a plugin. I use it for fluid auto-refreshing, but it looks like it could help you here.

JSFiddle AutoRefresh

// Refresh Rate is how often you want to refresh the page 
// bassed off the user inactivity. 
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times 
// we want to refresh anyway even if they are typing. 
// This is so we don't get the browser locked into 
// a state where the refresh never happens.    
var focus_margin = 10; 

// Reset the Timer on users last action
function reset() {
    last_user_action = 0;
    console.log("Reset");
}

function windowHasFocus() {
    has_focus = true;
}

function windowLostFocus() {
    has_focus = false;
    lost_focus_count++;
    console.log(lost_focus_count + " <~ Lost Focus");
}

// Count Down that executes ever second
setInterval(function () {
    last_user_action++;
    refreshCheck();
}, 1000);

// The code that checks if the window needs to reload
function refreshCheck() {
    var focus = window.onfocus;
    if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
        window.location.reload(); // If this is called no reset is needed
        reset(); // We want to reset just to make sure the location reload is not called.
    }

}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);

How to identify unused CSS definitions from multiple CSS files in a project

Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.

To enable it follow these steps:

  1. Open up DevTools (Command+Option+I on Mac; Control+Shift+I on Windows)
  2. Head over to DevTool Settings (Function+F1 on Mac; F1 on Windows)
  3. Click open the Experiments section
  4. Enable the CSS Overview option

enter image description here

Remove a prefix from a string

def remove_prefix(str, prefix):
    if str.startswith(prefix):
        return str[len(prefix):]
    else:
        return str

As an aside note, str is a bad name for a variable because it shadows the str type.

How to delete a record by id in Flask-SQLAlchemy

Another possible solution specially if you want batch delete

deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))
session.execute(deleted_objects)
session.commit()

How can I change cols of textarea in twitter-bootstrap?

I found the following in the site.css generated by VS2013

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

To override this behavior in a specific element, add the following...

 style="max-width: none;" 

For example:

 <div class="col-md-6">
      <textarea style="max-width: none;" 
                class="form-control" 
                placeholder="a col-md-6 multiline input box" />
 </div>

How do I add a new sourceset to Gradle?

I'm new to Gradle, using Gradle 6.0.1 JUnit 4.12. Here's what I came up with to solve this problem.

apply plugin: 'java'
repositories { jcenter() }

dependencies {
    testImplementation 'junit:junit:4.12'
}

sourceSets {
  main {
    java {
       srcDirs = ['src']
    }
  }
  test {
    java {
      srcDirs = ['tests']
    }
  }
}

Notice that the main source and test source is referenced separately, one under main and one under test.

The testImplementation item under dependencies is only used for compiling the source in test. If your main code actually had a dependency on JUnit, then you would also specify implementation under dependencies.

I had to specify the repositories section to get this to work, I doubt that is the best/only way.