Programs & Examples On #Automount

For questions regarding the auto-mounting of filesystems, for example, automatic reading of usb storage, enabled in many operating systems.

How can I calculate the difference between two ArrayLists?

I guess you're talking about C#. If so, you can try this

    ArrayList CompareArrayList(ArrayList a, ArrayList b)
    {
        ArrayList output = new ArrayList();
        for (int i = 0; i < a.Count; i++)
        {
            string str = (string)a[i];
            if (!b.Contains(str))
            {
                if(!output.Contains(str)) // check for dupes
                    output.Add(str);
            }
        }
        return output;
    }

Viewing contents of a .jar file

I think Java Decomplier is your best option you can download from here: http://jd.benow.ca/ Preview

How to put labels over geom_bar for each bar in R with ggplot2

Try this:

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

What is the syntax meaning of RAISERROR()

The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).

The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.

MVC Razor Hidden input and passing values

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server" thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

SQL Server replace, remove all after certain character

Use CHARINDEX to find the ";". Then use SUBSTRING to just return the part before the ";".

tSQL - Conversion from varchar to numeric works for all but integer

SELECT
  convert(numeric(18,5),Col1), Col2
     FROM DBname.dbo.TableName
         WHERE isnumeric(isnull(Col1,1)) <> 0

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Hi this is due to new version of the jQuery => 1.9.0

you can check the update : http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/

jQuery.Browser is deprecated. you can keep latest version by adding a migration script : http://code.jquery.com/jquery-migrate-1.0.0.js

replace :

<script src="http://code.jquery.com/jquery-latest.js"></script>

by :

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

in your page and its working.

Using OpenGl with C#?

OpenTK is an improvement over the Tao API, as it uses idiomatic C# style with overloading, strongly-typed enums, exceptions, and standard .NET types:

GL.Begin(BeginMode.Points);
GL.Color3(Color.Yellow);
GL.Vertex3(Vector3.Up);

as opposed to Tao which merely mirrors the C API:

Gl.glBegin(Gl.GL_POINTS);   // double "gl" prefix
Gl.glColor3ub(255, 255, 0); // have to pass RGB values as separate args
Gl.glVertex3f(0, 1, 0);     // explicit "f" qualifier

This makes for harder porting but is incredibly nice to use.

As a bonus it provides font rendering, texture loading, input handling, audio, math...

Update 18th January 2016: Today the OpenTK maintainer has stepped away from the project, leaving its future uncertain. The forums are filled with spam. The maintainer recommends moving to MonoGame or SDL2#.

Update 30th June 2020: OpenTK has had new maintainers for a while now and has an active discord community. So the previous recommendation of using another library isn't necessarily true.

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

You can then call it like this:

window.location.href = nextImage();

Demo here: http://jsfiddle.net/jfriend00/3VPEq/

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

Can I update a JSF component from a JSF backing bean method?

The RequestContext is deprecated from Primefaces 6.2. From this version use the following:

if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
    PrimeFaces.current().ajax().update(componentID);
}

And to execute javascript from the backbean use this way:

PrimeFaces.current().executeScript(jsCommand);

Reference:

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

How to extract text from an existing docx file using python-docx

There are two "generations" of python-docx. The initial generation ended with the 0.2.x versions and the "new" generation started at v0.3.0. The new generation is a ground-up, object-oriented rewrite of the legacy version. It has a distinct repository located here.

The opendocx() function is part of the legacy API. The documentation is for the new version. The legacy version has no documentation to speak of.

Neither reading nor writing hyperlinks are supported in the current version. That capability is on the roadmap, and the project is under active development. It turns out to be quite a broad API because Word has so much functionality. So we'll get to it, but probably not in the next month unless someone decides to focus on that aspect and contribute it. UPDATE Hyperlink support was added subsequent to this answer.

Excel VBA Run Time Error '424' object required

Private Sub CommandButton1_Click()

    Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption

    Me.Hide

    Run "filename"

End Sub

Private Sub MUN_Change()
    Dim r As Integer
    r = 2

    While Range("m" & CStr(r)).Value <> ""
        If Range("m" & CStr(r)).Value = MUN.Text Then
        Label5.Caption = Range("n" & CStr(r)).Value
        End If
        r = r + 1
    Wend

End Sub

Private Sub PROV_Change()
    If PROV.Text = "LAGUNA" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M26:M56"
    ElseIf PROV.Text = "CAVITE" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M2:M25"
    ElseIf PROV.Text = "QUEZON" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M57:M97"
    End If
End Sub

Android: ProgressDialog.show() crashes with getApplicationContext

Which API version are you using? If I'm right about what the problem is then this was fixed in Android 1.6 (API version 4).

It looks like the object reference that getApplicationContext() is returning just points to null. I think you're having a problem similar to one I had in that some of the code in the onCreate() is being run before the window is actually done being built. This is going to be a hack, but try launching a new Thread in a few hundred milliseconds (IIRC: 300-400 seemed to work for me, but you'll need to tinker) that opens your ProgressDialog and starts anything else you needed (eg. network IO). Something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    // do all your other stuff here

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mProgressDialog = ProgressDialog.show(
               YouTube.this.getApplicationContext(), "",
               YouTube.this.getString(R.string.loading), true);

            // start time consuming background process here
        }
    }, 1000); // starting it in 1 second
}

Running JAR file on Windows

Easiest route is probably upgrading or re-installing the Java Runtime Environment (JRE).

Or this:

  • Open the Windows Explorer, from the Tools select 'Folder Options...'
  • Click the File Types tab, scroll down and select JAR File type.
  • Press the Advanced button.
  • In the Edit File Type dialog box, select open in Actions box and click Edit...
  • Press the Browse button and navigate to the location the Java interpreter javaw.exe.
  • In the Application used to perform action field, needs to display something similar to C:\Program Files\Java\j2re1.4.2_04\bin\javaw.exe" -jar "%1" % (Note: the part starting with 'javaw' must be exactly like that; the other part of the path name can vary depending on which version of Java you're using) then press the OK buttons until all the dialogs are closed.

Which was stolen from here: http://windowstipoftheday.blogspot.com/2005/10/setting-jar-file-association.html

How to integrate sourcetree for gitlab

This worked for me,

Step 1: Click on + New Repository> Clone from URL

Step 2: In Source URL provide URL followed by your user name,

Example:

  • GitLab Repo URL : http://git.zaid-labs.info/zaid/iosapp.git
  • GitLab User Name : zaid.pathan

So final URL should be http://[email protected]/zaid/iosapp.git

Note: zaid.pathan@ added before git.

Step 3: Enjoy cloning :).

phpMyAdmin - config.inc.php configuration?

I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php is calling config-db.php

** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1

/etc/phpmyadmin/config-db.php:

$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';

Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration. That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs

disable all form elements inside div

    $(document).ready(function () {
        $('#chkDisableEnableElements').change(function () {
            if ($('#chkDisableEnableElements').is(':checked')) {
                enableElements($('#divDifferentElements').children());
            }
            else {
                disableElements($('#divDifferentElements').children());
            }
        });
    });

    function disableElements(el) {
        for (var i = 0; i < el.length; i++) {
            el[i].disabled = true;

            disableElements(el[i].children);
        }
    }

    function enableElements(el) {
        for (var i = 0; i < el.length; i++) {
            el[i].disabled = false;

            enableElements(el[i].children);
        }
    }

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
    <configuration>
        ...
        <system.web>
            ...
            <pages>
                ...
                <controls>
                    ...
                    <add tagPrefix="ajaxtoolkit"
                        namespace="AjaxControlToolkit"
                        assembly="AjaxControlToolKit"/>
                </controls>
            </pages>
            ...
        </system.web>
        ...
    </configuration>
    

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

HTML colspan in CSS

Another suggestion is using flexbox instead of tables altogether. This is a "modern browser" thing of course, but come on, it's 2016 ;)

At least this might be an alternative solution for those looking for an answer to this nowadays, since the original post was from 2010.

Here's a great guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

_x000D_
_x000D_
.table {_x000D_
  border: 1px solid red;_x000D_
  padding: 2px;_x000D_
  max-width: 300px;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
}_x000D_
.table-cell {_x000D_
  border: 1px solid blue;_x000D_
  flex: 1 30%;_x000D_
}_x000D_
.colspan-3 {_x000D_
  border: 1px solid green;_x000D_
  flex: 1 100%;_x000D_
}
_x000D_
<div class="table">_x000D_
  <div class="table-cell">_x000D_
    row 1 - cell 1_x000D_
  </div>_x000D_
  <div class="table-cell">_x000D_
    row 1 - cell 2_x000D_
  </div>_x000D_
  <div class="table-cell">_x000D_
    row 1 - cell 3_x000D_
  </div>_x000D_
  <div class="table-cell colspan-3">_x000D_
    row 2 - cell 1 (spans 3 columns)_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

git status shows modifications, git checkout -- <file> doesn't remove them

Normally, in GIT to clear all your modifications & new files the following 2 commands should work very nicely (be CAREFUL, this will delete all your new files+folders you may have created & will restore all your modified files to the state of your current commit):

$ git clean --force -d
$ git checkout -- .

Maybe a better option sometimes is just doing "git stash push" with optional message, like so:

$ git stash push -m "not sure if i will need this later"

This will also clear all your new and modified files, but you'll have all of them stashed in case you want to restore them. Stash in GIT carries from branch to branch, so you can restore them in a different branch, if you wish to.

As a side note, in case you have already staged some newly added files and want to get rid of them, this should do the trick:

$ git reset --hard

If all of the above doesn't work for you, read below what worked for me a while ago:

I ran into this problem few times before. I'm currently developing on Windows 10 machine provided by my employer. Today, this particular git behavior was caused by me creating a new branch from my "develop" branch. For some reason, after I switched back to "develop" branch, some seemingly random files persisted and were showing up as "modified" in "git status".

Also, at that point I couldn't checkout another branch, so I was stuck on my "develop" branch.

This is what I did:

$ git log

I noticed that the new branch I created from "develop" earlier today was showing in the first "commit" message, being referenced at the end "HEAD -> develop, origin/develop, origin/HEAD, The-branch-i-created-earlier-today".

Since I didn't really need it, I deleted it:

$ git branch -d The-branch-i-created-earlier-today

The changed files were still showing up, so I did:

$ git stash

This solved my problem:

$ git status
On branch develop
Your branch is up to date with 'origin/develop'.

nothing to commit, working tree clean

Of course $ git stash list will show stashed changes, and since I had few and didn't need any of my stashes, I did $ git stash clear to DELETE ALL STASHES.

NOTE: I haven't tried doing what someone suggested here before me:

$ git rm --cached -r .
$ git reset --hard

This may have worked as well, I'll be sure to try it next time I run into this problem.

What is the difference between the dot (.) operator and -> in C++?

The arrow operator is like dot, except it dereferences a pointer first. foo.bar() calls method bar() on object foo, foo->bar calls method bar on the object pointed to by pointer foo.

Manifest Merger failed with multiple errors in Android Studio

In addition to available solutions, please check this also.
If you have set android:allowBackup="false" in your AndroidManifest.xml then there may be a conflict for android:allowBackup="true" in other dependencies.

Solution
As suggested by @CLIFFORD P Y, switch to Merged Manifest in your AndroidManifest.xml. Android Studio will suggest to add tools:replace="android:allowBackup" in <application /> in your AndroidManifest.xml.

How to run script as another user without password?

`su -c "Your command right here" -s /bin/sh username`

The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example; execl: couldn't exec /bin/sh execl: Permission denied

I had to install setroubleshoot and setools and run the following to allow it:

yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p

How to find all occurrences of a substring?

This function does not look at all positions inside the string, it does not waste compute resources. My try:

def findAll(string,word):
    all_positions=[]
    next_pos=-1
    while True:
        next_pos=string.find(word,next_pos+1)
        if(next_pos<0):
            break
        all_positions.append(next_pos)
    return all_positions

to use it call it like this:

result=findAll('this word is a big word man how many words are there?','word')

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

Detect element content changes with jQuery

We can achieve this by using Mutation Events. According to www.w3.org, The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications. For more detail MUTATION EVENTS

For Example :

$("body").on('DOMSubtreeModified', "#content", function() {
    alert('Content Modified'); // do something
});

Insert picture/table in R Markdown

Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.

Images

The bookdown book does a great job of explaining that the best way to include images is by using include_graphics(). For example, a full width image can be printed with a caption below:

```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```

The reason this method is better than the pandoc approach ![your image](path/to/image):

  • It automatically changes the command based on the output format (HTML/PDF/Word)
  • The same syntax can be used to the size of the plot (fig.width), the output width in the report (out.width), add captions (fig.cap) etc.
  • It uses the best graphical devices for the output. This means PDF images remain high resolution.

Tables

knitr::kable() is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.

```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```

If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table package. It provides a tidy graphical interface for making tables.

Achieving custom styling of the table column width is beyond the scope of knitr, but the kableExtra package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html

Style Tips

The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.

If you are looking for potential extensions to the formatting, the bookdown package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

How do I find the date a video (.AVI .MP4) was actually recorded?

Have a try to exiftools or mediainfo, which provides you an export function as text. Just pay attention to daylight saving.

Pretty Printing JSON with React

const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")

const JSONDisplayer = ({children}) => (
    <div>
        <pre>{getJsonIndented(children)}</pre>
    </div>
)

Then you can easily use it:

const Demo = (props) => {
   ....
   return <JSONDisplayer>{someObj}<JSONDisplayer>
}

Process escape sequences in a string in Python

The correct thing to do is use the 'string-escape' code to decode the string.

>>> myString = "spam\\neggs"
>>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3 
>>> decoded_string = myString.decode('string_escape') # python2
>>> print(decoded_string)
spam
eggs

Don't use the AST or eval. Using the string codecs is much safer.

MS SQL 2008 - get all table names and their row counts in a DB

Try this it's simple and fast

SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
   INNER JOIN sys.sysindexes AS I ON T.object_id = I.id 
   AND I.indid < 2 ORDER  BY I.rows DESC

HTTP response header content disposition for attachments

Problems

The code has the following issues:

  • An Ajax call (<a4j:commandButton .../>) does not work with attachments.
  • Creating the output content must happen first.
  • Displaying the error messages also cannot use Ajax-based a4j tags.

Solution

  1. Change <a4j:commandButton .../> to <h:commandButton .../>.
  2. Update the source code:
    1. Change bw.write( getDomainDocument() ); to bw.write( document );.
    2. Add String document = getDomainDocument(); to the first line of the try/catch.
  3. Change the <a4j:outputPanel.../> (not shown) to <h:messages showDetail="false"/>.

Essentially, remove all the Ajax facilities related to the commandButton. It is still possible to display error messages and leverage the RichFaces UI style.

References

multiple prints on the same line in Python

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],

Static Initialization Blocks

I would say static block is just syntactic sugar. There is nothing you could do with static block and not with anything else.

To re-use some examples posted here.

This piece of code could be re-written without using static initialiser.

Method #1: With static

private static final HashMap<String, String> MAP;
static {
    MAP.put("banana", "honey");
    MAP.put("peanut butter", "jelly");
    MAP.put("rice", "beans");
  }

Method #2: Without static

private static final HashMap<String, String> MAP = getMap();
private static HashMap<String, String> getMap()
{
    HashMap<String, String> ret = new HashMap<>();
    ret.put("banana", "honey");
    ret.put("peanut butter", "jelly");
    ret.put("rice", "beans");
    return ret;
}

Why does the order in which libraries are linked sometimes cause errors in GCC?

I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs.

Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice.

For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.

Once you hit upon a solution document it so the next developer does not have to work it out again.

My old lecturer used to say, "high cohesion & low coupling", it’s still true today.

MySQL: When is Flush Privileges in MySQL really needed?

TL;DR

You should use FLUSH PRIVILEGES; only if you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE.

Build error: "The process cannot access the file because it is being used by another process"

Actually you should want "Enable the Visual Studio hosting process" checked. At least for VS2010 anyway. And I also have:

if exist "$(TargetPath).locked" del "$(TargetPath).locked" if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"

in the pre-build options. This problem has dogged me for a very long time and it wasn't until John W. mentioned this check box that I even took notice that it existed and low and behold it was already unchecked.

Also notice that -app-vshost.exe runs in the background even when not debugging. Which is what makes it successfully build and run every time I guess. It wasn't running before. And I also tried cleaning out the debug and release folders and changing the target type constantly and nothing worked except as described above. My solution before was to just wait 5 minutes between builds, which got super annoying and time-consuming to get anything done. I haven't seen any change in behavior where it mattered what tabs where open or XNA vs windows form or designers being opened. This issue occurred in 32-bit or 64-bit builds and didn't matter if I killed an app with ALT-F4 or killing it with task manager, which would, in theory, not allow the app to close or release resources. At first I thought it was a garbage collection issue.

ActivityCompat.requestPermissions not showing dialog box

Replace:

ActivityCompat.requestPermissions(this, new String[]{"Manifest.permission.READ_PHONE_STATE"}, 225);

with:

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

The actual string for that permission is not "Manifest.permission.READ_PHONE_STATE". Use the symbol Manifest.permission.READ_PHONE_STATE.

how to include js file in php?

If you truly wish to use PHP, you could use

include "file.php";

or

require "file.php";

and then in file.php, use a heredoc & echo it in.

file.php contents:
$some_js_code <<<_code
function myFunction()
{
   Alert("Some JS code would go here.");
}
_code;

At the top of your PHP file, bring in the file using either include or require then in head (or body section) echo it in

<?php
require "file.php";
?>
<html>
<head>
<?php
echo $some_js_code;
?>
</script>
</head>
<body>
</body>
</html>

Different way but it works. Just my $.02...

How to make a programme continue to run after log out from ssh?

You should try using nohup and running it in the background:

nohup sleep 3600 &

Releasing memory in Python

I'm guessing the question you really care about here is:

Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?

No, there is not. But there is an easy workaround: child processes.

If you need 500MB of temporary storage for 5 minutes, but after that you need to run for another 2 hours and won't touch that much memory ever again, spawn a child process to do the memory-intensive work. When the child process goes away, the memory gets released.

This isn't completely trivial and free, but it's pretty easy and cheap, which is usually good enough for the trade to be worthwhile.

First, the easiest way to create a child process is with concurrent.futures (or, for 3.1 and earlier, the futures backport on PyPI):

with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
    result = executor.submit(func, *args, **kwargs).result()

If you need a little more control, use the multiprocessing module.

The costs are:

  • Process startup is kind of slow on some platforms, notably Windows. We're talking milliseconds here, not minutes, and if you're spinning up one child to do 300 seconds' worth of work, you won't even notice it. But it's not free.
  • If the large amount of temporary memory you use really is large, doing this can cause your main program to get swapped out. Of course you're saving time in the long run, because that if that memory hung around forever it would have to lead to swapping at some point. But this can turn gradual slowness into very noticeable all-at-once (and early) delays in some use cases.
  • Sending large amounts of data between processes can be slow. Again, if you're talking about sending over 2K of arguments and getting back 64K of results, you won't even notice it, but if you're sending and receiving large amounts of data, you'll want to use some other mechanism (a file, mmapped or otherwise; the shared-memory APIs in multiprocessing; etc.).
  • Sending large amounts of data between processes means the data have to be pickleable (or, if you stick them in a file or shared memory, struct-able or ideally ctypes-able).

How to use System.Net.HttpClient to post a complex type?

The generic HttpRequestMessage<T> has been removed. This :

new HttpRequestMessage<Widget>(widget)

will no longer work.

Instead, from this post, the ASP.NET team has included some new calls to support this functionality:

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

So, the new code (from dunston) becomes:

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

Run task only if host does not belong to a group

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

group_names is a list (array) of all the groups the current host is in.

How to add RSA key to authorized_keys file?

mkdir -p ~/.ssh/

To overwrite authorized_keys

cat your_key > ~/.ssh/authorized_keys

To append to the end of authorized_keys

cat your_key >> ~/.ssh/authorized_keys

Compiling an application for use in highly radioactive environments

Perhaps it would help to know does it mean for the hardware to be "designed for this environment". How does it correct and/or indicates the presence of SEU errors ?

At one space exploration related project, we had a custom MCU, which would raise an exception/interrupt on SEU errors, but with some delay, i.e. some cycles may pass/instructions be executed after the one insn which caused the SEU exception.

Particularly vulnerable was the data cache, so a handler would invalidate the offending cache line and restart the program. Only that, due to the imprecise nature of the exception, the sequence of insns headed by the exception raising insn may not be restartable.

We identified the hazardous (not restartable) sequences (like lw $3, 0x0($2), followed by an insn, which modifies $2 and is not data-dependent on $3), and I made modifications to GCC, so such sequences do not occur (e.g. as a last resort, separating the two insns by a nop).

Just something to consider ...

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

I recently stuck in with this error while building my containerized jar applications with Bamboo:

org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye

After many hours of researching I fixed it. And I thought it would be useful to share my solution here.

So the error happen every time when bamboo run mvn clean package command for java applications in the docker containers. I am no Maven expert but the trouble was in Surefire and Junit4 plugins included in spring-boot as maven dependency.

To fix it you need to replace Junit4 for Junit5 and override Surefire plugin in you pom.xml.

1.Inside spring boot dependency insert exclusion:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <!-- FIX BAMBOO DEPLOY>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
    <!---->
</dependency>

2. Add new Junit5 dependencies:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-runner</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-surefire-provider</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>

3. Insert new plugin inside plugins section

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <dependencies>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-surefire-provider</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>
</plugin>

That's should be enough to repair bamboo builds. Don't forget also transform all Junit4 tests to support Junit5.

how to query LIST using linq

I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.

Example:
enter image description here

Removing duplicate objects with Underscore for Javascript

You can do it in a shorthand as:

_.uniq(foo, 'a')

Is Xamarin free in Visual Studio 2015?

Seems like now it's free for small teams and students, according to Scott Hanselman post https://twitter.com/shanselman/status/715568774418595840

https://visualstudio.microsoft.com/vs/pricing/

Visual Studio Community
FREE

A free, full-featured and extensible IDE for Windows users to create Android and iOS apps with Xamarin, as well as Windows apps, web apps, and cloud services.

  • Students
  • OSS development
  • Small teams

and

Xamarin Studio Community FREE

A free, full-featured IDE for Mac users to create Android and iOS apps using Xamarin.

  • Students
  • OSS development
  • Small teams

How to determine whether a given Linux is 32 bit or 64 bit?

If you shift 1 left by 32 and you get 1, your system is 32 bit. If you shift 1 left by 64 and you get 1, your system is 64 bit.

In other words,

if echo $((1<<32)) gives 1 then your system is 32 bit.

if echo $((1<<64)) gives 1 then your system is 64 bit.

CSS3 background image transition

You can transition background-image. Use the CSS below on the img element:

-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;

This is supported natively by Chrome, Opera and Safari. Firefox hasn't implemented it yet (bugzil.la). Not sure about IE.

How do you upload a file to a document library in sharepoint?

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

How I can get web page's content and save it into the string variable

I recommend not using WebClient.DownloadString. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM () incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!

Instead, this slight variation will work correctly with BOMs:

string ReadTextFromUrl(string url) {
    // WebClient is still convenient
    // Assume UTF8, but detect BOM - could also honor response charset I suppose
    using (var client = new WebClient())
    using (var stream = client.OpenRead(url))
    using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
        return textReader.ReadToEnd();
    }
}

MySQL Like multiple values

Or if you need to match only the beginning of words:

WHERE interests LIKE 'sports%' OR interests LIKE 'pub%'

you can use the regexp caret matches:

WHERE interests REGEXP '^sports|^pub'

https://www.regular-expressions.info/anchors.html

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained here:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

How to list files in an android directory?

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

writing integer values to a file using out.write()

any of these should work

outf.write("%s" % num)

outf.write(str(num))

print >> outf, num

Jquery Chosen plugin - dynamically populate list by Ajax

The chosen answer is outdated, same goes to meltingice /ajax-chosen plugin.

With Select2 plugin got many bugs which is i can't resolve it.

Here my answer for this question.

I integrated my solution with function trigger after user type. Thanks to this answer : https://stackoverflow.com/a/5926782/4319179.

//setup before functions
  var typingTimer;                //timer identifier
  var doneTypingInterval = 2000;  //time in ms (2 seconds)
  var selectID = 'YourSelectId';    //Hold select id
  var selectData = [];           // data for unique id array

  //on keyup, start the countdown
  $('#' + selectID + '_chosen .chosen-choices input').keyup(function(){

      // Change No Result Match text to Searching.
      $('#' + selectID + '_chosen .no-results').html('Searching = "'+ $('#' + selectID + '_chosen .chosen-choices input').val() + '"');


      clearTimeout(typingTimer);  //Refresh Timer on keyup 
      if ($('#' + selectID + '_chosen .chosen-choices input').val()) {

           typingTimer = setTimeout(doneTyping, doneTypingInterval);  //Set timer back if got value on input

      }

  });

  //user is "finished typing," do something
  function doneTyping () {

      var inputData = $('#' + selectID + '_chosen .chosen-choices input').val();  //get input data

      $.ajax({
        url: "YourUrl",
         data: {data: inputData},
        type:'POST',
        dataType: "json",
        beforeSend: function(){
          // Change No Result Match to Getting Data beforesend
          $('#' + selectID + '_chosen .no-results').html('Getting Data = "'+$('#' + selectID + '_chosen .chosen-choices input').val()+'"');
    },
        success: function( data ) { 

          // iterate data before append
          $.map( data, function( item ) {

            // matching data eg: by id or something unique; if data match: <option> not append - else: append <option>
            // This will prevent from select the same thing twice.
            if($.inArray(item.attr_hash,selectData) == -1){

              // if not match then append in select
              $('#' + selectID ).append('<option id="'+item.id+'" data-id = "'+item.id+'">' + item.data + '</option>');

            }            

          });

          // Update chosen again after append <option>
          $('#' + selectID ).trigger("chosen:updated");

        }
      });

  }

  // Chosen event listen on input change eg: after select data / deselect this function will be trigger
  $('#' + selectID ).on('change', function() {

    // get select jquery object
    var domArray = $('#' + selectID ).find('option:selected');

    // empty array data
    selectData = [];

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

      // Push unique data to array (for matching purpose)
      selectData.push( $(domArray[i]).data('id') );

    }

    // Replace select <option> to only selected option
    $('#' + selectID ).html(domArray);

    // Update chosen again after replace selected <option>
    $('#' + selectID ).trigger("chosen:updated");

  });

Group by in LINQ

You can also Try this:

var results= persons.GroupBy(n => new { n.PersonId, n.car})
                .Select(g => new {
                               g.Key.PersonId,
                               g.Key.car)}).ToList();

How to link to part of the same document in Markdown?

In addition to the above answers,

When setting the option number_sections: true in the YAML header:

number_sections: TRUE

RMarkdown will autonumber your sections.

To reference those autonumbered sections simply put the following in your R Markdown file:

[My Section]

Where My Section is the name of the section

This seems to work regardless of the section level:

# My section

## My section

### My section

TypeScript for ... of with index / key?

Or another old school solution:

var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
    console.log(item); // 9,2,5
    i++;
}

Command line: search and replace in all filenames matched by grep

This works using grep without needing to use perl or find.

grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

How to Free Inode Usage?

you could see this info

for i in /var/run/*;do echo -n "$i "; find $i| wc -l;done | column -t

Check with jquery if div has overflowing elements

I had the same question as the OP, and none of those answers fitted my needs. I needed a simple condition, for a simple need.

Here's my answer:

if ($("#myoverflowingelement").prop('scrollWidth') > $("#myoverflowingelement").width() ) {
  alert("this element is overflowing !!");
}
else {
 alert("this element is not overflowing!!");
}

Also, you can change scrollWidth by scrollHeight if you need to test the either case.

How to set iframe size dynamically

If you use jquery, it can be done by using $(window).height();

<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>

DataTables: Cannot read property style of undefined

You said any suggestions wold be helpful, so currently I resolved my DataTables "cannot read property 'style' of undefined" problem but my problem was basically using wrong indexes at data table initiation phase's columnDefs section. I got 9 columns and the indexes are 0, 1, 2, .. , 8 but I was using indexes for 9 and 10 so after fixing the wrong index issue the fault has disappeared. I hope this helps.

In short, you got to watch your columns amount and indexes if consistent everywhere.

Buggy Code:

    jQuery('#table').DataTable({
        "ajax": {
            url: "something_url",
            type: 'POST'
        },
        "processing": true,
        "serverSide": true,
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "columns": [
            { "data": "cl1" },
            { "data": "cl2" },
            { "data": "cl3" },
            { "data": "cl4" },
            { "data": "cl5" },
            { "data": "cl6" },
            { "data": "cl7" },
            { "data": "cl8" },
            { "data": "cl9" }
        ],
        columnDefs: [
            { orderable: false, targets: [ 7, 9, 10 ] } //This part was wrong
        ]
    });

Fixed Code:

    jQuery('#table').DataTable({
        "ajax": {
            url: "something_url",
            type: 'POST'
        },
        "processing": true,
        "serverSide": true,
        "bPaginate": true,
        "sPaginationType": "full_numbers",
        "columns": [
            { "data": "cl1" },
            { "data": "cl2" },
            { "data": "cl3" },
            { "data": "cl4" },
            { "data": "cl5" },
            { "data": "cl6" },
            { "data": "cl7" },
            { "data": "cl8" },
            { "data": "cl9" }
        ],
        columnDefs: [
            { orderable: false, targets: [ 5, 7, 8 ] } //This part is ok now
        ]
    });

ES6 exporting/importing in index file

You can easily re-export the default import:

export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';

There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';.

sorting a List of Map<String, String>

You should implement a Comparator<Map<String, String>> which basically extracts the "name" value from the two maps it's passed, and compares them.

Then use Collections.sort(list, comparator).

Are you sure a Map<String, String> is really the best element type for your list though? Perhaps you should have another class which contains a Map<String, String> but also has a getName() method?

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

Why cannot change checkbox color whatever I do?

Technically, it is possible to change the color of anything with CSS. As mentioned, you can't change the background-color or color but you can use CSS filters. For example:

input[type="checkbox"] { /* change "blue" browser chrome to yellow */
  filter: invert(100%) hue-rotate(18deg) brightness(1.7);
}

If you are really looking for design control over checkboxes though, your best bet is to do the "hidden" checkbox and style an adjacent element such as a div.

How do I create a constant in Python?

Here is an implementation of a "Constants" class, which creates instances with read-only (constant) attributes. E.g. can use Nums.PI to get a value that has been initialized as 3.14159, and Nums.PI = 22 raises an exception.

# ---------- Constants.py ----------
class Constants(object):
    """
    Create objects with read-only (constant) attributes.
    Example:
        Nums = Constants(ONE=1, PI=3.14159, DefaultWidth=100.0)
        print 10 + Nums.PI
        print '----- Following line is deliberate ValueError -----'
        Nums.PI = 22
    """

    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    # NOTE: This is only called if self lacks the attribute.
    # So it does not interfere with get of 'self._d', etc.
    def __getattr__(self, name):
        return self._d[name]

    # ASSUMES '_..' attribute is OK to set. Need this to initialize 'self._d', etc.
    #If use as keys, they won't be constant.
    def __setattr__(self, name, value):
        if (name[0] == '_'):
            super(Constants, self).__setattr__(name, value)
        else:
            raise ValueError("setattr while locked", self)

if (__name__ == "__main__"):
    # Usage example.
    Nums = Constants(ONE=1, PI=3.14159, DefaultWidth=100.0)
    print 10 + Nums.PI
    print '----- Following line is deliberate ValueError -----'
    Nums.PI = 22

Thanks to @MikeGraham 's FrozenDict, which I used as a starting point. Changed, so instead of Nums['ONE'] the usage syntax is Nums.ONE.

And thanks to @Raufio's answer, for idea to override __ setattr __.

Or for an implementation with more functionality, see @Hans_meine 's named_constants at GitHub

What's a good IDE for Python on Mac OS X?

Have tried many different (Kate, Eclipse, Scite, Vim, Komodo): each one have some glitches, either limited functions, or slow and unresponsive. Final choice after many years: Emacs + ropemacs + flymake. Rope project file open dialog is extremely quick. Rope refactoring and code assist functions are super helpful. Flymake shows syntax mistakes. Emacs is the most configurable editor. I am very happy with this config. Python related part of config is here: public.halogen-dg.com browser/alex-emacs-settings/configs/cfg_python.el

Set size on background image with CSS?

Not too hard, if you're not afraid of going a little more in depth :)

There's one forgotten argument:

background-size: contain;

This won't stretch your background-image as it would do with cover. It would stretch until the longer side reaches the width or height of the outer container and therefore preserving the image.

Edit: There's also -webkit-background-size and -moz-background-size.

The background-size property is supported in IE9+, Firefox 4+, Opera, Chrome, and Safari 5+.

- Source: W3 Schools

What are unit tests, integration tests, smoke tests, and regression tests?

REGRESSION TESTING-

"A regression test re-runs previous tests against the changed software to ensure that the changes made in the current software do not affect the functionality of the existing software."

How to sum up elements of a C++ vector?

I'm a Perl user, an a game we have is to find every different ways to increment a variable... that's not really different here. The answer to how many ways to find the sum of the elements of a vector in C++ is probably an infinity...

My 2 cents:

Using BOOST_FOREACH, to get free of the ugly iterator syntax:

sum = 0;
BOOST_FOREACH(int & x, myvector){
  sum += x;
}

iterating on indices (really easy to read).

int i, sum = 0;
for (i=0; i<myvector.size(); i++){
  sum += myvector[i];
}

This other one is destructive, accessing vector like a stack:

while (!myvector.empty()){
   sum+=myvector.back();
   myvector.pop_back();
}

How to set DOM element as the first child?

2018 version - prepend

parent.prepend(newChild)  // [newChild, child1, child2]

This is modern JS! It is more readable than previous options. It is currently available in Chrome, FF, and Opera.

The equivalent for adding to the end is append, replacing the old appendChild

parent.append(newChild)  // [child1, child2, newChild]

Advanced usage

  1. You can pass multiple values (or use spread operator ...).
  2. Any string value will be added as a text element.

Examples:

parent.prepend(newChild, "foo")   // [newChild, "foo", child1, child2]

const list = ["bar", newChild]
parent.append(...list, "fizz")    // [child1, child2, "bar", newChild, "fizz"]

Related DOM methods

  1. Read More - child.before and child.after
  2. Read More - child.replaceWith

Mozilla Documentation

Can I Use

How to remove an element from an array in Swift

To remove elements from an array, use the remove(at:), removeLast() and removeAll().

yourArray = [1,2,3,4]

Remove the value at 2 position

yourArray.remove(at: 2)

Remove the last value from array

yourArray.removeLast()

Removes all members from the set

yourArray.removeAll()

How to increment an iterator by 2?

http://www.cplusplus.com/reference/std/iterator/advance/

std::advance(it,n);

where n is 2 in your case.

The beauty of this function is, that If "it" is an random access iterator, the fast

it += n

operation is used (i.e. vector<,,>::iterator). Otherwise its rendered to

for(int i = 0; i < n; i++)
    ++it;

(i.e. list<..>::iterator)

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

Display PDF within web browser

I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.

<iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

Cordova : Requirements check failed for JDK 1.8 or greater

As per official Cordova documentation it supports only JDK 1.8 not greater till the date (April 2018). Or there might be problem with version detection script within cordova.

Cordova: Installing the requirements

Insert and set value with max()+1 problems

We declare a variable 'a'

SET **@a** = (SELECT MAX( customer_id ) FROM customers) +1;

INSERT INTO customers
  ( customer_id, firstname, surname )
VALUES 
  (**@a**, 'jim', 'sock')

What does status=canceled for a resource mean in Chrome Developer Tools?

I have embedded all types of font as well as woff, woff2, ttf when I embed a web font in style sheet. Recently I noticed that Chrome cancels request to ttf and woff when woff2 is present. I use Chrome version 66.0.3359.181 right now but I am not sure when Chrome started canceling of extra font types.

iPhone X / 8 / 8 Plus CSS media queries

If your page is missing meta[@name="viewport"] element within its DOM, then the following could be used to detect a mobile device:

@media only screen and (width: 980px), (hover: none) { … }

If you want to avoid false-positives with desktops that just magically have their viewport set to 980px like all the mobile browsers do, then a device-width test could also be added into the mix:

@media only screen and (max-device-width: 800px) and (width: 980px), (hover: none) { … }

Per the list at https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries, the new hover property would appear to be the final new way to detect that you've got yourself a mobile device that doesn't really do proper hover; it's only been introduced in 2018 with Firefox 64 (2018), although it's been supported since 2016 with Android Chrome 50 (2016), or even since 2014 with Chrome 38 (2014):

Switching between GCC and Clang/LLVM using CMake

System wide C change on Ubuntu:

sudo update-alternatives --config cc

System wide C++ change on Ubuntu:

sudo update-alternatives --config c++

For each of the above, press Selection number (1) and Enter to select Clang:

  Selection    Path            Priority   Status
------------------------------------------------------------
* 0            /usr/bin/gcc     20        auto mode
  1            /usr/bin/clang   10        manual mode
  2            /usr/bin/gcc     20        manual mode
Press enter to keep the current choice[*], or type selection number:

How to show full column content in a Spark Dataframe?

The following answer applies to a Spark Streaming application.

By setting the "truncate" option to false, you can tell the output sink to display the full column.

val query = out.writeStream
          .outputMode(OutputMode.Update())
          .format("console")
          .option("truncate", false)
          .trigger(Trigger.ProcessingTime("5 seconds"))
          .start()

newline in <td title="">

This should be OK, but is Internet Explorer specific:

<td title="lineone
linetwo 
etc...">

As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.

How to ignore certain files in Git

Create a .gitignore in the directory where .git is. You can list files in it separated by a newline. You also can use wildcards:

*.o
.*.swp

How can I calculate the difference between two dates?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];

int numberOfDays = secondsBetween / 86400;

NSLog(@"There are %d days in between the two dates.", numberOfDays);

EDIT:

Remember, NSDate objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter, the NSDateFormatter converts the time from the configured timezone. Therefore, the number of seconds between two NSDate objects will always be time-zone-agnostic.

Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.

SQL Insert Query Using C#

private void button1_Click(object sender, EventArgs e)
    {
        String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
        try
        {
            using (SqlCommand command = new SqlCommand(query, con))
            {

                command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
                command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
                command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
                command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);


                con.Open();
                int result = command.ExecuteNonQuery();

                // Check Error
                if (result < 0)
                    MessageBox.Show("Error");

                MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                con.Close();
                loader();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }

Creating a Custom Event

Yes you can create events on objects, here is an example;

public class Foo
{
    public delegate void MyEvent(object sender, object param);
    event MyEvent OnMyEvent;

    public Foo()
    {
        this.OnMyEvent += new MyEvent(Foo_OnMyEvent);
    }

    void Foo_OnMyEvent(object sender, object param)
    {
        if (this.OnMyEvent != null)
        {
            //do something
        }
    }



    void RaiseEvent()
    {
        object param = new object();
        this.OnMyEvent(this,param);
    }
}

How do you overcome the HTML form nesting limitation?

My solution is to have the buttons call JS functions which write and then submit forms outwith the main form

<head>
<script>
function removeMe(A, B){
        document.write('<form name="removeForm" method="POST" action="Delete.php">');
        document.write('<input type="hidden" name="customerID" value="' + A + '">');
        document.write('<input type="hidden" name="productID" value="' + B + '">');
        document.write('</form>');
        document.removeForm.submit();
}
function insertMe(A, B){
        document.write('<form name="insertForm" method="POST" action="Insert.php">');
        document.write('<input type="hidden" name="customerID" value="' + A + '">');
        document.write('<input type="hidden" name="productID" value="' + B + '">');
        document.write('</form>');
        document.insertForm.submit();
}
</script>
</head>

<body>
<form method="POST" action="main_form_purpose_page.php">

<input type="button" name="remove" Value="Remove" onclick="removeMe('$customerID','$productID')">
<input type="button" name="insert" Value="Insert" onclick="insertMe('$customerID','$productID')">

<input type="submit" name="submit" value="Submit">
</form>
</body>

How to navigate through a vector using iterators? (C++)

Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[].

To access arbitrary elements in a vector vec, you can use the following:

vec.begin()                  // 1st
vec.begin()+1                // 2nd
// ...
vec.begin()+(i-1)            // ith
// ...
vec.begin()+(vec.size()-1)   // last

The following is an example of a typical access pattern (earlier versions of C++):

int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

The advantage of using iterator is that you can apply the same pattern with other containers:

sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
    sum += *it;
}

For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).

Another option using std::for_each and lambdas:

sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });

Since C++11 you can use auto to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):

sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
    sum += *it;
}

And, in addition, there is a simpler for-each variant:

sum = 0;
for (auto value : vec) {
    sum += value;
}

And finally there is also std::accumulate where you have to be careful whether you are adding integer or floating point numbers.

Installing jQuery?

Well, as most of the answers pointed out, you can include the jQuery file locally as well as use Google's CDN/Microsoft CDN servers. On choosing Google vs. Microsoft CDN go Google_CDN vs. Microsoft_CDN depending on your requirement.

Generally for intranet applications include jQuery file locally and never use the CDN method since for intranet, the LAN is 10x times faster than Internet. For Internet and public facing applications use a hybrid approach as suggested by cowgod elsewhere. Also don't forget to use the nice tool JS_Compressor to compress the extra JavaScript code you add to your jQuery library. It makes JavaScript really fast.

How do I convert Int/Decimal to float in C#?

The same as an int:

float f = 6;

Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:

int i = 8;
float f = Convert.ToSingle(i);

Or you can just cast an int to a float:

float f = (float)i;

Cannot run the macro... the macro may not be available in this workbook

Delete your name macro and build again. I did this, and the macro worked.

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

How to properly set Column Width upon creating Excel file? (Column properties)

I have change all columns width in my case as

            worksheet.Columns[1].ColumnWidth = 7;
            worksheet.Columns[2].ColumnWidth = 15;
            worksheet.Columns[3].ColumnWidth = 15;
            worksheet.Columns[4].ColumnWidth = 15;
            worksheet.Columns[5].ColumnWidth = 18;
            worksheet.Columns[6].ColumnWidth = 8;
            worksheet.Columns[7].ColumnWidth = 13;
            worksheet.Columns[8].ColumnWidth = 17;
            worksheet.Columns[9].ColumnWidth = 17;

Note: Columns in worksheet start with 1 not from 0 as in Arrary.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For me ComboBox.DropDownClosed Event did it.

private void cbValueType_DropDownClosed(object sender, EventArgs e)
    {
        if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
        {
            // change sel Index of other Combo for example
            cbDataType.SelectedIndex = someotherIntValue;
        }
    }

Read file content from S3 bucket with boto3

boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline or readlines.

s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
    key = obj.key
    body = obj.get()['Body'].read()

git: fatal: Could not read from remote repository

I had the same error, which brought me to this answer that didn't help me. I was trying to create a new "bare" repository for the first time using the commands below to track to an NTFS location:

cd myrepository
git init --bare \\myserver.mycompany.local\myrepository.git
git init
git status
git add .
git status
git commit -m "Initial Commit"
git remote add origin \\myserver.mycompany.local\myrepository.git
git push -u origin master
git status

My problem turned out to be using the back slashes instead of forward slashes in the NTFS location when trying to add origin to set the (new) tracked upstream branch.

I had to remove the origin using:

git remote rm origin

Then add the origin again using the expected forward slashes

git remote add origin //myserver.mycompany.local/myrepository.git

Hope this helps someone in the future.

why should I make a copy of a data frame in pandas

Assumed you have data frame as below

df1
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

When you would like create another df2 which is identical to df1, without copy

df2=df1
df2
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

And would like modify the df2 value only as below

df2.iloc[0,0]='changed'

df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

At the same time the df1 is changed as well

df1
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Since two df as same object, we can check it by using the id

id(df1)
140367679979600
id(df2)
140367679979600

So they as same object and one change another one will pass the same value as well.


If we add the copy, and now df1 and df2 are considered as different object, if we do the same change to one of them the other will not change.

df2=df1.copy()
id(df1)
140367679979600
id(df2)
140367674641232

df1.iloc[0,0]='changedback'
df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Good to mention, when you subset the original dataframe, it is safe to add the copy as well in order to avoid the SettingWithCopyWarning

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

To put a sequence or another numpy array into a numpy array, Just change this line:

kOUT=np.zeros(N+1)

to:

kOUT=np.asarray([None]*(N+1))

Or:

kOUT=np.zeros((N+1), object)

Python: How to remove empty lists from a list?

Calling filter with None will filter out all falsey values from the list (which an empty list is)

list2 = filter(None, list1)

Initialize a byte array to a certain value, other than the default null?

For small arrays use array initialisation syntax:

var sevenItems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };

For larger arrays use a standard for loop. This is the most readable and efficient way to do it:

var sevenThousandItems = new byte[7000];
for (int i = 0; i < sevenThousandItems.Length; i++)
{
    sevenThousandItems[i] = 0x20;
}

Of course, if you need to do this a lot then you could create a helper method to help keep your code concise:

byte[] sevenItems = CreateSpecialByteArray(7);
byte[] sevenThousandItems = CreateSpecialByteArray(7000);

// ...

public static byte[] CreateSpecialByteArray(int length)
{
    var arr = new byte[length];
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] = 0x20;
    }
    return arr;
}

how to get the cookies from a php curl into a variable

This does it without regexps, but requires the PECL HTTP extension.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
curl_close($ch);

$headers = http_parse_headers($result);
$cookobjs = Array();
foreach($headers AS $k => $v){
    if (strtolower($k)=="set-cookie"){
        foreach($v AS $k2 => $v2){
            $cookobjs[] = http_parse_cookie($v2);
        }
    }
}

$cookies = Array();
foreach($cookobjs AS $row){
    $cookies[] = $row->cookies;
}

$tmp = Array();
// sort k=>v format
foreach($cookies AS $v){
    foreach ($v  AS $k1 => $v1){
        $tmp[$k1]=$v1;
    }
}

$cookies = $tmp;
print_r($cookies);

How to remove &quot; from my Json in javascript?

i used replace feature in Notepad++ and replaced &quot; (without quotes) with " and result was valid json

How can I get query string values in JavaScript?

tl;dr

A quick, complete solution, which handles multivalued keys and encoded characters.

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})

//using ES6   (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
Multi-lined:
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})

What is all this code...
"null-coalescing", short-circuit evaluation
ES6 Destructuring assignments, Arrow functions, Template strings

Example:
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> qd.a[1]    // "5"
> qd["a"][1] // "5"



Read more... about the Vanilla JavaScript solution.

To access different parts of a URL use location.(search|hash)

Easiest (dummy) solution

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
  • Handles empty keys correctly.
  • Overrides multi-keys with last value found.
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined

Multi-valued keys

Simple key check (item in dict) ? dict.item.push(val) : dict.item = [val]

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})
  • Now returns arrays instead.
  • Access values by qd.key[index] or qd[key][index]
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]

Encoded characters?

Use decodeURIComponent() for the second or both splits.

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
Example:
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]



From comments

*!!! Please note, that decodeURIComponent(undefined) returns string "undefined". The solution lies in a simple usage of &&, which ensures that decodeURIComponent() is not called on undefined values. (See the "complete solution" at the top.)

v = v && decodeURIComponent(v);


If the querystring is empty (location.search == ""), the result is somewhat misleading qd == {"": undefined}. It is suggested to check the querystring before launching the parsing function likeso:

if (location.search) location.search.substr(1).split("&").forEach(...)

Background color on input type=button :hover state sticks in IE

You need to make sure images come first and put in a comma after the background image call. then it actually does work:

    background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */

How to remove application from app listings on Android Developer Console

The one exception worth noting is that while you can't delete apps, the folks over at Google Play Developer Support are able to on their end if the app is both unpublished and has 0 lifetime installs. So if your app has 0 lifetime installs, you might be in luck.

First you will need unpublish the app and wait 24 hours (to allow global stats to update and ensure that no last-minute installs happened). Assuming no last-minute installs happen over those 24 hours, you can contact Google Play Developer Support and check to see if they can delete it.

Please note that their requirement for 0 installs is a hard requirement. No exceptions can be made (not even if you installed the app yourself for testing purposes).

How can I "disable" zoom on a mobile web page?

You can accomplish the task by simply adding the following 'meta' element into your 'head':

<meta name="viewport" content="user-scalable=no">

Adding all the attributes like 'width','initial-scale', 'maximum-width', 'maximum-scale' might not work. Therefore, just add the above element.

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

How to change line color in EditText

 <EditText
        android:id="@+id/et_password_tlay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:textColorHint="#9e9e9e"
        android:backgroundTint="#000"
        android:singleLine="true"
        android:drawableTint="#FF4081"
        android:paddingTop="25dp"
        android:textColor="#000"
        android:paddingBottom="5dp"
        android:inputType="textPassword"/>

    <View
        android:id="@+id/UnderLine"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@+id/et_password_tlay"
        android:layout_centerHorizontal="true"
        android:background="#03f94e" />

**it one of doing with view **

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

Have you got the driver installed? If you go into Start > Settings > Control Panel > Administrative Tools and click the Data Sources, then select the Drivers tab your driver info should be registered there.

Failing that it may be easier to simply set up a DSN connection to test with.

You can define multiple connection strings of course and set-up a 'mode' for working on different machines.

Also there's ConnectionStrings.com.

-- EDIT --

Just to further this, I found this thread on another site.

How to add DOM element script to head section?

If injecting multiple script tags in the head like this with mix of local and remote script files a situation may arise where the local scripts that are dependent on external scripts (such as loading jQuery from googleapis) will have errors because the external scripts may not be loaded before the local ones are.

So something like this would have a problem: ("jQuery is not defined" in jquery.some-plugin.js).

var head = document.getElementsByTagName('head')[0];

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js";
head.appendChild(script);

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/jquery.some-plugin.js";
head.appendChild(script);

Of course this situation is what the .onload() is for, but if multiple scripts are being loaded that can be cumbersome.

As a resolution to this situation, I put together this function that will keep a queue of scripts to be loaded, loading each subsequent item after the previous finishes, and returns a Promise that resolves when the script (or the last script in the queue if no parameter) is done loading.

load_script = function(src) {
    // Initialize scripts queue
    if( load_script.scripts === undefined ) {
        load_script.scripts = [];
        load_script.index = -1;
        load_script.loading = false;
        load_script.next = function() {
            if( load_script.loading ) return;

            // Load the next queue item
            load_script.loading = true;
            var item = load_script.scripts[++load_script.index];
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = item.src;
            // When complete, start next item in queue and resolve this item's promise
            script.onload = () => {
                load_script.loading = false;
                if( load_script.index < load_script.scripts.length - 1 ) load_script.next();
                item.resolve();
            };
            head.appendChild(script);
        };
    };

    // Adding a script to the queue
    if( src ) {
        // Check if already added
        for(var i=0; i < load_script.scripts.length; i++) {
            if( load_script.scripts[i].src == src ) return load_script.scripts[i].promise;
        }
        // Add to the queue
        var item = { src: src };
        item.promise = new Promise(resolve => {item.resolve = resolve;});
        load_script.scripts.push(item);
        load_script.next();
    }

    // Return the promise of the last queue item
    return load_script.scripts[ load_script.scripts.length - 1 ].promise;
};

With this adding scripts in order ensuring the previous are done before staring the next can be done like...

["https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js",
 "/jquery.some-plugin.js",
 "/dependant-on-plugin.js",
].forEach(load_script);

Or load the script and use the return Promise to do work when it's complete...

load_script("some-script.js")
.then(function() {
    /* some-script.js is done loading */
});

Best way to check for null values in Java?

I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.

That doesn't always feel right to me.

SQL - ORDER BY 'datetime' DESC

  1. use single quotes for strings
  2. do NOT put single quotes around table names(use ` instead)
  3. do NOT put single quotes around numbers (you can, but it's harder to read)
  4. do NOT put AND between ORDER BY and LIMIT
  5. do NOT put = between ORDER BY, LIMIT keywords and condition

So you query will look like:

SELECT post_datetime 
FROM post 
WHERE type = 'published' 
ORDER BY post_datetime DESC 
LIMIT 3

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

Are list-comprehensions and functional functions faster than "for loops"?

If you check the info on python.org, you can see this summary:

Version Time (seconds)
Basic loop 3.47
Eliminate dots 2.45
Local variable & no dots 1.79
Using map function 0.54

But you really should read the above article in details to understand the cause of the performance difference.

I also strongly suggest you should time your code by using timeit. At the end of the day, there can be a situation where, for example, you may need to break out of for loop when a condition is met. It could potentially be faster than finding out the result by calling map.

Installing tensorflow with anaconda in windows

"Conda" installs some of the special packages that might have compiled in C or other languages. You can use "pip install tensorflow" and it will work.

Append a tuple to a list - what's the difference between two ways?

The tuple function takes only one argument which has to be an iterable

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

Try making 3,4 an iterable by either using [3,4] (a list) or (3,4) (a tuple)

For example

a_list.append(tuple((3, 4)))

will work

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Build an iOS app without owning a mac?

You can use Smartface for developing your app with javascript and deploy to stores directly without a Mac. What they say is below.

With the Cloud Build module, Smartface removes all the hassle of application deployment. You don’t need to worry about managing code signing certificates and having a Mac to sign your apps. Smartface Cloud can store all your iOS certificates and Android keystores in one place and signing and building is fully in the cloud. No matter which operating system you use, you can get store-ready (or enterprise distribution) binaries. Smartface frees you from the lock-in to Mac and allows you to use your favorite operating system for development.

https://www.smartface.io/smartface/

how to enable sqlite3 for php?

one thing I want to add , before you try to install

apt-get install php5-sqlite

or

apt-get install php5-sqlite3 

search the given package is available or not :-

 # apt-cache search 'php5'

After that you get :-

php5-rrd - rrd module for PHP 5

php5-sasl - Cyrus SASL extension for PHP 5

php5-snmp - SNMP module for php5

**php5-sqlite - SQLite module for php5**

php5-svn - PHP Bindings for the Subversion Revision control system

php5-sybase - Sybase / MS SQL Server module for php5

Here you get an idea about whether your version support or not .. in my system I get php5-sqlite - SQLite module for php5 so I prefer to install

**apt-get install php5-sqlite**

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

How to use the toString method in Java?

the toString() converts the specified object to a string value.

What are the "spec.ts" files generated by Angular CLI for?

The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test command.

You can use this for some further reading:

https://angular.io/guide/testing

Download the Android SDK components for offline install

Here is how I figured it out. I am behind corporate firewall too.

Go to Chrome or your Internet Settings by clicking the wrench in Chrome --> Settings --> Under the Hood --> Network --> Change Proxy Settings

Click on LAN Settings and then Advanced. Copy the proxy server address and port.

Mostly the connection refused link occurs when trying to download SDK packages through Eclipse.

Navigate to the SDK Manager.exe and double click on it. Once it starts click on Tools --> Options and then enter the proxy server address and the Port #

Check the checkbox force https:// to http:// That's it your SDK Manager will now be able to download packages from google remote site without any issue even from behind a firewall.

I am on Windows by the way. Tried everything and this works great.

Deleting a pointer in C++

int value, *ptr;

value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.

ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.

ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.

Clear input fields on form submit

By this way, you hold a form by his ID and throw all his content. This technic is fastiest.

document.forms["id_form"].reset();

Regex: Check if string contains at least one digit

If anybody falls here from google, this is how to check if string contains at least one digit in C#:

With Regex

if (Regex.IsMatch(myString, @"\d"))
{
  // do something
}

Info: necessary to add using System.Text.RegularExpressions

With linq:

if (myString.Any(c => Char.IsDigit(c)))
{
  // do something
}

Info: necessary to add using System.Linq

Print in new line, java

You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.

Since Java 1.7

System.lineSeparator()

Pre Java 1.7

System.getProperty("line.separator")

XML Parser for C

Could you give some indication of what platforms you are writing for? This should weigh heavily on what is 'best'. You might find a super 'xml-foo' library that does not ship commonly on most systems by default .. while its great, the lack of the library might prevent (or at least) annoy users.

Mostly, I use libxml2 .. because its standard or easy to install on the platforms that I target.

As you see, 'best' is also determined by the library being available on your target platforms.

How to convert milliseconds to "hh:mm:ss" format?

I tried as shown in the first answer. It works, but minus brought me into confusion. My answer by Groovy:

import static java.util.concurrent.TimeUnit.*

...

private static String formatElapsedTime(long millis) {

    int hrs = MILLISECONDS.toHours(millis) % 24
    int min = MILLISECONDS.toMinutes(millis) % 60
    int sec = MILLISECONDS.toSeconds(millis) % 60
    int mls = millis % 1000

    sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])
}

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

MySQL Event Scheduler on a specific time everyday

My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:

CREATE EVENT applog_clean_event
ON SCHEDULE 
    EVERY 1 DAY
    STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO 

How to get current page URL in MVC 3

I too was looking for this for Facebook reasons and none of the answers given so far worked as needed or are too complicated.

@Request.Url.GetLeftPart(UriPartial.Path)

Gets the full protocol, host and path "without" the querystring. Also includes the port if you are using something other than the default 80.

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Passing variables to the next middleware using next() in Express.js

The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling

app.get('some/url/endpoint', middleware1, middleware2);

Since you can handle your request in the first middleware

(req, res, next) => {
    var yourvalue = anyvalue
}

In middleware 1 you handle your logic and store your value like below:

req.anyvariable = yourvalue

In middleware 2 you can catch this value from middleware 1 doing the following:

(req, res, next) => {
    var storedvalue = req.yourvalue
}

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I've just had an email from a github.com admin stating the following: "We normally advise people to use the HTTPS URL unless they have a specific reason to be using the SSH protocol. HTTPS is secure and easier to set up, so we default to that when a new repository is created."

The password prompt does indeed accept the normal github.com login details. A tutorial on how to set up password caching can be found here. I followed the steps in the tutorial, and it worked for me.

Select folder dialog WPF

Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.

Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.

How to enable external request in IIS Express?

[project properties dialog]

For development using VisualStudio 2017 and a NetCore API-project:

1) In Cmd-Box: ipconfig /all to determine IP-address

2a) Enter the retrieved IP-address in Project properties-> Debug Tab

2b) Select a Port and attach that to the IP-address from step 2a.

3) Add an allow rule in the firewall to allow incoming TCP-traffic on the selected Port (my firewall triggered with a dialog: "Block or add rule to firewall"). Add will in that case do the trick.

Disadvantage of the solution above:

1) If you use a dynamic IP-address you need to redo the steps above in case another IP-address has been assigned.

2) You server has now an open Port which you might forget, but this open port remains an invitation for unwanted guests.

Manually map column names with class properties

Taken from the Dapper Tests which is currently on Dapper 1.42.

// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping), 
                                    (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);

Helper class to get name off the Description attribute (I personally have used Column like @kalebs example)

static string GetDescriptionFromAttribute(MemberInfo member)
{
   if (member == null) return null;

   var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
   return attrib == null ? null : attrib.Description;
}

Class

public class TypeWithMapping
{
   [Description("B")]
   public string A { get; set; }

   [Description("A")]
   public string B { get; set; }
}

What is the first character in the sort order used by Windows Explorer?

TLDR; technically space sorts before exclamation mar, and can be used by preceding it with ' or - (which will be ignored in sorting), but exclamation mark follows right after space, and is easier to use.

On windows 7 at least, a minus sign (-) and (') seem to be ignored in a name except for one quirk: in a name that is otherwise identical, the ' will be sorted before -, for example: (a'a) will sort above (a-a)

Empty string will sort above everything else, which means for example aa will sort above aaa because the 'empty string' after two a letters will sort before the third 'a'.

This also means that aa will be sorted above a'a because the 'empty string' between two a letters will sort above the ' mark.

What follows then is, ' alone will sort first, because technically it's an empty string. However adding for example letters behind it will sort the name as if the ' didn't exist.

Since the first 'unignored' character (as far as I know) is space, in case you want to sort 'real names' above others, the best way to go would be ' followed by space, and then the name you want to actually use. For example: (' first)

You can of course top that by using more than one space in the strong, such as (' firster) and (' firstest) with two and three blanks before the f.

While minus sign sorts below ' in otherwise similar name, there's no other difference in sorting (that I know of), and I find minus sign visually clearer, so if I want to put something on top of list, I'd use minus followed by space, then the 'actual name', for example: (- first file -)

If you are worried about using space on the filename, then exclamation mark (!) is the next best thing - and since it can appear as first character on a string, it's easier to use.

Where does this come from: -*- coding: utf-8 -*-

# -*- coding: utf-8 -*- is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.

See: Should I use encoding declaration in Python 3?

pyupgrade is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object.

Creating a very simple 1 username/password login in php

Here is a simple php script for login and a page that can only be accessed by logged in users.

login.php

<?php
    session_start();
    echo isset($_SESSION['login']);
    if(isset($_SESSION['login'])) {
      header('LOCATION:index.php'); die();
    }
?>
<!DOCTYPE html>
<html>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
<body>
  <div class="container">
    <h3 class="text-center">Login</h3>
    <?php
      if(isset($_POST['submit'])){
        $username = $_POST['username']; $password = $_POST['password'];
        if($username === 'admin' && $password === 'password'){
          $_SESSION['login'] = true; header('LOCATION:admin.php'); die();
        } {
          echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
        }

      }
    ?>
    <form action="" method="post">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" name="password" required>
      </div>
      <button type="submit" name="submit" class="btn btn-default">Login</button>
    </form>
  </div>
</body>
</html>

admin.php ( only logged in users can access it )

<?php
    session_start();
    if(!isset($_SESSION['login'])) {
        header('LOCATION:login.php'); die();
    }
?>
<html>
    <head>
        <title>Admin Page</title>
    </head>
    <body>
        This is admin page view able only by logged in users.
    </body> 
</html>

json_encode is returning NULL?

For anyone using PDO, the solution is similar to ntd's answer.

From the PHP PDO::__construct page, as a comment from the user Kiipa at live dot com:

To get UTF-8 charset you can specify that in the DSN.

$link = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");

How to use a client certificate to authenticate and authorize in a Web API

Tracing helped me find what the problem was (Thank you Fabian for that suggestion). I found with further testing that I could get the client certificate to work on another server (Windows Server 2012). I was testing this on my development machine (Window 7) so I could debug this process. So by comparing the trace to an IIS Server that worked and one that did not I was able to pinpoint the relevant lines in the trace log. Here is a portion of a log where the client certificate worked. This is the setup right before the send

System.Net Information: 0 : [17444] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [17444] SecureChannel#54718731 - We have user-provided certificates. The server has not specified any issuers, so try all the certificates.
System.Net Information: 0 : [17444] SecureChannel#54718731 - Selected certificate:

Here is what the trace log looked like on the machine where the client certificate failed.

System.Net Information: 0 : [19616] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [19616] SecureChannel#54718731 - We have user-provided certificates. The server has specified 137 issuer(s). Looking for certificates that match any of the issuers.
System.Net Information: 0 : [19616] SecureChannel#54718731 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [19616] Using the cached credential handle.

Focusing on the line that indicated the server specified 137 issuers I found this Q&A that seemed similar to my issue. The solution for me was not the one marked as an answer since my certificate was in the trusted root. The answer is the one under it where you update the registry. I just added the value to the registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL

Value name: SendTrustedIssuerList Value type: REG_DWORD Value data: 0 (False)

After adding this value to the registry it started to work on my Windows 7 machine. This appears to be a Windows 7 issue.

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

Export to CSV using MVC, C# and jQuery

Respect to Biff, here's a few tweaks that let me use the method to bounce CSV from jQuery/Post against the server and come back as a CSV prompt to the user.

    [Themed(false)]
    public FileContentResult DownloadCSV()
    {

        var csvStringData = new StreamReader(Request.InputStream).ReadToEnd();

        csvStringData = Uri.UnescapeDataString(csvStringData.Replace("mydata=", ""));

        return File(new System.Text.UTF8Encoding().GetBytes(csvStringData), "text/csv", "report.csv");
    }

You'll need the unescape line if you are hitting this from a form with code like the following,

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val(data);
    $('#downloadForm').append($(input));
    $("#downloadForm").submit();

How do I create 7-Zip archives with .NET?

I used the sdk.

eg:

using SevenZip.Compression.LZMA;
private static void CompressFileLZMA(string inFile, string outFile)
{
   SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();

   using (FileStream input = new FileStream(inFile, FileMode.Open))
   {
      using (FileStream output = new FileStream(outFile, FileMode.Create))
      {
          coder.Code(input, output, -1, -1, null);
          output.Flush();
      }
   }
}

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Persist javascript variables across pages?

You could use the window’s name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Finding local IP addresses using Python's stdlib

Socket API method

see https://stackoverflow.com/a/28950776/711085

Downsides:

  • Not cross-platform.
  • Requires more fallback code, tied to existence of particular addresses on the internet
  • This will also not work if you're behind a NAT
  • Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server)
  • Make sure you make the destination address UNREACHABLE, like a numeric IP address that is spec-guaranteed to be unused. Do NOT use some domain like fakesubdomain.google.com or somefakewebsite.com; you'll still be spamming that party (now or in the future), and spamming your own network boxes as well in the process.

Reflector method

(Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.)

You can query some site like whatismyip.com (but with an API), such as:

from urllib.request import urlopen
import re
def getPublicIp():
    data = str(urlopen('http://checkip.dyndns.com/').read())
    # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'

    return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)

or if using python2:

from urllib import urlopen
import re
def getPublicIp():
    data = str(urlopen('http://checkip.dyndns.com/').read())
    # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n'

    return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)

Advantages:

  • One upside of this method is it's cross-platform
  • It works from behind ugly NATs (e.g. your home router).

Disadvantages (and workarounds):

  • Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure.
  • Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server)

edit: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question "what is the internet?". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for gateways and routes. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that ("is it the network card, or the ethernet cable, which we're talking about?"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.

How can I remove an entry in global configuration with git config?

Try these commands to remove all users' usernames and emails.

git config --global --unset-all user.name
git config --global --unset-all user.email

Angularjs simple file download causes router to redirect

https://docs.angularjs.org/guide/$location#html-link-rewriting

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element Example:
    <a href="/ext/link?a=b" target="_self">link</a>

  • Absolute links that go to a different domain Example:
    <a href="http://angularjs.org/">link</a>

  • Links starting with '/' that lead to a different base path when base is defined Example:
    <a href="/not-my-base/link">link</a>

So in your case, you should add a target attribute like so...

<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">

How can I get a list of locally installed Python modules?

Very simple searching using pkgutil.iter_modules

from pkgutil import iter_modules
a=iter_modules()
while True:
    try: x=a.next()
    except: break
    if 'searchstr' in x[1]: print x[1]

How can I load the contents of a text file into a batch file variable?

You can use:

set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i

How to force maven update?

mvn clean install -U

-U means force update of snapshot dependencies. Release dependencies can't be updated this way.

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

Python class returning value

class MyClass():
    def __init__(self, a, b):
        self.value1 = a
        self.value2 = b

    def __call__(self):
        return [self.value1, self.value2]

Testing:

>>> x = MyClass('foo','bar')
>>> x()
['foo', 'bar']

C++ printing spaces or tabs given a user input integer

You just need a loop that iterates the number of times given by n and prints a space each time. This would do:

while (n--) {
  std::cout << ' ';
}

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Right Align button in horizontal LinearLayout

You can use RelativeLayout or set gravity="right" on the parent layout of your Button.

Can I invoke an instance method on a Ruby module without including it?

Firstly, I'd recommend breaking the module up into the useful things you need. But you can always create a class extending that for your invocation:

module UsefulThings
  def a
    puts "aaay"
  end
  def b
    puts "beee"
  end
end

def test
  ob = Class.new.send(:include, UsefulThings).new
  ob.a
end

test

How to serialize Joda DateTime with Jackson JSON processor?

I'm using Java 8 and this worked for me.

Add the dependency on pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

and add JodaModule on your ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

Set output of a command as a variable (with pipes)

The lack of a Linux-like backtick/backquote facility is a major annoyance of the pre-PowerShell world. Using backquotes via for-loops is not at all cosy. So we need kinda of setvar myvar cmd-line command.

In my %path% I have a dir with a number of bins and batches to cope with those Win shortcomings.

One batch I wrote is:

:: setvar varname cmd
:: Set VARNAME to the output of CMD
:: Triple escape pipes, eg:
:: setvar x  dir c:\ ^^^| sort 
:: -----------------------------

@echo off
SETLOCAL

:: Get command from argument 
for /F "tokens=1,*" %%a in ("%*") do set cmd=%%b

:: Get output and set var
for /F "usebackq delims=" %%a in (`%cmd%`) do (
     ENDLOCAL
     set %1=%%a
)

:: Show results 
SETLOCAL EnableDelayedExpansion
echo %1=!%1! 

So in your case, you would type:

> setvar text echo Hello
text=Hello 

The script informs you of the results, which means you can:

> echo text var is now %text%
text var is now Hello 

You can use whatever command:

> setvar text FIND "Jones" names.txt

What if the command you want to pipe to some variable contains itself a pipe?
Triple escape it, ^^^|:

> setvar text dir c:\ ^^^| find "Win"

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

How to extract the hostname portion of a URL in JavaScript

Try

document.location.host

or

document.location.hostname

How to validate email id in angularJs using ng-pattern

This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.

var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;

Source.

UICollectionView current visible cell index

Just want to add for others : for some reason, I didnt not get the cell that was visible to the user when I was scrolling to previous cell in collectionView with pagingEnabled.

So I insert the code inside dispatch_async to give it some "air" and this works for me.

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    dispatch_async(dispatch_get_main_queue(), ^{
            UICollectionViewCell * visibleCell= [[self.collectionView visibleCells] objectAtIndex:0];


            [visibleCell doSomthing];
        });
}

How to declare 2D array in bash

Mark Reed suggested a very good solution for 2D arrays (matrix)! They always can be converted in a 1D array (vector). Although Bash doesn't have a native support for 2D arrays, it's not that hard to create a simple ADT around the mentioned principle.

Here is a barebone example with no argument checks, etc, just to keep the solution clear: the array's size is set as two first elements in the instance (documentation for the Bash module that implements a matrix ADT, https://github.com/vorakl/bash-libs/blob/master/src.docs/content/pages/matrix.rst )

#!/bin/bash

matrix_init() {
    # matrix_init instance x y data ...

    declare -n self=$1                                                          
    declare -i width=$2 height=$3                                                
    shift 3;                                                                    

    self=(${width} ${height} "$@")                                               
}                                                                               

matrix_get() {                                                                  
    # matrix_get instance x y

    declare -n self=$1                                                          
    declare -i x=$2 y=$3                                                        
    declare -i width=${self[0]} height=${self[1]}                                

    echo "${self[2+y*width+x]}"                                                 
}                                                                               

matrix_set() {                                                                  
    # matrix_set instance x y data

    declare -n self=$1                                                          
    declare -i x=$2 y=$3                                                        
    declare data="$4"                                                           
    declare -i width=${self[0]} height=${self[1]}                                

    self[2+y*width+x]="${data}"                                                 
}                                                                               

matrix_destroy() {                                                                     
    # matrix_destroy instance

    declare -n self=$1                                                          
    unset self                                                                  
}

# my_matrix[3][2]=( (one, two, three), ("1 1" "2 2" "3 3") )
matrix_init my_matrix \                                                         
        3 2 \                                                               
        one two three \                                                     
        "1 1" "2 2" "3 3"

# print my_matrix[2][0]
matrix_get my_matrix 2 0

# print my_matrix[1][1]
matrix_get my_matrix 1 1

# my_matrix[1][1]="4 4 4"
matrix_set my_matrix 1 1 "4 4 4"                                                

# print my_matrix[1][1]
matrix_get my_matrix 1 1                                                        

# remove my_matrix
matrix_destroy my_matrix

How to close a JavaFX application on window close?

Instead of playing around with onCloseRequest handlers or window events, I prefer calling Platform.setImplicitExit(true) the beginning of the application.

According to JavaDocs:

"If this attribute is true, the JavaFX runtime will implicitly shutdown when the last window is closed; the JavaFX launcher will call the Application.stop() method and terminate the JavaFX application thread."

Example:

@Override
void start(Stage primaryStage) {
    Platform.setImplicitExit(true)
    ...
    // create stage and scene
}

Can I set an unlimited length for maxJsonLength in web.config?

I fixed it.

//your Json data here
string json_object="........";
JavaScriptSerializer jsJson = new JavaScriptSerializer();
jsJson.MaxJsonLength = 2147483644;
MyClass obj = jsJson.Deserialize<MyClass>(json_object);

It works very well.

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

Array definition in XML?

In XML values in text() nodes.

If we write this

<numbers>1,2,3</numbers>

in element "numbers" will be one text() node with value "1,2,3".

Native way to get many text() nodes in element is insert nodes of other types in text.

Other available types is element or comment() node.

Split with element node:

<numbers>3<_/>2<_/>1</numbers>

Split with comment() node:

<numbers>3<!---->2<!---->1</numbers>

We can select this values by this XPath

//numbers/text()

Select value by index

//numbers/text()[3]

Will return text() node with value "1"

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

Directly assigning values to C Pointers

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

You need to create an int variable somewhere in memory for the int * variable to point at.

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

Redirect to a page/URL after alert button is pressed

<head>
<script>
    function myFunction() {
        var x;
        var r = confirm("Do you want to clear data?");
        if (r == true) {
            x = "Your Data is Cleared";
            window.location.href = "firstpage.php";
        }
        else {
            x = "You pressed Cancel!";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>

<p id="demo"></p>
</body>
</html>

This will redirect to new php page.

extract date only from given timestamp in oracle sql

In Oracle 11g, To get the complete date from the Timestamp, use this-

Select TRUNC(timestamp) FROM TABLE_NAME;

To get the Year from the Timestamp, use this-

Select EXTRACT(YEAR FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Month from the Timestamp, use this-

Select EXTRACT(MONTH FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Day from the Timestamp, use this-

Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

try this...    
<script type="text/javascript">
    function test(){
    var av=document.getElementById("mytext").value;
    alert(av);
    }
    </script>

    <input type="text" value="" id="mytext">
    <input type="button" onclick="test()" value="go" />

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

.apply() takes in a function as the first parameter; pass in the label_race function as so:

df['race_label'] = df.apply(label_race, axis=1)

You don't need to make a lambda function to pass in a function.

How to check if a variable is a dictionary in Python?

You could use if type(ele) is dict or use isinstance(ele, dict) which would work if you had subclassed dict:

d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
    if isinstance(element, dict):
       for k, v in element.items():
           print(k,' ',v)