Programs & Examples On #Vnc server

vnc-server is used to remotely access a machine from another machine where vnc-client will be running

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

This might help some who come across this error. If you are working across a VPN and it becomes disconnected, you can also get this error. The simple fix is to reconnect your VPN.

This Activity already has an action bar supplied by the window decor

It could also be because you have a style without a parent specified:

<style name="DarkModeTheme" >
    <item name="searchBarBgColor">#D6D6D6</item>
</style>

Remove it, and it should fix the problem.

What is the best workaround for the WCF client `using` block issue?

I used Castle dynamic proxy to solve the Dispose() issue, and also implemented auto-refreshing the channel when it is in an unusable state. To use this you must create a new interface that inherits your service contract and IDisposable. The dynamic proxy implements this interface and wraps a WCF channel:

Func<object> createChannel = () =>
    ChannelFactory<IHelloWorldService>
        .CreateChannel(new NetTcpBinding(), new EndpointAddress(uri));
var factory = new WcfProxyFactory();
var proxy = factory.Create<IDisposableHelloWorldService>(createChannel);
proxy.HelloWorld();

I like this since you can inject WCF services without consumers needing to worry about any details of WCF. And there's no added cruft like the other solutions.

Have a look at the code, it's actually pretty simple: WCF Dynamic Proxy

After installing with pip, "jupyter: command not found"

Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:

First verify this is a PATH issue:

Check if the path returned by which jupyter is covered by the sudo user:

sudo env | grep ^PATH

(As opposed to the current user: env | grep ^PATH)

If its not covered - add a soft link from it to one of the covered paths. For ex:

sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin

Now you sould be able to run:

sudo jupyter notebook

use video as background for div

Why not fix a <video> and use z-index:-1 to put it behind all other elements?

html, body { width:100%; height:100%; margin:0; padding:0; }

<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
    <video id="video" style="width:100%; height:100%">
        ....
    </video>
</div>
<div class='content'>
    ....

Demo

If you want it within a container you have to add a container element and a little more CSS

/* HTML */
<div class='vidContain'>
    <div class='vid'>
        <video> ... </video>
    </div>
    <div class='content'> ... The rest of your content ... </div>
</div>

/* CSS */
.vidContain {
    width:300px; height:200px;
    position:relative;
    display:inline-block;
    margin:10px;
}
.vid {
    position: absolute; 
    top: 0; left:0;
    width: 100%; height: 100%; 
    z-index: -1;
}    
.content {
    position:absolute;
    top:0; left:0;
    background: black;
    color:white;
}

Demo

What is Java String interning?

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

Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.

This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.


More on memory constraints of using intern()

On one hand, it is true that you can remove String duplicates by internalizing them. The problem is that the internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.

-- From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html


From JDK 7 (I mean in HotSpot), something has changed.

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

-- From Java SE 7 Features and Enhancements

Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

Error: could not find function "%>%"

On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr (or magrittr, which dplyr loads).

Example:

plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
    return(getPlot(myInput))
}

If you omit the .packages command, and use %do% instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.

How can I reduce the waiting (ttfb) time

I have met the same problem. My project is running on the local server. I checked my php code.

$db = mysqli_connect('localhost', 'root', 'root', 'smart');

I use localhost to connect to my local database. That maybe the cause of the problem which you're describing. You can modify your HOSTS file. Add the line

127.0.0.1 localhost.

How to convert strings into integers in Python?

You can do this with a list comprehension:

T2 = [[int(column) for column in row] for row in T1]

The inner list comprehension ([int(column) for column in row]) builds a list of ints from a sequence of int-able objects, like decimal strings, in row. The outer list comprehension ([... for row in T1])) builds a list of the results of the inner list comprehension applied to each item in T1.

The code snippet will fail if any of the rows contain objects that can't be converted by int. You'll need a smarter function if you want to process rows containing non-decimal strings.

If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

T2 = [parse_a_row_of_T1(row) for row in T1]

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

Jump to function definition in vim

Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.

int
main(int argc, char *argv[])
{
    ...
}

The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.

Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.

Redirecting to authentication dialog - "An error occurred. Please try again later"

I just encountered this problem myself. I'm developing an app internally, so my host is 'localhost'. It wasn't obvious how to set 'localhost' up in the app configuration. If you want to develop locally, set up your app by following these steps:

  1. Go to the place where you manage your Facebook app. Specifically, you want to be in "Basic" under the "Settings" menu.
  2. Add 'localhost' to "App Domain".
  3. Under "Select how your app integrates with Facebook", select "Website", and enter "http://localhost/".

Save and wait a couple of minutes for the information to propagate, although it worked right away for me.

Animate change of view background color on Android

I ended up figuring out a (pretty good) solution for this problem!

You can use a TransitionDrawable to accomplish this. For example, in an XML file in the drawable folder you could write something like:

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
    <item android:drawable="@drawable/original_state" />
    <item android:drawable="@drawable/new_state" />
</transition>

Then, in your XML for the actual View you would reference this TransitionDrawable in the android:background attribute.

At this point you can initiate the transition in your code on-command by doing:

TransitionDrawable transition = (TransitionDrawable) viewObj.getBackground();
transition.startTransition(transitionTime);

Or run the transition in reverse by calling:

transition.reverseTransition(transitionTime);

See Roman's answer for another solution using the Property Animation API, which wasn't available at the time this answer was originally posted.

Assigning default values to shell variables with a single command in bash

To answer your question and on all variable substitutions

echo "$\{var}"
echo "Substitute the value of var."


echo "$\{var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."


echo "$\{var:=word}"
echo "If var is null or unset, var is set to the value of word."


echo "$\{var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."


echo "$\{var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

How to add hamburger menu in bootstrap

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
      <ul class="nav navbar-nav">_x000D_
        <li><a href="index.php">Home</a></li>_x000D_
        <li><a href="about.php">About</a></li>_x000D_
        <li><a href="#portfolio">Portfolio</a></li>_x000D_
        <li><a href="#">Blog</a></li>_x000D_
        <li><a href="contact.php">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

how do I create an array in jquery?

Here is the clear working example:

//creating new array
var custom_arr1 = [];


//storing value in array
custom_arr1.push("test");
custom_arr1.push("test1");

alert(custom_arr1);
//output will be  test,test1

How to write LaTeX in IPython Notebook?

You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.

Alternatively, Latex section of the iPython notebook tutorial explains this well.

You can either do:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 
\end{eqnarray}""")

or do this:

%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

More info found in this link

CSS media queries: max-width OR max-height

There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:

@media only screen 
and (min-width : 415px){
    /* Styles */
}

@media only screen 
and (min-width : 769px){
    /* Styles */
}

@media only screen 
and (min-width : 992px){
    /* Styles */
}

But if you are writing media queries for smaller device first, then it would be something like:

@media only screen 
and (max-width : 991px){
    /* Styles */
}

@media only screen 
and (max-width : 768px){
    /* Styles */
}

@media only screen 
and (max-width : 414px){
    /* Styles */
}

How to check the extension of a filename in a bash script?

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

#!/bin/bash
# flvcache script

CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M

for f in `find $CACHE -size +$MINFILESIZE`
do
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
        then
            cp "$f" "$OUTPUTDIR/$o"
    fi
done

nautilus  "$OUTPUTDIR"&

It uses similar ideas to those presented here, hope this is helpful to someone.

adb devices command not working

You need to restart the adb server as root. See here.

What is middleware exactly?

it is a software layer between the operating system and applications on each side of a distributed computing system in a network. In fact it connects heterogeneous network and software systems.

Regex - how to match everything except a particular pattern

My answer here might solve your problem as well:

https://stackoverflow.com/a/27967674/543814

  • Instead of Replace, you would use Match.
  • Instead of group $1, you would read group $2.
  • Group $2 was made non-capturing there, which you would avoid.

Example:

Regex.Match("50% of 50% is 25%", "(\d+\%)|(.+?)");

The first capturing group specifies the pattern that you wish to avoid. The last capturing group captures everything else. Simply read out that group, $2.

I want to align the text in a <td> to the top

you can use valign="top" on the td tag it is working perfectly for me.

How to test an Internet connection with bash?

If your local nameserver is down,

ping 4.2.2.1

is an easy-to-remember always-up IP (it's actually a nameserver, even).

Saving and Reading Bitmaps/Images from Internal memory in Android

For Kotlin users, I created a ImageStorageManager class which will handle save, get and delete actions for images easily:

class ImageStorageManager {
    companion object {
        fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
            context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 25, fos)
            }
            return context.filesDir.absolutePath
        }

        fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
            val directory = context.filesDir
            val file = File(directory, imageFileName)
            return BitmapFactory.decodeStream(FileInputStream(file))
        }

        fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
            val dir = context.filesDir
            val file = File(dir, imageFileName)
            return file.delete()
        }
    }
}

Read more here

Route [login] not defined

**Adding this for the future me.**
I encountered this because I was reusing Laravel's "HomeController", and adding my custom functions to it. Note that this controller calls the auth middleware in its __construct() method as shown below, which means that all functions must be authenticated. No wonder it tries to take you to login page first. So, if you are not using Laravel's authentication scafffolding, you will be in a mess. Disable the constructor, or do as you seem fit, now that you know what is happening.

public function __construct()
{
    $this->middleware('auth');
}

Redirecting Output from within Batch file

I know this is an older post, but someone will stumble across it in a Google search and it also looks like some questions the OP asked in comments weren't specifically addressed. Also, please go easy on me since this is my first answer posted on SO. :)

To redirect the output to a file using a dynamically generated file name, my go-to (read: quick & dirty) approach is the second solution offered by @dbenham. So for example, this:

@echo off
> filename_prefix-%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log (
echo Your Name Here
echo Beginning Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
REM do some stuff here
echo Your Name Here
echo Ending Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
)

Will create a file like what you see in this screenshot of the file in the target directory

That will contain this output:

Your Name Here
Beginning Date/Time: 2016-09-16_141048.log
Your Name Here
Ending Date/Time: 2016-09-16_141048.log

Also keep in mind that this solution is locale-dependent, so be careful how/when you use it.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

For those looking to do this in VB, here's how I got mine to work with a checkbox.

Background: I was trying to make my own checkbox that is a slider/switch control. I've only included the relevant code for this question.

In User control MyCheckbox.ascx

<asp:CheckBox ID="checkbox" runat="server" AutoPostBack="true" />

In User control MyCheckbox.ascx.vb

Create an EventHandler (OnCheckChanged). When an event fires on the control (ID="checkbox") inside your usercontrol (MyCheckBox.ascx), then fire your EventHandler (OnCheckChanged).

Public Event OnCheckChanged As EventHandler

Private Sub checkbox_CheckedChanged(sender As Object, e As EventArgs) Handles checkbox.CheckedChanged
    RaiseEvent OnCheckChanged(Me, e)
End Sub

In Page MyPage.aspx

<uc:MyCheckbox runat="server" ID="myCheck" OnCheckChanged="myCheck_CheckChanged" />

Note: myCheck_CheckChanged didn't fire until I added the Handles clause below

In Page MyPage.aspx.vb

Protected Sub myCheck_CheckChanged (sender As Object, e As EventArgs) Handles scTransparentVoting.OnCheckChanged
    'Do some page logic here
End Sub

Node.js: Gzip compression?

For compressing the file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt').pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));
console.log("File Compressed.");

For decompressing the same file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("File Decompressed.");

how to know status of currently running jobs

We've found and have been using this code for a good solution. This code will start a job, and monitor it, killing the job automatically if it exceeds a time limit.

/****************************************************************
--This SQL will take a list of SQL Agent jobs (names must match),
--start them so they're all running together, and then
--monitor them, not quitting until all jobs have completed.
--
--In essence, it's an SQL "watchdog" loop to start and monitor SQL Agent Jobs
--
--Code from http://cc.davelozinski.com/code/sql-watchdog-loop-start-monitor-sql-agent-jobs
--
****************************************************************/
SET NOCOUNT ON 

-------- BEGIN ITEMS THAT NEED TO BE CONFIGURED --------

--The amount of time to wait before checking again 
--to see if the jobs are still running.
--Should be in hh:mm:ss format. 
DECLARE @WaitDelay VARCHAR(8) = '00:00:20'

--Job timeout. Eg, if the jobs are running longer than this, kill them.
DECLARE @TimeoutMinutes INT = 240

DECLARE @JobsToRunTable TABLE
(
    JobName NVARCHAR(128) NOT NULL,
    JobID UNIQUEIDENTIFIER NULL,
    Running INT NULL
)

--Insert the names of the SQL jobs here. Last two values should always be NULL at this point.
--Names need to match exactly, so best to copy/paste from the SQL Server Agent job name.
INSERT INTO @JobsToRunTable (JobName, JobID, Running) VALUES ('NameOfFirstSQLAgentJobToRun',NULL,NULL)
INSERT INTO @JobsToRunTable (JobName, JobID, Running) VALUES ('NameOfSecondSQLAgentJobToRun',NULL,NULL)
INSERT INTO @JobsToRunTable (JobName, JobID, Running) VALUES ('NameOfXSQLAgentJobToRun',NULL,NULL)

-------- NOTHING FROM HERE DOWN SHOULD NEED TO BE CONFIGURED --------

DECLARE @ExecutionStatusTable TABLE
(
    JobID UNIQUEIDENTIFIER PRIMARY KEY, -- Job ID which will be a guid
    LastRunDate INT, LastRunTime INT, -- Last run date and time
    NextRunDate INT, NextRunTime INT, -- Next run date and time
    NextRunScheduleID INT, -- an internal schedule id
    RequestedToRun INT, RequestSource INT, RequestSourceID VARCHAR(128),
    Running INT,    -- 0 or 1, 1 means the job is executing
    CurrentStep INT, -- which step is running
    CurrentRetryAttempt INT, -- retry attempt
    JobState INT -- 0 = Not idle or suspended, 1 = Executing, 2 = Waiting For Thread,
                     -- 3 = Between Retries, 4 = Idle, 5 = Suspended, 
                     -- 6 = WaitingForStepToFinish, 7 = PerformingCompletionActions
)

DECLARE @JobNameToRun NVARCHAR(128) = NULL
DECLARE @IsJobRunning BIT = 1
DECLARE @AreJobsRunning BIT = 1
DECLARE @job_owner sysname = SUSER_SNAME()
DECLARE @JobID UNIQUEIDENTIFIER = null
DECLARE @StartDateTime DATETIME = GETDATE()
DECLARE @CurrentDateTime DATETIME = null
DECLARE @ExecutionStatus INT = 0
DECLARE @MaxTimeExceeded BIT = 0

--Loop through and start every job
DECLARE dbCursor CURSOR FOR SELECT JobName FROM @JobsToRunTable
OPEN dbCursor FETCH NEXT FROM dbCursor INTO @JobNameToRun
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC [msdb].[dbo].sp_start_job @JobNameToRun
    FETCH NEXT FROM dbCursor INTO @JobNameToRun
END
CLOSE dbCursor
DEALLOCATE dbCursor

print '*****************************************************************'
print 'Jobs started. ' + CAST(@StartDateTime as varchar)
print '*****************************************************************'

--Debug (if needed)
--SELECT * FROM @JobsToRunTable

WHILE 1=1 AND @AreJobsRunning = 1
BEGIN

    --This has to be first with the delay to make sure the jobs
    --have time to actually start up and are recognized as 'running'
    WAITFOR DELAY @WaitDelay 

    --Reset for each loop iteration
    SET @AreJobsRunning = 0

    --Get the currently executing jobs by our user name
    INSERT INTO @ExecutionStatusTable
    EXECUTE [master].[dbo].xp_sqlagent_enum_jobs 1, @job_owner

    --Debug (if needed)
    --SELECT 'ExecutionStatusTable', * FROM @ExecutionStatusTable

    --select every job to see if it's running
    DECLARE dbCursor CURSOR FOR 
        SELECT x.[Running], x.[JobID], sj.name 
        FROM @ExecutionStatusTable x 
        INNER JOIN [msdb].[dbo].sysjobs sj ON sj.job_id = x.JobID
        INNER JOIN @JobsToRunTable jtr on sj.name = jtr.JobName
    OPEN dbCursor FETCH NEXT FROM dbCursor INTO @IsJobRunning, @JobID, @JobNameToRun

    --Debug (if needed)
    --SELECT x.[Running], x.[JobID], sj.name 
    --  FROM @ExecutionStatusTable x 
    --  INNER JOIN msdb.dbo.sysjobs sj ON sj.job_id = x.JobID
    --  INNER JOIN @JobsToRunTable jtr on sj.name = jtr.JobName

    WHILE @@FETCH_STATUS = 0
    BEGIN
        --bitwise operation to see if the loop should continue
        SET @AreJobsRunning = @AreJobsRunning | @IsJobRunning

        UPDATE @JobsToRunTable
        SET Running = @IsJobRunning, JobID = @JobID
        WHERE JobName = @JobNameToRun

        --Debug (if needed)
        --SELECT 'JobsToRun', * FROM @JobsToRunTable

        SET @CurrentDateTime=GETDATE()

        IF @IsJobRunning = 1
        BEGIN -- Job is running or finishing (not idle)

            IF DATEDIFF(mi, @StartDateTime, @CurrentDateTime) > @TimeoutMinutes
            BEGIN     
                print '*****************************************************************'
                print @JobNameToRun + ' exceeded timeout limit of ' + @TimeoutMinutes + ' minutes. Stopping.'
                --Stop the job
                EXEC [msdb].[dbo].sp_stop_job @job_name = @JobNameToRun
            END
            ELSE
            BEGIN
                print @JobNameToRun + ' running for ' + CONVERT(VARCHAR(25),DATEDIFF(mi, @StartDateTime, @CurrentDateTime)) + ' minute(s).'
            END
        END

        IF @IsJobRunning = 0 
        BEGIN
            --Job isn't running
            print '*****************************************************************'
            print @JobNameToRun + ' completed or did not run. ' + CAST(@CurrentDateTime as VARCHAR)
        END

        FETCH NEXT FROM dbCursor INTO @IsJobRunning, @JobID, @JobNameToRun

    END -- WHILE @@FETCH_STATUS = 0
    CLOSE dbCursor
    DEALLOCATE dbCursor

    --Clear out the table for the next loop iteration
    DELETE FROM @ExecutionStatusTable

    print '*****************************************************************'

END -- WHILE 1=1 AND @AreJobsRunning = 1

SET @CurrentDateTime = GETDATE()
print 'Finished at ' + CAST(@CurrentDateTime as varchar)
print CONVERT(VARCHAR(25),DATEDIFF(mi, @StartDateTime, @CurrentDateTime)) + ' minutes total run time.'

C++ Singleton design pattern

I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:

#include<iostream>
#include<string>

class DoNotCopy
{
protected:
    DoNotCopy(void) = default;
    DoNotCopy(const DoNotCopy&) = delete;
    DoNotCopy& operator=(const DoNotCopy&) = delete;
};

class DoNotMove
{
protected:
    DoNotMove(void) = default;
    DoNotMove(DoNotMove&&) = delete;
    DoNotMove& operator=(DoNotMove&&) = delete;
};

class DoNotCopyMove : public DoNotCopy,
    public DoNotMove
{
protected:
    DoNotCopyMove(void) = default;
};

template<class T>
class Singleton : public DoNotCopyMove
{
public:
    static T& Instance(void)
    {
        static T instance;
        return instance;
    }

protected:
    Singleton(void) = default;
};

class Logger final: public Singleton<Logger>
{
public:
    void log(const std::string& str) { std::cout << str << std::endl; }
};



int main()
{
    Logger::Instance().log("xx");
}

The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).

addEventListener not working in IE8

This is also simple crossbrowser solution:

var addEvent =  window.attachEvent||window.addEventListener;
var event = window.attachEvent ? 'onclick' : 'click';
addEvent(event, function(){
    alert('Hello!')
});

Instead of 'click' can be any event of course.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

Eclipse hangs on loading workbench

Get a backup copy of the .metadata/.plugin/org.eclipse.core.resources folder, then delete that folder and launch eclipse. That should launch the workspace, but all projects will be gone as org.eclipse.core.resources keeps a list of all projects.

Next, close eclipse properly and copy back org.eclipse.core.resources from back up to .metadata/.plugins/ folder overriding the existing one.

Open eclipse and things should work fine with all your projects back to normal.

Error: Failed to lookup view in Express

I had the same error at first and i was really annoyed. you just need to have ./ before the path to the template

res.render('./index/index');

Hope it works, worked for me.

Python Timezone conversion

Python 3.9 adds the zoneinfo module so now only the the standard library is needed!

>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime

>>> d = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo('America/Los_Angeles'))
>>> d.astimezone(ZoneInfo('Europe/Berlin'))  # 12:00 in Cali will be 20:00 in Berlin
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Wikipedia list of available time zones


Some functions such as now() and utcnow() return timezone-unaware datetimes, meaning they contain no timezone information. I recommend only requesting timezone-aware values from them using the keyword tz=ZoneInfo('localtime').

If astimezone gets a timezone-unaware input, it will assume it is local time, which can lead to errors:

>>> datetime.utcnow()  # UTC -- NOT timezone-aware!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 376479)
>>> datetime.now()     # Local time -- NOT timezone-aware!!
datetime.datetime(2020, 6, 2, 0, 39, 57, 376675)

>>> datetime.now(tz=ZoneInfo('localtime'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376806, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> datetime.now(tz=ZoneInfo('Europe/Berlin'))  # timezone-aware
datetime.datetime(2020, 6, 2, 0, 39, 57, 376937, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
>>> datetime.utcnow().astimezone(ZoneInfo('Europe/Berlin'))  # WRONG!!
datetime.datetime(2020, 6, 1, 22, 39, 57, 377562, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

How to split data into training/testing sets using sample function

Below a function that create a list of sub-samples of the same size which is not exactly what you wanted but might prove usefull for others. In my case to create multiple classification trees on smaller samples to test overfitting :

df_split <- function (df, number){
  sizedf      <- length(df[,1])
  bound       <- sizedf/number
  list        <- list() 
  for (i in 1:number){
    list[i] <- list(df[((i*bound+1)-bound):(i*bound),])
  }
  return(list)
}

Example :

x <- matrix(c(1:10), ncol=1)
x
# [,1]
# [1,]    1
# [2,]    2
# [3,]    3
# [4,]    4
# [5,]    5
# [6,]    6
# [7,]    7
# [8,]    8
# [9,]    9
#[10,]   10

x.split <- df_split(x,5)
x.split
# [[1]]
# [1] 1 2

# [[2]]
# [1] 3 4

# [[3]]
# [1] 5 6

# [[4]]
# [1] 7 8

# [[5]]
# [1] 9 10

Why is processing a sorted array faster than processing an unsorted array?

I just read up on this question and its answers, and I feel an answer is missing.

A common way to eliminate branch prediction that I've found to work particularly good in managed languages is a table lookup instead of using a branch (although I haven't tested it in this case).

This approach works in general if:

  1. it's a small table and is likely to be cached in the processor, and
  2. you are running things in a quite tight loop and/or the processor can preload the data.

Background and why

From a processor perspective, your memory is slow. To compensate for the difference in speed, a couple of caches are built into your processor (L1/L2 cache). So imagine that you're doing your nice calculations and figure out that you need a piece of memory. The processor will get its 'load' operation and loads the piece of memory into cache -- and then uses the cache to do the rest of the calculations. Because memory is relatively slow, this 'load' will slow down your program.

Like branch prediction, this was optimized in the Pentium processors: the processor predicts that it needs to load a piece of data and attempts to load that into the cache before the operation actually hits the cache. As we've already seen, branch prediction sometimes goes horribly wrong -- in the worst case scenario you need to go back and actually wait for a memory load, which will take forever (in other words: failing branch prediction is bad, a memory load after a branch prediction fail is just horrible!).

Fortunately for us, if the memory access pattern is predictable, the processor will load it in its fast cache and all is well.

The first thing we need to know is what is small? While smaller is generally better, a rule of thumb is to stick to lookup tables that are <= 4096 bytes in size. As an upper limit: if your lookup table is larger than 64K it's probably worth reconsidering.

Constructing a table

So we've figured out that we can create a small table. Next thing to do is get a lookup function in place. Lookup functions are usually small functions that use a couple of basic integer operations (and, or, xor, shift, add, remove and perhaps multiply). You want to have your input translated by the lookup function to some kind of 'unique key' in your table, which then simply gives you the answer of all the work you wanted it to do.

In this case: >= 128 means we can keep the value, < 128 means we get rid of it. The easiest way to do that is by using an 'AND': if we keep it, we AND it with 7FFFFFFF; if we want to get rid of it, we AND it with 0. Notice also that 128 is a power of 2 -- so we can go ahead and make a table of 32768/128 integers and fill it with one zero and a lot of 7FFFFFFFF's.

Managed languages

You might wonder why this works well in managed languages. After all, managed languages check the boundaries of the arrays with a branch to ensure you don't mess up...

Well, not exactly... :-)

There has been quite some work on eliminating this branch for managed languages. For example:

for (int i = 0; i < array.Length; ++i)
{
   // Use array[i]
}

In this case, it's obvious to the compiler that the boundary condition will never be hit. At least the Microsoft JIT compiler (but I expect Java does similar things) will notice this and remove the check altogether. WOW, that means no branch. Similarly, it will deal with other obvious cases.

If you run into trouble with lookups in managed languages -- the key is to add a & 0x[something]FFF to your lookup function to make the boundary check predictable -- and watch it going faster.

The result of this case

// Generate data
int arraySize = 32768;
int[] data = new int[arraySize];

Random random = new Random(0);
for (int c = 0; c < arraySize; ++c)
{
    data[c] = random.Next(256);
}

/*To keep the spirit of the code intact, I'll make a separate lookup table
(I assume we cannot modify 'data' or the number of loops)*/

int[] lookup = new int[256];

for (int c = 0; c < 256; ++c)
{
    lookup[c] = (c >= 128) ? c : 0;
}

// Test
DateTime startTime = System.DateTime.Now;
long sum = 0;

for (int i = 0; i < 100000; ++i)
{
    // Primary loop
    for (int j = 0; j < arraySize; ++j)
    {
        /* Here you basically want to use simple operations - so no
        random branches, but things like &, |, *, -, +, etc. are fine. */
        sum += lookup[data[j]];
    }
}

DateTime endTime = System.DateTime.Now;
Console.WriteLine(endTime - startTime);
Console.WriteLine("sum = " + sum);
Console.ReadLine();

Detect when an image fails to load in Javascript

/**
 * Tests image load.
 * @param {String} url
 * @returns {Promise}
 */
function testImageUrl(url) {
  return new Promise(function(resolve, reject) {
    var image = new Image();
    image.addEventListener('load', resolve);
    image.addEventListener('error', reject);
    image.src = url;
  });
}

return testImageUrl(imageUrl).then(function imageLoaded(e) {
  return imageUrl;
})
.catch(function imageFailed(e) {
  return defaultImageUrl;
});

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

Encountered this issue in chrome. Resolved by cleaning up related cookies. Note that you don't have to cleanup ALL your cookies.

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

How to convert hashmap to JSON object in Java

You can just enumerate the map and add the key-value pairs to the JSONObject

Method :

private JSONObject getJsonFromMap(Map<String, Object> map) throws JSONException {
    JSONObject jsonData = new JSONObject();
    for (String key : map.keySet()) {
        Object value = map.get(key);
        if (value instanceof Map<?, ?>) {
            value = getJsonFromMap((Map<String, Object>) value);
        }
        jsonData.put(key, value);
    }
    return jsonData;
}

How do I disable right click on my web page?

The original question was about how to stop right-click given that the user can disable JavaScript: which sound nefarious and evil (hence the negative responses) - but all duplicates redirect here, even though many of the duplicates are asking for less evil purposes.

Like using the right-click button in HTML5 games, for example. This can be done with the inline code above, or a bit nicer is something like this:

document.addEventListener("contextmenu", function(e){
    e.preventDefault();
}, false);

But if you are making a game, then remember that the right-click button fires the contextmenu event - but it also fires the regular mousedown and mouseup events too. So you need to check the event's which property to see if it was the left (which === 1), middle (which === 2), or right (which === 3) mouse button that is firing the event.

Here's an example in jQuery - note that the pressing the right mouse button will fire three events: the mousedown event, the contextmenu event, and the mouseup event.

// With jQuery
$(document).on({
    "contextmenu": function(e) {
        console.log("ctx menu button:", e.which); 

        // Stop the context menu
        e.preventDefault();
    },
    "mousedown": function(e) { 
        console.log("normal mouse down:", e.which); 
    },
    "mouseup": function(e) { 
        console.log("normal mouse up:", e.which); 
    }
});

So if you're using the left and right mouse buttons in a game, you'll have to do some conditional logic in the mouse handlers.

Calculate the date yesterday in JavaScript

new Date(new Date().setDate(new Date().getDate()-1))

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Eclipse - "Workspace in use or cannot be created, chose a different one."

Running eclipse in Administrator Mode fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe from your install dir.

I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock and .log files but that did not help. It can be a combination of all as well that made it work.

Converting .NET DateTime to JSON

If you pass a DateTime from a .Net code to a javascript code, C#:

DateTime net_datetime = DateTime.Now;

javascript treats it as a string, like "/Date(1245398693390)/":

You can convert it as fllowing:

// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))

or:

// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))

Understanding implicit in Scala

Also, in the above case there should be only one implicit function whose type is double => Int. Otherwise, the compiler gets confused and won't compile properly.

//this won't compile

implicit def doubleToInt(d: Double) = d.toInt
implicit def doubleToIntSecond(d: Double) = d.toInt
val x: Int = 42.0

TypeScript, Looping through a dictionary

If you just for in a object without if statement hasOwnProperty then you will get error from linter like:

for (const key in myobj) {
   console.log(key);
}
WARNING in component.ts
for (... in ...) statements must be filtered with an if statement

So the solutions is use Object.keys and of instead.

for (const key of Object.keys(myobj)) {
   console.log(key);
}

Hope this helper some one using a linter.

Use YAML with variables

I had this same question, and after a lot of research, it looks like it's not possible.

The answer from cgat is on the right track, but you can't actually concatenate references like that.

Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):

Define a value and use an exact copy of it later:

default: &default_title This Post Has No Title
title: *default_title

{ or }

example_post: &example
  title: My mom likes roosters
  body: Seriously, she does. And I don't know when it started.
  date: 8/18/2012
first_post: *example
second_post:
  title: whatever, etc.

For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References

Define an object and use it with modifications later:

default: &DEFAULT
  URL:          stooges.com
  throw_pies?:  true  
  stooges:  &stooge_list
    larry:  first_stooge
    moe:    second_stooge
    curly:  third_stooge

development:
  <<: *DEFAULT
  URL:      stooges.local
  stooges: 
    shemp: fourth_stooge

test:
  <<: *DEFAULT
  URL:    test.stooges.qa
  stooges: 
    <<: *stooge_list
    shemp: fourth_stooge

This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804

How to list containers in Docker

There are also the following options:

docker container ls
docker container ls -a
# --all, -a
# Show all containers (default shows just running)

since: 1.13.0 (2017-01-18):

Restructure CLI commands by adding docker image and docker container commands for more consistency #26025

and as stated here: Introducing Docker 1.13, users are encouraged to adopt the new syntax:

CLI restructured

In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example list and start of containers are now subcommands of docker container and history is a subcommand of docker image.

These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.

Does Python have a string 'contains' substring method?

if needle in haystack: is the normal use, as @Michael says -- it relies on the in operator, more readable and faster than a method call.

If you truly need a method instead of an operator (e.g. to do some weird key= for a very peculiar sort...?), that would be 'haystack'.__contains__. But since your example is for use in an if, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.

Does IMDB provide an API?

Found this one

IMDbPY is a Python package useful to retrieve and manage the data of the IMDb movie database about movies, people, characters and companies.

http://imdbpy.sourceforge.net/

CSS body background image fixed to full screen even when zooming in/out

Use Directly like this

.bg-div{
     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

or call CSS separately like

.bg-div{
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to set <Text> text to upper case in react native

@Cherniv Thanks for the answer

<Text style={{}}> {'Test'.toUpperCase()} </Text>

Xcode iOS 8 Keyboard types not supported

This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

USE BINARY_CHECKSUM

SELECT 
FROM Users
WHERE   
    BINARY_CHECKSUM(Username) = BINARY_CHECKSUM(@Username)
    AND BINARY_CHECKSUM(Password) = BINARY_CHECKSUM(@Password)

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

I'm using jQuery 3.3.1 and I received the same error, in my case, the URL was an Object vs a string.

What happened was, that I took URL = window.location - which returned an object. Once I've changed it into window.location.href - it worked w/o the e.indexOf error.

How to monitor Java memory usage?

As has been suggested, try VisualVM to get a basic view.

You can also use Eclipse MAT, to do a more detailed memory analysis.

It's ok to do a System.gc() as long as you dont depend on it, for the correctness of your program.

Disable spell-checking on HTML textfields

If you have created your HTML element dynamically, you'll want to disable the attribute via JS. There is a little trap however:

When setting elem.contentEditable you can use either the boolean false or the string "false". But when you set elem.spellcheck, you can only use the boolean - for some reason. Your options are thus:

elem.spellcheck = false;

Or the option Mac provided in his answer:

elem.setAttribute("spellcheck", "false"); // Both string and boolean work here. 

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

Python 3 Building an array of bytes

agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack(). http://docs.python.org/release/3.1.3/library/struct.html

How to configure postgresql for the first time?

The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.

  1. Connect to the default database with user postgres:

    sudo -u postgres psql template1

  2. Set the password for user postgres, then exit psql (Ctrl-D):

    ALTER USER postgres with encrypted password 'xxxxxxx';

  3. Edit the pg_hba.conf file:

    sudo vim /etc/postgresql/9.1/main/pg_hba.conf

    and change "peer" to "md5" on the line concerning postgres:

    local      all     postgres     peer md5

    To know what version of postgresql you are running, look for the version folder under /etc/postgresql. Also, you can use Nano or other editor instead of VIM.

  4. Restart the database :

    sudo /etc/init.d/postgresql restart

    (Here you can check if it worked with psql -U postgres).

  5. Create a user having the same name as you (to find it, you can type whoami):

    sudo createuser -U postgres -d -e -E -l -P -r -s <my_name>

    The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb.

    Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).

  6. Again, edit the pg_hba.conf file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:

    local      all     all     peer md5

  7. Restart (like in step 4), and check that you can login without -U postgres:

    psql template1

    Note that if you do a mere psql, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami). template1 is the admin database that is here from the start.

  8. Now createdb <dbname> should work.

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

Plot width settings in ipython notebook

This is way I did it:

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)

You can define your own sizes.

How can I get the current directory name in Javascript?

You can use window.location.pathname.split('/');

That will produce an array with all of the items between the /'s

Creating runnable JAR with Gradle

Have you tried the 'installApp' task? Does it not create a full directory with a set of start scripts?

http://www.gradle.org/docs/current/userguide/application_plugin.html

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Retrofit 2.3.0

    // Load CAs from an InputStream
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

    InputStream inputStream = context.getResources().openRawResource(R.raw.ssl_certificate); //(.crt)
    Certificate certificate = certificateFactory.generateCertificate(inputStream);
    inputStream.close();

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", certificate);

    // Create a TrustManager that trusts the CAs in our KeyStore.
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
    trustManagerFactory.init(keyStore);

    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    X509TrustManager x509TrustManager = (X509TrustManager) trustManagers[0];


    // Create an SSLSocketFactory that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
    sslSocketFactory = sslContext.getSocketFactory();

    //create Okhttp client
    OkHttpClient client = new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory,x509TrustManager)
                .build();

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();

Why don't self-closing script elements work?

XHTML 1 specification says:

?.3. Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />).

XHTML DTD specifies script elements as:

<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

Alternative for PHP_excel

For Writing Excel

  • PEAR's PHP_Excel_Writer (xls only)
  • php_writeexcel from Bettina Attack (xls only)
  • XLS File Generator commercial and xls only
  • Excel Writer for PHP from Sourceforge (spreadsheetML only)
  • Ilia Alshanetsky's Excel extension now on github (xls and xlsx, and requires commercial libXL component)
  • PHP's COM extension (requires a COM enabled spreadsheet program such as MS Excel or OpenOffice Calc running on the server)
  • The Open Office alternative to COM (PUNO) (requires Open Office installed on the server with Java support enabled)
  • PHP-Export-Data by Eli Dickinson (Writes SpreadsheetML - the Excel 2003 XML format, and CSV)
  • Oliver Schwarz's php-excel (SpreadsheetML)
  • Oliver Schwarz's original version of php-excel (SpreadsheetML)
  • excel_xml (SpreadsheetML, despite its name)... link reported as broken
  • The tiny-but-strong (tbs) project includes the OpenTBS tool for creating OfficeOpenXML documents (OpenDocument and OfficeOpenXML formats)
  • SimpleExcel Claims to read and write Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats
  • KoolGrid xls spreadsheets only, but also doc and pdf
  • PHP_XLSXWriter OfficeOpenXML
  • PHP_XLSXWriter_plus OfficeOpenXML, fork of PHP_XLSXWriter
  • php_writeexcel xls only (looks like it's based on PEAR SEW)
  • spout OfficeOpenXML (xlsx) and CSV
  • Slamdunk/php-excel (xls only) looks like an updated version of the old PEAR Spreadsheet Writer

For Reading Excel

A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.

All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.

Traversing text in Insert mode

You could use imap to map any key in insert mode to one of the cursor keys. Like so:

imap h <Left>

Now h works like in normal mode, moving the cursor. (Mapping h in this way is obviously a bad choice)

Having said that I do not think the standard way of moving around in text using VIM is "not productive". There are lots of very powerful ways of traversing the text in normal mode (like using w and b, or / and ?, or f and F, etc.)

How to check if a character is upper-case in Python?

Maybe you want str.istitle

>>> help(str.istitle)
Help on method_descriptor:

istitle(...)
    S.istitle() -> bool

    Return True if S is a titlecased string and there is at least one
    character in S, i.e. uppercase characters may only follow uncased
    characters and lowercase characters only cased ones. Return False
    otherwise.

>>> "Alpha_beta_Gamma".istitle()
False
>>> "Alpha_Beta_Gamma".istitle()
True
>>> "Alpha_Beta_GAmma".istitle()
False

"Fatal error: Unable to find local grunt." when running "grunt" command

if you are a exists project, maybe should execute npm install.

guntjs getting started step 2.

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

How to execute Python code from within Visual Studio Code

As stated in Visual Studio Code documentation, just right-click anywhere in the editor and select Run Python File in Terminal.

Callback when CSS3 transition finishes

There is an animationend Event that can be observed see documentation here, also for css transition animations you could use the transitionend event

There is no need for additional libraries these all work with vanilla JS

_x000D_
_x000D_
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
 this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
_x000D_
_x000D_

How do I write a Windows batch script to copy the newest file from a directory?

Windows shell, one liner:

FOR /F %%I IN ('DIR *.* /B /O:-D') DO COPY %%I <<NewDir>> & EXIT

Disable browser 'Save Password' functionality

if autocomplete="off" is not working...remove the form tag and use a div tag instead, then pass the form values using jquery to the server. This worked for me.

how to configuring a xampp web server for different root directory

# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks Includes ExecCGI

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride All

#
# Controls who can get stuff from this server.
#
Require all granted

Write above code inside following tags < Directory "c:\projects" > < / Directory > c:(you can add any directory d: e:) is drive where you have created your project folder.

Alias /projects "c:\projects"

Now you can access the pr0jects directory on your browser :

localhost/projects/

How can I check if mysql is installed on ubuntu?

Multiple ways of searching for the program.

Type mysql in your terminal, see the result.

Search the /usr/bin, /bin directories for the binary.

Type apt-cache show mysql to see if it is installed

locate mysql

How can I check if an array contains a specific value in php?

Using dynamic variable for search in array

 /* https://ideone.com/Pfb0Ou */

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

/* variable search */
$search = 'living_room';

if (in_array($search, $array)) {
    echo "this array contains $search";
} else
    echo "this array NOT contains $search";

Class not registered Error

I was getting the below error in my 32 bit application.

Error: Retrieving the COM class factory for component with CLSID {4911BB26-11EE-4182-B66C-64DF2FA6502D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

And on setting the "Enable32bitApplications" to true in defaultapplicationpool in IIS worked for me.

How to get "wc -l" to print just the number of lines without file name?

Best way would be first of all find all files in directory then use AWK NR (Number of Records Variable)

below is the command :

find <directory path>  -type f | awk  'END{print NR}'

example : - find /tmp/ -type f | awk 'END{print NR}'

How to find all positions of the maximum value in a list?

The chosen answer (and most others) require at least two passes through the list.
Here's a one pass solution which might be a better choice for longer lists.

Edited: To address the two deficiencies pointed out by @John Machin. For (2) I attempted to optimize the tests based on guesstimated probability of occurrence of each condition and inferences allowed from predecessors. It was a little tricky figuring out the proper initialization values for max_val and max_indices which worked for all possible cases, especially if the max happened to be the first value in the list — but I believe it now does.

def maxelements(seq):
    ''' Return list of position(s) of largest element '''
    max_indices = []
    if seq:
        max_val = seq[0]
        for i,val in ((i,val) for i,val in enumerate(seq) if val >= max_val):
            if val == max_val:
                max_indices.append(i)
            else:
                max_val = val
                max_indices = [i]

    return max_indices

Overlaying histograms with ggplot2 in R

Using @joran's sample data,

ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")

note that the default position of geom_histogram is "stack."

see "position adjustment" of this page:

docs.ggplot2.org/current/geom_histogram.html

What is JavaScript garbage collection?

What is JavaScript garbage collection?

check this

What's important for a web programmer to understand about JavaScript garbage collection, in order to write better code?

In Javascript you don't care about memory allocation and deallocation. The whole problem is demanded to the Javascript interpreter. Leaks are still possible in Javascript, but they are bugs of the interpreter. If you are interested in this topic you could read more in www.memorymanagement.org

AngularJs ReferenceError: $http is not defined

Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.


You can also use $inject to add a dependency:

var MyController = function($scope, $http) {
  // ...
}
MyController.$inject = ['$scope', '$http'];

Sum all the elements java arraylist

Java 8+ version for Integer, Long, Double and Float

    List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
    List<Long> longs = Arrays.asList(1L, 2L, 3L, 4L, 5L);
    List<Double> doubles = Arrays.asList(1.2d, 2.3d, 3.0d, 4.0d, 5.0d);
    List<Float> floats = Arrays.asList(1.3f, 2.2f, 3.0f, 4.0f, 5.0f);

    long intSum = ints.stream()
            .mapToLong(Integer::longValue)
            .sum();

    long longSum = longs.stream()
            .mapToLong(Long::longValue)
            .sum();

    double doublesSum = doubles.stream()
            .mapToDouble(Double::doubleValue)
            .sum();

    double floatsSum = floats.stream()
            .mapToDouble(Float::doubleValue)
            .sum();

    System.out.println(String.format(
            "Integers: %s, Longs: %s, Doubles: %s, Floats: %s",
            intSum, longSum, doublesSum, floatsSum));

15, 15, 15.5, 15.5

how to set JAVA_OPTS for Tomcat in Windows?

Try

set JAVA_OPTS=%JAVA_OPTS% -Xms512M -Xmx1024M

How to copy an object in Objective-C

I don't know the difference between that code and mine, but I have problems with that solution, so I read a little bit more and found that we have to set the object before return it. I mean something like:

#import <Foundation/Foundation.h>

@interface YourObject : NSObject <NSCopying>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;

-(id) copyWithZone: (NSZone *) zone;

@end


@implementation YourObject


-(id) copyWithZone: (NSZone *) zone
{
    YourObject *copy = [[YourObject allocWithZone: zone] init];

    [copy setNombre: self.name];
    [copy setLinea: self.line];
    [copy setTags: self.tags];
    [copy setHtmlSource: self.htmlSource];

    return copy;
}

I added this answer because I have a lot of problems with this issue and I have no clue about why is it happening. I don't know the difference, but it's working for me and maybe it can be useful for others too : )

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

What is context in _.each(list, iterator, [context])?

As explained in other answers, context is the this context to be used inside callback passed to each.

I'll explain this with the help of source code of relevant methods from underscore source code

The definition of _.each or _.forEach is as follows:

_.each = _.forEach = function(obj, iteratee, context) {
  iteratee = optimizeCb(iteratee, context);

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

Second statement is important to note here

iteratee = optimizeCb(iteratee, context);

Here, context is passed to another method optimizeCb and the returned function from it is then assigned to iteratee which is called later.

var optimizeCb = function(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1:
      return function(value) {
        return func.call(context, value);
      };
    case 2:
      return function(value, other) {
        return func.call(context, value, other);
      };
    case 3:
      return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
    case 4:
      return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
  }
  return function() {
    return func.apply(context, arguments);
  };
};

As can be seen from the above method definition of optimizeCb, if context is not passed then func is returned as it is. If context is passed, callback function is called as

func.call(context, other_parameters);
          ^^^^^^^

func is called with call() which is used to invoke a method by setting this context of it. So, when this is used inside func, it'll refer to context.

_x000D_
_x000D_
// Without `context`_x000D_
_.each([1], function() {_x000D_
  console.log(this instanceof Window);_x000D_
});_x000D_
_x000D_
_x000D_
// With `context` as `arr`_x000D_
var arr = [1, 2, 3];_x000D_
_.each([1], function() {_x000D_
  console.log(this);_x000D_
}, arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

You can consider context as the last optional parameter to forEach in JavaScript.

Read text file into string array (and write)

Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func writeLines(lines []string, path string) (err error) {
    var (
        file *os.File
    )

    if file, err = os.Create(path); err != nil {
        return
    }
    defer file.Close()

    //writer := bufio.NewWriter(file)
    for _,item := range lines {
        //fmt.Println(item)
        _, err := file.WriteString(strings.TrimSpace(item) + "\n"); 
        //file.Write([]byte(item)); 
        if err != nil {
            //fmt.Println("debug")
            fmt.Println(err)
            break
        }
    }
    /*content := strings.Join(lines, "\n")
    _, err = writer.WriteString(content)*/
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
    //array := []string{"7.0", "8.5", "9.1"}
    err = writeLines(lines, "foo2.txt")
    fmt.Println(err)
}

How to define a circle shape in an Android XML drawable file?

If you want a circle like this

enter image description here

Try using the code below:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="0dp"
    android:shape="ring"
    android:thicknessRatio="2"
    android:useLevel="false" >
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dp"
        android:color="@android:color/darker_gray" />
</shape>

Java Immutable Collections

Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);

c1 is mutable (i.e. neither unmodifiable nor immutable).
c2 is unmodifiable: it can't be changed itself, but if later on I change c1 then that change will be visible in c2.

This is because c2 is simply a wrapper around c1 and not really an independent copy. Guava provides the ImmutableList interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).

Regarding your second question:

The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.

Session timeout in ASP.NET

After changing the session timeout value in IIS, Kindly restart the IIS. To achieve this go to command prompt. Type IISRESET and press enter.

Deleting Objects in JavaScript

I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop() all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.

Play sound on button click android

  • The audio must be placed in the raw folder, if it doesn't exists, create one.
  • The raw folder must be inside the res folder
  • The name mustn't have any - or special characters in it.

On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.

Example:

private Button myButton;
private MediaPlayer mp;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);
        mp = MediaPlayer.create(this, R.raw.gunshot);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
}
}

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

In my case, my App icon files were not in the camel case notation. For example:

My Filename: Appicon57x57

Should be: AppIcon57x57 (note the capital 'i' here)

So, in my case the solution was this:

  1. Remove all the icon files from the Asset Catalog.
  2. Rename the file as mentioned above.
  3. Add the renamed files back to the Asset Catalog again.

This should fix the problem.

What's the best way to detect a 'touch screen' device using JavaScript?

The biggest "gotcha" with trying to detect touch is on hybrid devices that support both touch and the trackpad/mouse. Even if you're able to correctly detect whether the user's device supports touch, what you really need to do is detect what input device the user is currently using. There's a detailed write up of this challenge and a possible solution here.

Basically the approach to figuring out whether a user just touched the screen or used a mouse/ trackpad instead is to register both a touchstart and mouseover event on the page:

document.addEventListener('touchstart', functionref, false) // on user tap, "touchstart" fires first
document.addEventListener('mouseover', functionref, false) // followed by mouse event, ie: "mouseover"

A touch action will trigger both of these events, though the former (touchstart) always first on most devices. So counting on this predictable sequence of events, you can create a mechanism that dynamically adds or removes a can-touch class to the document root to reflect the current input type of the user at this moment on the document:

;(function(){
    var isTouch = false //var to indicate current input type (is touch versus no touch) 
    var isTouchTimer 
    var curRootClass = '' //var indicating current document root class ("can-touch" or "")
     
    function addtouchclass(e){
        clearTimeout(isTouchTimer)
        isTouch = true
        if (curRootClass != 'can-touch'){ //add "can-touch' class if it's not already present
            curRootClass = 'can-touch'
            document.documentElement.classList.add(curRootClass)
        }
        isTouchTimer = setTimeout(function(){isTouch = false}, 500) //maintain "istouch" state for 500ms so removetouchclass doesn't get fired immediately following a touch event
    }
     
    function removetouchclass(e){
        if (!isTouch && curRootClass == 'can-touch'){ //remove 'can-touch' class if not triggered by a touch event and class is present
            isTouch = false
            curRootClass = ''
            document.documentElement.classList.remove('can-touch')
        }
    }
     
    document.addEventListener('touchstart', addtouchclass, false) //this event only gets called when input type is touch
    document.addEventListener('mouseover', removetouchclass, false) //this event gets called when input type is everything from touch to mouse/ trackpad
})();

More details here.

Join/Where with LINQ and Lambda

This linq query Should work for you. It will get all the posts that have post meta.

var query = database.Posts.Join(database.Post_Metas,
                                post => post.postId, // Primary Key
                                meta => meat.postId, // Foreign Key
                                (post, meta) => new { Post = post, Meta = meta });

Equivalent SQL Query

Select * FROM Posts P
INNER JOIN Post_Metas pm ON pm.postId=p.postId

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

Getting the last element of a split string array

And if you don't want to construct an array ...

var str = "how,are you doing, today?";
var res = str.replace(/(.*)([, ])([^, ]*$)/,"$3");

The breakdown in english is:

/(anything)(any separator once)(anything that isn't a separator 0 or more times)/

The replace just says replace the entire string with the stuff after the last separator.

So you can see how this can be applied generally. Note the original string is not modified.

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

Assigning a variable NaN in python without numpy

You can get NaN from "inf - inf", and you can get "inf" from a number greater than 2e308, so, I generally used:

>>> inf = 9e999
>>> inf
inf
>>> inf - inf
nan

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

What are non-recursive mutexes good for?

They are absolutely good when you have to make sure the mutex is unlocked before doing something. This is because pthread_mutex_unlock can guarantee that the mutex is unlocked only if it is non-recursive.

pthread_mutex_t      g_mutex;

void foo()
{
    pthread_mutex_lock(&g_mutex);
    // Do something.
    pthread_mutex_unlock(&g_mutex);

    bar();
}

If g_mutex is non-recursive, the code above is guaranteed to call bar() with the mutex unlocked.

Thus eliminating the possibility of a deadlock in case bar() happens to be an unknown external function which may well do something that may result in another thread trying to acquire the same mutex. Such scenarios are not uncommon in applications built on thread pools, and in distributed applications, where an interprocess call may spawn a new thread without the client programmer even realising that. In all such scenarios it's best to invoke the said external functions only after the lock is released.

If g_mutex was recursive, there would be simply no way to make sure it is unlocked before making a call.

How can I find out which server hosts LDAP on my windows domain?

If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

How to add hyperlink in JLabel?

Just put window.open(website url), it works every time.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Best way to change the background color for an NSView

I tested the following and it worked for me (in Swift):

view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

Best way to run scheduled tasks

Here's another way:

1) Create a "heartbeat" web script that is responsible for launching the tasks if they are DUE or overdue to be launched.

2) Create a scheduled process somewhere (preferrably on the same web server) that hits the webscript and forces it to run at a regular interval. (e.g. windows schedule task that quietly launches the heatbeat script using IE or whathaveyou)

The fact that the task code is contained within a web script is purely for the sake of keeping the code within the web application code-base (the assumption is that both are dependent on each other), which would be easier for web developers to manage.

The alternate approach is to create an executable server script / program that does all the schedule work itself and run the executable itself as a scheduled task. This can allow for fundamental decoupling between the web application and the scheduled task. Hence if you need your scheduled tasks to run even in the even that the web app / database might be down or inaccessible, you should go with this approach.

Concatenate text files with Windows command line, dropping leading lines

more +2 file2.txt > temp
type temp file1.txt > out.txt

or you can use copy. See copy /? for more.

copy /b temp+file1.txt  out.txt

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];
fruitvegbasket.push(veggies);

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

How to edit the size of the submit button on a form?

Just add style="width:auto"

<input type="submit" id="search" value="Search" style="width:auto" />

This worked for me in IE, Firefox and Chrome.

Plot multiple lines in one graph

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)

tab<-t(tab)

plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

R multiple lines plot

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

What's the difference between ViewData and ViewBag?

It uses the C# 4.0 dynamic feature. It achieves the same goal as viewdata and should be avoided in favor of using strongly typed view models (the same way as viewdata should be avoided).

So basically it replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

for which you have no compile time safety.

I continue to blame Microsoft for ever introducing this concept in MVC.

The name of the properties are case sensitive.

How do I get the value of a textbox using jQuery?

Possible Duplicate:

Just Additional Info which took me long time to find.what if you were using the field name and not id for identifying the form field. You do it like this:

For radio button:

 var inp= $('input:radio[name=PatientPreviouslyReceivedDrug]:checked').val();

For textbox:

 var txt=$('input:text[name=DrugDurationLength]').val();

Find size of object instance in bytes in c#

For unmanaged types aka value types, structs:

        Marshal.SizeOf(object);

For managed objects the closer i got is an approximation.

        long start_mem = GC.GetTotalMemory(true);

        aclass[] array = new aclass[1000000];
        for (int n = 0; n < 1000000; n++)
            array[n] = new aclass();

        double used_mem_median = (GC.GetTotalMemory(false) - start_mem)/1000000D;

Do not use serialization.A binary formatter adds headers, so you can change your class and load an old serialized file into the modified class.

Also it won't tell you the real size in memory nor will take into account memory alignment.

[Edit] By using BiteConverter.GetBytes(prop-value) recursivelly on every property of your class you would get the contents in bytes, that doesn't count the weight of the class or references but is much closer to reality. I would recommend to use a byte array for data and an unmanaged proxy class to access values using pointer casting if size matters, note that would be non-aligned memory so on old computers is gonna be slow but HUGE datasets on MODERN RAM is gonna be considerably faster, as minimizing the size to read from RAM is gonna be a bigger impact than unaligned.

iconv - Detected an illegal character in input string

this bellow solution worked for me

$result_encr="##Sƒ";

iconv("cp1252", "utf-8//IGNORE", $result_encr);

How to open the second form?

On any click event (or other one):

Form2 frm2 = new Form2();
frm2.Show();

How to generate a random number between a and b in Ruby?

See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

Just to add to the other answers, the documentation gives this explanation:

  • KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

  • A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

  • A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.

basic authorization command for curl

Background

You can use the base64 CLI tool to generate the base64 encoded version of your username + password like this:

$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz

-or-

$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==

Base64 is reversible so you can also decode it to confirm like this:

$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass

-or-

$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass

NOTE: username = joeuser, password = secretpass

Example #1 - using -H

You can put this together into curl like this:

$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com

Example #2 - using -u

Most will likely agree that if you're going to bother doing this, then you might as well just use curl's -u option.

$ curl --help |grep -- "--user "
 -u, --user USER[:PASSWORD]  Server user and password

For example:

$ curl -u someuser:secretpass http://example.com

But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.

For example, here I'm using the LastPass' CLI tool, lpass, to retrieve my credentials:

$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
     http://example.com

Example #3 - using curl config

There's an even safer way to hand your credentials off to curl though. This method makes use of the -K switch.

$ curl -X GET -K \
    <(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
    http://example.com

When used, your details remain hidden, since they're passed to curl via a temporary file descriptor, for example:

+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%       

NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.

This method is dynamically creating a file with the contents user = "<username>:<password>" and giving that to curl.

HTTP Basic Authorization

The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.

When the user agent wants to send authentication credentials to the server, it may use the Authorization field.

The Authorization field is constructed as follows:

  1. The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
  2. The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
  3. The resulting string is encoded using a variant of Base64.
  4. The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.

For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:

Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l

Source: Basic access authentication

Calculate distance between two points in google maps V3

To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:

private void build_retrofit_and_get_response(String type) {

    String url = "https://maps.googleapis.com/maps/";

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitMaps service = retrofit.create(RetrofitMaps.class);

    Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);

    call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Response<Example> response, Retrofit retrofit) {

            try {
                //Remove previous line from map
                if (line != null) {
                    line.remove();
                }
                // This loop will go through all the results and add marker on each location.
                for (int i = 0; i < response.body().getRoutes().size(); i++) {
                    String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
                    String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
                    ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
                    String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
                    List<LatLng> list = decodePoly(encodedString);
                    line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(20)
                                    .color(Color.RED)
                                    .geodesic(true)
                    );
                }
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d("onFailure", t.toString());
        }
    });

}

Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:

package com.androidtutorialpoint.googlemapsdistancecalculator;


import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;

public interface RetrofitMaps {


/*
 * Retrofit get annotation with our URL
 * And our method that will return us details of student.
 */
@GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode);

}

I hope this explains your query. All the best :)

Source: Google Maps Distance Calculator

How do I increase the capacity of the Eclipse output console?

For C++ users, to increase the Build console output size see here

ie Windows > Preference > C/C++ > Build > Console

How does Content Security Policy (CSP) work?

The Content-Security-Policy meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.

I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.

For brevity I won’t write the full tag in each sample. Instead I'll only show the content property, so a sample that says content="default-src 'self'" means this:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

1. How can I allow multiple sources?

You can simply list your sources after a directive as a space-separated list:

content="default-src 'self' https://example.com/js/"

Note that there are no quotes around parameters other than the special ones, like 'self'. Also, there's no colon (:) after the directive. Just the directive, then a space-separated list of parameters.

Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:

https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js

These, however, would not be valid:

http://example.com/js/file.js
^^^^ wrong protocol

https://example.com/file.js
                   ^^ above the specified path

2. How can I use different directives? What do they each do?

The most common directives are:

  • default-src the default policy for loading javascript, images, CSS, fonts, AJAX requests, etc
  • script-src defines valid sources for javascript files
  • style-src defines valid sources for css files
  • img-src defines valid sources for images
  • connect-src defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400 error

There are others, but these are the ones you're most likely to need.

3. How can I use multiple directives?

You define all your directives inside one meta-tag by terminating them with a semicolon (;):

content="default-src 'self' https://example.com/js/; style-src 'self'"

4. How can I handle ports?

Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:

content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"

The above would result in:

https://ajax.googleapis.com:123
                           ^^^^ Not ok, wrong port

https://ajax.googleapis.com - OK

http://example.com/free/stuff/file.js
                 ^^ Not ok, only the port 123 is allowed

http://example.com:123/free/stuff/file.js - OK

As I mentioned, you can also use an asterisk to explicitly allow all ports:

content="default-src example.com:*"

5. How can I handle different protocols?

By default, only standard protocols are allowed. For example to allow WebSockets ws:// you will have to allow it explicitly:

content="default-src 'self'; connect-src ws:; style-src 'self'"
                                         ^^^ web Sockets are now allowed on all domains and ports.

6. How can I allow the file protocol file://?

If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem parameter:

content="default-src filesystem"

7. How can I use inline scripts and style definitions?

Unless explicitly allowed, you can't use inline style definitions, code inside <script> tags or in tag properties like onclick. You allow them like so:

content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"

You'll also have to explicitly allow inline, base64 encoded images:

content="img-src data:"

8. How can I allow eval()?

I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:

content="script-src 'unsafe-eval'"

9. What exactly does 'self' mean?

You might take 'self' to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.

I've used 'self' in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.

But hang on a minute! Can't I just use content="default-src *" and be done with it?

No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:

content="default-src * 'unsafe-inline' 'unsafe-eval'"

... but I trust you won’t.

Further reading:

http://content-security-policy.com

http://en.wikipedia.org/wiki/Content_Security_Policy

Returning a C string from a function

If you really can't use pointers, do something like this:

char get_string_char(int index)
{
    static char array[] = "my string";
    return array[index];
}

int main()
{
    for (int i = 0; i < 9; ++i)
        printf("%c", get_string_char(i));
    printf("\n");
    return 0;
}

The magic number 9 is awful, and this is not an example of good programming. But you get the point. Note that pointers and arrays are the same thing (kind of), so this is a bit cheating.

ExtJs Gridpanel store refresh

Try refreshing the view:

Ext.getCmp('yourGridId').getView().refresh();

What does the ^ (XOR) operator do?

XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.

This is its function table:

a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

This operation is performed between every two corresponding bits of a number.

Example: 7 ^ 10
In binary: 0111 ^ 1010

  0111
^ 1010
======
  1101 = 13

Properties: The operation is commutative, associative and self-inverse.

It is also the same as addition modulo 2.

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

Convert a CERT/PEM certificate to a PFX certificate

Here is how to do this on Windows without third-party tools:

  1. Import certificate to the certificate store. In Windows Explorer select "Install Certificate" in context menu. enter image description here Follow the wizard and accept default options "Local User" and "Automatically".

  2. Find your certificate in certificate store. On Windows 10 run the "Manage User Certificates" MMC. On Windows 2013 the MMC is called "Certificates". On Windows 10 by default your certificate should be under "Personal"->"Certificates" node.

  3. Export Certificate. In context menu select "Export..." menu: enter image description here

    Select "Yes, export the private key": enter image description here

    You will see that .PFX option is enabled in this case: enter image description here

    Specify password for private key.

Show / hide div on click with CSS

You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.

How can I convert integer into float in Java?

// The integer I want to convert

int myInt = 100;

// Casting of integer to float

float newFloat = (float) myInt

What is the difference between HAVING and WHERE in SQL?

When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.

However, when GROUP BY is used:

  • The WHERE clause is used to filter records from a result. The filtering occurs before any groupings are made.
  • The HAVING clause is used to filter values from a group (i.e., to check conditions after aggregation into groups has been performed).

Use jquery click to handle anchor onClick()

The first time you click the link, the openSolution function is executed. That function binds the click event handler to the link, but it won't execute it. The second time you click the link, the click event handler will be executed.

What you are doing seems to kind of defeat the point of using jQuery in the first place. Why not just bind the click event to the elements in the first place:

$(document).ready(function() {
    $("#solTitle a").click(function() {
        //Do stuff when clicked
    });
});

This way you don't need onClick attributes on your elements.

It also looks like you have multiple elements with the same id value ("solTitle"), which is invalid. You would need to find some other common characteristic (class is usually a good option). If you change all occurrences of id="solTitle" to class="solTitle", you can then use a class selector:

$(".solTitle a")

Since duplicate id values is invalid, the code will not work as expected when facing multiple copies of the same id. What tends to happen is that the first occurrence of the element with that id is used, and all others are ignored.

How to convert a UTF-8 string into Unicode?

If you have a UTF-8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the following:

public static string Utf8ToUtf16(string utf8String)
{
    /***************************************************************
     * Every .NET string will store text with the UTF-16 encoding, *
     * known as Encoding.Unicode. Other encodings may exist as     *
     * Byte-Array or incorrectly stored with the UTF-16 encoding.  *
     *                                                             *
     * UTF-8 = 1 bytes per char                                    *
     *    ["100" for the ansi 'd']                                 *
     *    ["206" and "186" for the russian '?']                    *
     *                                                             *
     * UTF-16 = 2 bytes per char                                   *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["186, 3" for the russian '?']                           *
     *                                                             *
     * UTF-8 inside UTF-16                                         *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["206, 0" and "186, 0" for the russian '?']              *
     *                                                             *
     * First we need to get the UTF-8 Byte-Array and remove all    *
     * 0 byte (binary 0) while doing so.                           *
     *                                                             *
     * Binary 0 means end of string on UTF-8 encoding while on     *
     * UTF-16 one binary 0 does not end the string. Only if there  *
     * are 2 binary 0, than the UTF-16 encoding will end the       *
     * string. Because of .NET we don't have to handle this.       *
     *                                                             *
     * After removing binary 0 and receiving the Byte-Array, we    *
     * can use the UTF-8 encoding to string method now to get a    *
     * UTF-16 string.                                              *
     *                                                             *
     ***************************************************************/

    // Get UTF-8 bytes and remove binary 0 bytes (filler)
    List<byte> utf8Bytes = new List<byte>(utf8String.Length);
    foreach (byte utf8Byte in utf8String)
    {
        // Remove binary 0 bytes (filler)
        if (utf8Byte > 0) {
            utf8Bytes.Add(utf8Byte);
        }
    }

    // Convert UTF-8 bytes to UTF-16 string
    return Encoding.UTF8.GetString(utf8Bytes.ToArray());
}

In my case the DLL result is a UTF-8 string too, but unfortunately the UTF-8 string is interpreted with UTF-16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 was converted to the UTF-16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf8ToUtf16(string utf8String)
{
    // Get UTF-8 bytes by reading each byte with ANSI encoding
    byte[] utf8Bytes = Encoding.Default.GetBytes(utf8String);

    // Convert UTF-8 bytes to UTF-16 bytes
    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);

    // Return UTF-16 bytes as UTF-16 string
    return Encoding.Unicode.GetString(utf16Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 MultiByteToWideChar(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPStr)] String lpMultiByteStr, Int32 cbMultiByte, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, Int32 cchWideChar);

public static string Utf8ToUtf16(string utf8String)
{
    Int32 iNewDataLen = MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, null, 0);
    if (iNewDataLen > 1)
    {
        StringBuilder utf16String = new StringBuilder(iNewDataLen);
        MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, utf16String, utf16String.Capacity);

        return utf16String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf16ToUtf8. Hope I could be of help.

JQuery datepicker not working

try adjusting the order in which your script runs. Place the script tag below the element it is trying to affect. Or leave it up at the top and wrap it in a $(document).ready() EDIT: and include the right file.

How to set time to 24 hour format in Calendar

if you replace in the function SimpleDateFormat("hh") with ("HH") will format the hour in 24 hours instead of 12.

SimpleDateFormat df = new SimpleDateFormat("HH:mm");

Return list from async/await method

In addition to @takemyoxygen's answer the convention of having a function name that ends in Async is that this function is truly asynchronous. I.e. it does not start a new thread and it doesn't simply call Task.Run. If that is all the code that is in your function, it will be better to remove it completely and simply have:

List<Item> list = await Task.Run(() => manager.GetList());

display HTML page after loading complete

Hide the body initially, and then show it with jQuery after it has loaded.

body {
    display: none;
}

$(function () {
    $('body').show();
}); // end ready

Also, it would be best to have $('body').show(); as the last line in your last and main .js file.

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

Calling Member Functions within Main C++

declare it "static" like this:

static void MyClass::printInformation() { return; }

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

Count number of tables in Oracle

select COUNT(*) from ALL_ALL_TABLES where OWNER='<Database-name>';

.....

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I had faced the same problem but it was on Visual studios's own web development server instead of IIS.The get around is to uncheck the option in Web tab under project properties, Apply server settings to all users(store in project file.).Hope it will save some one's valuable time.

Why do we use $rootScope.$broadcast in AngularJS?

$rootScope basically functions as an event listener and dispatcher.

To answer the question of how it is used, it used in conjunction with rootScope.$on;

$rootScope.$broadcast("hi");

$rootScope.$on("hi", function(){
    //do something
});

However, it is a bad practice to use $rootScope as your own app's general event service, since you will quickly end up in a situation where every app depends on $rootScope, and you do not know what components are listening to what events.

The best practice is to create a service for each custom event you want to listen to or broadcast.

.service("hiEventService",function($rootScope) {
    this.broadcast = function() {$rootScope.$broadcast("hi")}
    this.listen = function(callback) {$rootScope.$on("hi",callback)}
})

Safari 3rd party cookie iframe trick no longer working?

I used modified (added signed_request param to the link) Whiteagle's trick and it worked ok for safari, but IE is constantly refreshing the page in that case. So my solution for safari and internet explorer is:

$fbapplink = 'https://apps.facebook.com/[appnamespace]/';
$isms = stripos($_SERVER['HTTP_USER_AGENT'], 'msie') !== false;

// safari fix
if(! $isms  && !isset($_SESSION['signed_request'])) {

    if (isset($_GET["start_session"])) {
        $_SESSION['signed_request'] = $_GET['signed_request'];
        die(header("Location:" . $fbapplink ));

    }
    if (!isset($_GET["sid"])) {
        die(header("Location:?sid=" . session_id() . '&signed_request='.$_REQUEST['signed_request']));
    }
    $sid = session_id();
    if (empty($sid) || $_GET["sid"] != $sid) {
    ?>
    <script>
        top.window.location="?start_session=true";
    </script>
    <?php
    exit;
    }
}

// IE fix
header('P3P: CP="CAO PSA OUR"');
header('P3P: CP="HONK"');


.. later in the code

$sr = $_REQUEST['signed_request'];
if($sr) {
        $_SESSION['signed_request'] = $sr;
} else {
        $sr = $_SESSION['signed_request'];
}

CSS word-wrapping in div

It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the

overflow-x: scroll;

What happens if you remove that?

Vue is not defined

I found two main problems with that implementation. First, when you import the vue.js script you use type="JavaScript" as content-type which is wrong. You should remove this type parameter because by default script tags have text/javascript as default content-type. Or, just replace the type parameter with the correct content-type which is type="text/javascript".

The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ }); or adding a javascript function as shown in this example:

_x000D_
_x000D_
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
  /in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
  var demo = new Vue({_x000D_
    el: '#demo',_x000D_
    data: {_x000D_
      message: 'Hello Vue.js!'_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
  <p>{{message}}</p>_x000D_
  <input v-model="message">_x000D_
</div>
_x000D_
_x000D_
_x000D_

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

Letter Count on a string

x=str(input("insert string"))
c=0
for i in x:
   if 'a' in i:
      c=c+1
print(c)        

SVN: Folder already under version control but not comitting?

I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:

Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)

You will see the following Eclipse error message:

org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control

After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)

You will see the following message dialog: "File list is empty"

Press cancel and refresh the project in Eclipse. Your project should be under version control again.

Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.

How to implement __iter__(self) for a container object (Python)

In case you don't want to inherit from dict as others have suggested, here is direct answer to the question on how to implement __iter__ for a crude example of a custom dict:

class Attribute:
    def __init__(self, key, value):
        self.key = key
        self.value = value

class Node(collections.Mapping):
    def __init__(self):
        self.type  = ""
        self.attrs = [] # List of Attributes

    def __iter__(self):
        for attr in self.attrs:
            yield attr.key

That uses a generator, which is well described here.

Since we're inheriting from Mapping, you need to also implement __getitem__ and __len__:

    def __getitem__(self, key):
        for attr in self.attrs:
            if key == attr.key:
                return attr.value
        raise KeyError

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

How to run shell script file using nodejs?

Also, you can use shelljs plugin. It's easy and it's cross-platform.

Install command:

npm install [-g] shelljs

What is shellJS

ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!

An example of how it works:

var shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');

// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}

Also, you can use from the command line:

$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

Python - Passing a function into another function

Treat function as variable in your program so you can just pass them to other functions easily:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

How to format DateTime in Flutter , How to get current time in flutter?

Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

import 'package:jiffy/jiffy.dart';   

var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");

You can also do the following

var a = Jiffy().yMMMMd; // October 18, 2019

And you can also pass in your DateTime object, A string and an array

var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019

var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019

var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019

Is it possible to have multiple statements in a python lambda expression?

Putting the expressions in a list may simulate multiple expressions:

E.g.:

lambda x: [f1(x), f2(x), f3(x), x+1]

This will not work with statements.

How to select only date from a DATETIME field in MySQL?

Simply You can do

SELECT DATE(date_field) AS date_field FROM table_name

Installing python module within code

The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.

Use sys.executable to ensure that you will call the same pip associated with the current runtime.

import subprocess
import sys

def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

Use jQuery to change a second select list based on the first select list option

On the selected answer I see that when initially the page is loaded the selection of first option is prior fixed and therefore gives the option of all the categories in selection 2. You can avoid that by adding the first option as the following in both the select tag:- <option value="none" selected disabled hidden>Select an Option</option>

<select name="select1" id="select1">
<option value="none" selected disabled hidden>Select an Option</option>
<option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>


<select name="select2" id="select2">
<option value="none" selected disabled hidden>Select an Option</option>
  <option value="1">Banana</option>
  <option value="1">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Wolf</option>
  <option value="2">Fox</option>
  <option value="2">Bear</option>
  <option value="3">Eagle</option>
  <option value="3">Hawk</option>
  <option value="4">BWM<option>
</select>

How can I count the rows with data in an Excel sheet?

This is what I finally came up with, which works great!

{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}

Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

$(...).datepicker is not a function - JQuery - Bootstrap

Need to include jquery-ui too:

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

How to convert a file into a dictionary?

def get_pair(line):
    key, sep, value = line.strip().partition(" ")
    return int(key), value

with open("file.txt") as fd:    
    d = dict(get_pair(line) for line in fd)

Parse JSON String into List<string>

Since you are using JSON.NET, personally I would go with serialization so that you can have Intellisense support for your object. You'll need a class that represents your JSON structure. You can build this by hand, or you can use something like json2csharp to generate it for you:

e.g.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class RootObject
{
    public List<Person> People { get; set; }
}

Then, you can simply call JsonConvert's methods to deserialize the JSON into an object:

RootObject instance = JsonConvert.Deserialize<RootObject>(json);

Then you have Intellisense:

var firstName = instance.People[0].FirstName;
var lastName = instance.People[0].LastName;

Function inside a function.?

X returns (value +3), while Y returns (value*2)

Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56.

Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:

1) You can't call y() before calling x(), because function y() won't actually be defined until x() has executed once.

2) Calling x() twice will cause PHP to redeclare function y(), leading to a fatal error:

Fatal error: Cannot redeclare y()

The solution to both would be to split the code, so that both functions are declared independent of each other:

function x ($y) 
{
  return($y+3);
}

function y ($z)
{
  return ($z*2);
}

This is also a lot more readable.

Detect Click into Iframe using JavaScript

Assumptions -

  1. Your script runs outside the iframe BUT NOT in the outermost window.top window. (For outermost window, other blur solutions are good enough)
  2. A new page is opened replacing the current page / a new page in a new tab and control is switched to new tab.

This works for both sourceful and sourceless iframes

var ifr = document.getElementById("my-iframe");
var isMouseIn;
ifr.addEventListener('mouseenter', () => {
    isMouseIn = true;
});
ifr.addEventListener('mouseleave', () => {
    isMouseIn = false;
});
window.document.addEventListener("visibilitychange", () => {
    if (isMouseIn && document.hidden) {
        console.log("Click Recorded By Visibility Change");
    }
});
window.addEventListener("beforeunload", (event) => {
    if (isMouseIn) {
        console.log("Click Recorded By Before Unload");
    }
});

If a new tab is opened / same page unloads and the mouse pointer is within the Iframe, a click is considered

phpmyadmin logs out after 1440 secs

drive here your wamp installed then go to wamp then apps then your phpmyadmin version folder then go to libraries then edit config.default.php file e.g

E:\wamp\apps\phpmyadmin4.6.4\libraries\config.default.php

here you have to change

$cfg['LoginCookieRecall'] = true;

to

$cfg['LoginCookieRecall'] = false;

also you can change time of cookie instead to disable cookie recall

$cfg['LoginCookieValidity'] = 1440;

to

$cfg['LoginCookieValidity'] = anthing grater then 1440 

mine is

 $cfg['LoginCookieValidity'] = 199000;

after changing restart your server enter image description here

also there is another method but it reset when ever we restart our wamp server and here is that method also

login to your phpmyadmin dashbord then go to setting then click on features and in general tab you will see Login cookie validity put anything greater then 14400 but this is valid until next restart of your server.

enter image description here

How to use opencv in using Gradle?

You can do this very easily in Android Studio.

Follow the below steps to add Open CV in your project as library.

  1. Create a libraries folder underneath your project main directory. For example, if your project is OpenCVExamples, you would create a OpenCVExamples/libraries folder.

  2. Go to the location where you have SDK "\OpenCV-2.4.8-android-sdk\sdk" here you will find the java folder, rename it to opencv.

  3. Now copy the complete opencv directory from the SDK into the libraries folder you just created.

  4. Now create a build.gradle file in the opencv directory with the following contents

    apply plugin: 'android-library'
    
    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.9.+'
        }
    }
    
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.1"
    
        defaultConfig {
            minSdkVersion 8
            targetSdkVersion 19
            versionCode 2480
            versionName "2.4.8"
        }
    
        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                resources.srcDirs = ['src']
                res.srcDirs = ['res']
                aidl.srcDirs = ['src']
            }
        }
    }
    
  5. Edit your settings.gradle file in your application’s main directory and add this line:

    include ':libraries:opencv'
    
  6. Sync your project with Gradle and it should looks like this

    screen 1

  7. Right click on your project then click on the Open Module Settings then Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new module dependency.

    enter image description here

  8. Choose Module dependency. It will open a dialog with a list of modules to choose from; select “:libraries:opencv”.

    enter image description here

  9. Create a jniLibs folder in the /app/src/main/ location and copy the all the folder with *.so files (armeabi, armeabi-v7a, mips, x86) in the jniLibs from the OpenCV SDK.

    enter image description here

  10. Click OK. Now everything done, go and enjoy with OpenCV.

How to check if a folder exists

We can check files and thire Folders.

import java.io.*;
public class fileCheck
{
    public static void main(String arg[])
    {
        File f = new File("C:/AMD");
        if (f.exists() && f.isDirectory()) {
        System.out.println("Exists");
        //if the file is present then it will show the msg  
        }
        else{
        System.out.println("NOT Exists");
        //if the file is Not present then it will show the msg      
        }
    }
}

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

psycopg2: insert multiple rows with one query

executemany accept array of tuples

https://www.postgresqltutorial.com/postgresql-python/insert/

    """ array of tuples """
    vendor_list = [(value1,)]

    """ insert multiple vendors into the vendors table  """
    sql = "INSERT INTO vendors(vendor_name) VALUES(%s)"
    conn = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        # execute the INSERT statement
        cur.executemany(sql,vendor_list)
        # commit the changes to the database
        conn.commit()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

How do I get the title of the current active window using c#?

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

Publish to IIS, setting Environment Variable

@tredder solution with editing applicationHost.config is the one that works if you have several different applications located within virtual directories on IIS.

My case is:

  • I do have API project and APP project, under the same domain, placed in different virtual directories
  • Root page XXX doesn't seem to propagate ASPNETCORE_ENVIRONMENT variable to its children in virtual directories and...
  • ...I'm unable to set the variables inside the virtual directory as @NickAb described (got error The request is not supported. (Exception from HRESULT: 0x80070032) during saving changes in Configuration Editor):
  • Going into applicationHost.config and manually creating nodes like this:

    <location path="XXX/app"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location> <location path="XXX/api"> <system.webServer> <aspNetCore> <environmentVariables> <clear /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" /> </environmentVariables> </aspNetCore> </system.webServer> </location>

and restarting the IIS did the job.

Prepend line to beginning of a file

To put code to NPE's answer, I think the most efficient way to do this is:

def insert(originalfile,string):
    with open(originalfile,'r') as f:
        with open('newfile.txt','w') as f2: 
            f2.write(string)
            f2.write(f.read())
    os.rename('newfile.txt',originalfile)

Redirect to external URL with return in laravel

For Laravel 5.x / 6.x / 7.x use:

return redirect()->away('https://www.google.com');

as stated in the docs:

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Similar to what Luke Puplett is saying, the problem can be caused by not properly disposing or creating your context.

In my case, I had a class which accepted a context called ContextService:

public class ContextService : IDisposable
{
    private Context _context;

    public void Dispose()
    {
        _context.Dispose();
    }
    public ContextService(Context context)
    {
        _context = context;
    }
//... do stuff with the context

My context service had a function which updates an entity using an instantiated entity object:

        public void UpdateEntity(MyEntity myEntity, ICollection<int> ids)
        {
            var item = _context.Entry(myEntity);
            item.State = EntityState.Modified;
            item.Collection(x => x.RelatedEntities).Load();
            myEntity.RelatedEntities.Clear();
            foreach (var id in ids)
            {
                myEntity.RelatedEntities.Add(_context.RelatedEntities.Find(id));
            }
            _context.SaveChanges();
        }

All of this was fine, my controller where I initialized the service was the problem. My controller originally looked like this:

    private static NotificationService _service = 
        new NotificationService(new NotificationContext());
    public void Dispose()
    {
    }

I changed it to this and the error went away:

    private static NotificationService _service;
    public TemplateController()
    {
        _service = new NotificationService(new NotificationContext());
    }
    public void Dispose()
    {
        _service.Dispose();
    }

Pass a simple string from controller to a view MVC3

Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.

public class MyViewModel
{
    public string YourString { get; set; }
}

In the view

@model MyViewModel
@Html.Label(model => model.YourString)

In the controller

public ActionResult Index() 
{
     myViewModel = new MyViewModel();
     myViewModel.YourString = "However you are setting this."
     return View(myViewModel)
}

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

Disable time in bootstrap date time picker

Initialize your datetimepicker like this

For disable time

$(document).ready(function(){
    $('#dp3').datetimepicker({
      pickTime: false
    });
});

For disable date

$(document).ready(function(){
    $('#dp3').datetimepicker({
      pickDate: false
    });
});

To disable both date and time

$(document).ready(function(){
   $("#dp3").datetimepicker('disable'); 
});

please refer following documentation if you have any doubt

http://eonasdan.github.io/bootstrap-datetimepicker/#options

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

OpenCV & Python - Image too big to display

Use this for example:

cv2.namedWindow('finalImg', cv2.WINDOW_NORMAL)
cv2.imshow("finalImg",finalImg)

Error when trying vagrant up

This work for me on Windows 10: https://stackoverflow.com/a/31594225/2400373

But it is necessary to delete the file: Vagranfile after use the command:

vagrant init precise64 http://files.vagrantup.com/precise64.box

And after

vagrant up

Return array in a function

This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR ).

I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.

However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.

There a few ways you can handle this better. Pass in a std::vector or std::array (not sure if std::array was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.

std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
    // (before c++11)
    for(auto it = arr.begin(); it != arr.end(); ++it)
    { /* do stuff */ }

    // Note the following are for c++11 and higher.  They will work for all
    // the other examples below except for the stuff after the Edit.

    // (c++11 and up)
    for(auto it = std::begin(arr); it != std::end(arr); ++it)
    { /* do stuff */ }

    // range for loop (c++11 and up)
    for(auto& element : arr)
    { /* do stuff */ }

    return arr;
}

std::vector<int>& fillarr(std::vector<int>& arr)
{
    for(auto it = arr.begin(); it != arr.end(); ++it)
    { /* do stuff */ }
    return arr;
}

However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.

template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
    // N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
    for(int* it = arr; it != arr + N; ++it)
    { /* do stuff */ }
    return arr;
}

Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:

template <typename T>
using type_t = T;

template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
    // N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
    for(int* it = arr; it != arr + N; ++it)
    { /* do stuff */ }
    return arr;
}

This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:

type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

As I said, my type_t<> trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:

template<typename T>
struct type
{
  typedef T type;
};

typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

Which starts to look pretty ugly again, but at least is still more readable, though the typename may have been optional back then depending on the compiler, resulting in:

type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

And then of course you could have specified a specific type, rather than using my helper.

typedef int(&array5)[5];

array5 fillarr(array5 arr)
{
    // Prefer using the compiler to figure out how many elements there are
    // as it reduces the number of locations where you have to change if needed.
    for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
    { /* do stuff */ }
    return arr;
}

Back then, the free functions std::begin() and std::end() didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.

As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.

void other_function(type_t<int(&)[5]> x) { /* do something else */ }

void fn()
{
    int array[5];
    other_function(fillarr(array));
}

or

void fn()
{
    int array[5];
    auto& array2 = fillarr(array); // alias. But why bother.
    int forth_entry = array[4];
    int forth_entry2 = array2[4]; // same value as forth_entry
}

To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.

Edit

Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.

// separate size value
int* fillarr(int* arr, size_t size)
{
    for(int* it = arr; it != arr + size; ++it)
    { /* do stuff */ }
    return arr;
}

Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.

// separate end pointer
int* fillarr(int* arr, int* end)
{
    for(int* it = arr; it != end; ++it)
    { /* do stuff */ }
    return arr;
}

Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.

// I document that this function will ONLY take 5 elements and 
// return the same array of 5 elements.  If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
    for(int* it = arr; it != arr + 5; ++it)
    { /* do stuff */ }
    return arr;
}

Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.

You could pass a std::pair<int*, int*>, which you can use for begin and end and pass that around, but then it really stops looking like an array.

std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
    for(int* it = arr.first; it != arr.second; ++it)
    { /* do stuff */ }
    return arr; // if you change arr, then return the original arr value.
}

void fn()
{
    int array[5];
    auto array2 = fillarr(std::make_pair(&array[0], &array[5]));

    // Can be done, but you have the original array in scope, so why bother.
    int fourth_element = array2.first[4];
}

or

void other_function(std::pair<int*, int*> array)
{
    // Can be done, but you have the original array in scope, so why bother.
    int fourth_element = array2.first[4];
}

void fn()
{
    int array[5];
    other_function(fillarr(std::make_pair(&array[0], &array[5])));
}

Funny enough, this is very similar to how std::initializer_list work (c++11), but they don't work in this context.

Serializing enums with Jackson

Use @JsonCreator annotation, create method getType(), is serialize with toString or object working

{"ATIVO"}

or

{"type": "ATIVO", "descricao": "Ativo"}

...

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SituacaoUsuario {

    ATIVO("Ativo"),
    PENDENTE_VALIDACAO("Pendente de Validação"),
    INATIVO("Inativo"),
    BLOQUEADO("Bloqueado"),
    /**
     * Usuarios cadastrados pelos clientes que não possuem acesso a aplicacao,
     * caso venham a se cadastrar este status deve ser alterado
     */
    NAO_REGISTRADO("Não Registrado");

    private SituacaoUsuario(String descricao) {
        this.descricao = descricao;
    }

    private String descricao;

    public String getDescricao() {
        return descricao;
    }

    // TODO - Adicionar metodos dinamicamente
    public String getType() {
        return this.toString();
    }

    public String getPropertieKey() {
        StringBuilder sb = new StringBuilder("enum.");
        sb.append(this.getClass().getName()).append(".");
        sb.append(toString());
        return sb.toString().toLowerCase();
    }

    @JsonCreator
    public static SituacaoUsuario fromObject(JsonNode node) {
        String type = null;
        if (node.getNodeType().equals(JsonNodeType.STRING)) {
            type = node.asText();
        } else {
            if (!node.has("type")) {
                throw new IllegalArgumentException();
            }
            type = node.get("type").asText();
        }
        return valueOf(type);
    }

}

How do I convert a long to a string in C++?

I don't know what kind of homework this is, but most probably the teacher doesn't want an answer where you just call a "magical" existing function (even though that's the recommended way to do it), but he wants to see if you can implement this by your own.

Back in the days, my teacher used to say something like "I want to see if you can program by yourself, not if you can find it in the system." Well, how wrong he was ;) ..

Anyway, if your teacher is the same, here is the hard way to do it..

std::string LongToString(long value)
{
  std::string output;
  std::string sign;

  if(value < 0)
  {
    sign + "-";
    value = -value;
  }

  while(output.empty() || (value > 0))
  {
    output.push_front(value % 10 + '0')
    value /= 10;
  }

  return sign + output;
}

You could argue that using std::string is not "the hard way", but I guess what counts in the actual agorithm.

MySQL Orderby a number, Nulls last

SELECT * FROM tablename WHERE visible=1 ORDER BY CASE WHEN `position` = 0 THEN 'a' END , position ASC

Operator overloading on class templates

This way works:

class A
{
    struct Wrap
    {
        A& a;
        Wrap(A& aa) aa(a) {}
        operator int() { return a.value; }
        operator std::string() { stringstream ss; ss << a.value; return ss.str(); } 
    }
    Wrap operator*() { return Wrap(*this); }
};

Radio buttons not checked in jQuery

If my firebug profiler work fine (and i know how to use it well), this:

$('#communitymode').attr('checked')

is faster than

$('#communitymode').is('checked')

You can try on this page :)

And then you can use it like

if($('#communitymode').attr('checked')===true) { 
// do something
}