Programs & Examples On #Cross window scripting

How do I run a Java program from the command line on Windows?

Assuming the file is called "CopyFile.java", do the following:

javac CopyFile.java
java -cp . CopyFile

The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).

c# .net change label text

you should convert test type >>>> test.tostring();

change the last line to this :

Label1.Text = "Du har nu lånat filmen:" + test.tostring();

How to execute a shell script in PHP?

Several possibilities:

  • You have safe mode enabled. That way, only exec() is working, and then only on executables in safe_mode_exec_dir
  • exec and shell_exec are disabled in php.ini
  • The path to the executable is wrong. If the script is in the same directory as the php file, try exec(dirname(__FILE__) . '/myscript.sh');

NSCameraUsageDescription in iOS 10.0 runtime crash?

For those who are still getting the error even though you added proper keys into Info.plist:

Make sure you are adding the key into correct Info.plist. Newer version of xCode, apparently has 3 Info.plist.

One is under folder with your app's name which solved problem for me.

Second is under YourappnameTests and third one is under YourappnameUITests.

Hope it helps.

Batch Files - Error Handling

I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output

command 1> file - Write the standard output of command to file

command 2> file - Write the standard error of command to file

How to write and save html file in python?

You can do it using write() :

#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()

Why is using the JavaScript eval function a bad idea?

  1. Improper use of eval opens up your code for injection attacks

  2. Debugging can be more challenging (no line numbers, etc.)

  3. eval'd code executes slower (no opportunity to compile/cache eval'd code)

Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.

Deploy a project using Git push

My take on Christians solution.

git archive --prefix=deploy/  master | tar -x -C $TMPDIR | rsync $TMPDIR/deploy/ --copy-links -av [email protected]:/home/user/my_app && rm -rf $TMPDIR/deploy
  • Archives the master branch into tar
  • Extracts tar archive into deploy dir in system temp folder.
  • rsync changes into server
  • delete deploy dir from temp folder.

Filtering Pandas DataFrames on dates

How about using pyjanitor

It has cool features.

After pip install pyjanitor

import janitor

df_filtered = df.filter_date(your_date_column_name, start_date, end_date)

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

javascript set cookie with expire time

Below are code snippets to create and delete a cookie. The cookie is set for 1 day.

// 1 Day = 24 Hrs = 24*60*60 = 86400.
  1. By using max-age:

    • Creating the cookie:

    document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
    
    • Deleting the cookie:

    document.cookie = "cookieName=; max-age=- (any digit); path=/;";
    
  2. By using expires:

    • Syntax for creating the cookie for one day:

    var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
    document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
    

How to add click event to a iframe with JQuery

This may be interesting for ppl using Primefaces (which uses CLEditor):

document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}

I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)

How to capitalize the first character of each word in a string

public static void main(String[] args) throws IOException {
    String words = "this is a test";

    System.out.println(Arrays.asList(words.split(" ")).stream().reduce("",(a, b)->(a + " " + b.substring(0, 1).toUpperCase() + b.substring(1))));


}

}

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

CSS white space at bottom of page despite having both min-height and height tag

There is a second paragraph in your footer that contains a script. It is this that is causing the issue.

Random string generation with upper case letters and digits

this is a take on Anurag Uniyal 's response and something that i was working on myself.

import random
import string

oneFile = open('?Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase + string.digits + string.punctuation

for userInput in range(int(input('How many 12 digit keys do you want?'))):
    while key_count <= userInput:
        key_count += 1
        number = random.randint(1, 999)
        key = number

        text = str(key) + ": " + str(''.join(random.sample(chars*6, 12)))
        oneFile.write(text + "\n")
oneFile.close()

Why can't Python import Image from PIL?

In Ubuntu OS, I solved it with the followings commands

pip install Pillow
apt-get install python-imaging

And sorry, dont ask me why, it's up to me ;-)

Set session variable in laravel

To add to the above answers, ensure you define your function like this:

public function functionName(Request $request)  {
       //
}

Note the "(Request $request)", now set a session like this:

$request->session()->put('key', 'value');

And retrieve the session in this way:

$data = $request->session()->get('key');

To erase the session try this:

$request->session()->forget('key');  

or

$request->session()->flush();

Accessing a Dictionary.Keys Key through a numeric index

I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.

The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.

WPF loading spinner

With Images

Visual summary of options for spinning icons. Recorded using Screen To Gif.


Font-Awesome-WPF

Documentation on GitHub.

Install via NuGet:

PM> Install-Package FontAwesome.WPF

Looks like this:

XAML:

<fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="4" />

Icons pictured are Spinner, CircleOutlineNotch, Refresh and Cog. There are many others.


Method from @HAdes

XAML copy/paste.

Getting unique values in Excel by using formulas only

Simple formula solution: Using dynamic array functions (UNIQUE function)

Since fall 2018, the subscription versions of Microsoft Excel (Office 365 / Microsoft 365 app) contain so called dynamic array functions (not yet available in Office 2016/2019 nonsubscription versions).

UNIQUE function

One of those functions is the UNIQUE function that will deliver an array of unique values for the selected range.

Example

In the following example, the input values are in range A1:A6. The UNIQUE function is typed into cell C1.

=UNIQUE(A1:A6)

Simple solution to show unique values in Excel using dynamic array functions

As you can see, the UNIQUE function will automatically spill over the necessary range of cells in order to show all unique values. This is indicated by the thin, blue frame around C1:C4.

Good to know

As the UNIQUE function automatically spills over the necessary number of rows, you should leave enough space under the C1. If there is not enough space, you will get a #SPILL error.

Dynamic array functions: Spill not possible because a value in C3 is blocking the spill range

If you want to reference the results of the UNIQUE function, you can just reference the cell containing the UNIQUE function and add a hash # sign.

=C1#

It is also possible to check unique values in several columns. In this case, the UNIQUE function will deliver all rows where the combination of the cells within the row are unique:

Applying the UNIQUE function over several columns

If you wish to show unique columns instead of unique rows, you have to set the [by_col] argument to TRUE (default is FALSE, meaning you will receive unique rows).

You can also show values that appear exactly once by setting the [exactly_once] argument to TRUE:

=UNIQUE(A1:A6;;TRUE)

Show unique values that appear exactly once

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

Another option is to simply use the Application log accessible via the Windows Event Viewer. The .Net error will be recorded to the Application log.

You can see these events here:

Event Viewer (Local) > Windows Logs > Application

How to assign text size in sp value using java code

This is code for the convert PX to SP format. 100% Works

view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);

How do I prevent an Android device from going to sleep programmatically?

One option is to use a wake lock. Example from the docs:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

There's also a table on this page that describes the different kinds of wakelocks.

Be aware that some caution needs to be taken when using wake locks. Ensure that you always release() the lock when you're done with it (or not in the foreground). Otherwise your app can potentially cause some serious battery drain and CPU usage.

The documentation also contains a useful page that describes different approaches to keeping a device awake, and when you might choose to use one. If "prevent device from going to sleep" only refers to the screen (and not keeping the CPU active) then a wake lock is probably more than you need.

You also need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this method.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

When to throw an exception?

One rule of thumb is to use exceptions in the case of something you couldn't normally predict. Examples are database connectivity, missing file on disk, etc. For scenarios that you can predict, ie users attempting to log in with a bad password you should be using functions that return booleans and know how to handle the situation gracefully. You don't want to abruptly end execution by throwing an exception just because someone mistyped their password.

return, return None, and no return at all?

On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set person's mother's name and then the function exits after completing successfully.

def set_mother(person, mother):
    if is_human(person):
        person.mother = mother

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

How to import a .cer certificate into a java keystore?

Here's a script I used to batch import a bunch of crt files in the current directory into the java keystore. Just save this to the same folder as your certificate, and run it like so:

./import_all_certs.sh

import_all_certs.sh

KEYSTORE="$(/usr/libexec/java_home)/jre/lib/security/cacerts";

function running_as_root()
{
  if [ "$EUID" -ne 0 ]
    then echo "NO"
    exit
  fi

  echo "YES"
}

function import_certs_to_java_keystore
{
  for crt in *.crt; do 
    echo prepping $crt 
    keytool -import -file $crt -storepass changeit -noprompt --alias alias__${crt} -keystore $KEYSTORE
    echo 
  done
}

if [ "$(running_as_root)" == "YES" ]
then
  import_certs_to_java_keystore
else
  echo "This script needs to be run as root!"
fi

Get the string value from List<String> through loop for display

Use the For-Each loop which came with Java 1.5, and it work on Types which are iterable.

ArrayList<String> data = new ArrayList<String>();
data.add("Vivek");
data.add("Vadodara");
data.add("Engineer");
data.add("Feelance");

for (String s : data){

 System.out.prinln("Data of "+data.indexOf(s)+" "+s);

 }

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

C# Copy a file to another location with a different name

The easiest method you can use is this:

System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);

This will take care of everything you requested.

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

How to add new line in Markdown presentation?

I was using Markwon for markdown parsing in Android. The following worked great:

"My first line  \nMy second line  \nMy third line  \nMy last line"

...two spaces followed by \n at the end of each line.

jquery background-color change on focus and blur

#FFFFEEE is not a correct color code. Try with #FFFFEE instead.

When to use self over $this?

Short Answer

Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

Full Answer

Here is an example of correct usage of $this and self for non-static and static member variables:

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this->non_static_member . ' '
           . self::$static_member;
    }
}

new X();
?>

Here is an example of incorrect usage of $this and self for non-static and static member variables:

<?php
class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo self::$non_static_member . ' '
           . $this->static_member;
    }
}

new X();
?>

Here is an example of polymorphism with $this for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        $this->foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>

Here is an example of suppressing polymorphic behaviour by using self for member functions:

<?php
class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo();
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar();
?>

The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

From http://www.phpbuilder.com/board/showthread.php?t=10354489:

By http://board.phpbuilder.com/member.php?145249-laserlight

How to get name of the computer in VBA?

Looks like I'm late to the game, but this is a common question...

This is probably the code you want.

Please note that this code is in the public domain, from Usenet, MSDN, and the Excellerando blog.

Public Function ComputerName() As String
'' Returns the host name

'' Uses late-binding: bad for performance and stability, useful for 
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    ComputerName = objNetwork.ComputerName
    
    Set objNetwork = Nothing

End Function

You'll probably need this, too:

Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name

'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork


    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    If WithDomain Then
        UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
    Else
        UserName = objNetwork.UserName
    End If
    
    Set objNetwork = Nothing

End Function

Error: Specified cast is not valid. (SqlManagerUI)

I had a similar error "Specified cast is not valid" restoring from SQL Server 2012 to SQL Server 2008 R2

First I got the MDF and LDF Names:

RESTORE FILELISTONLY 
FROM  DISK = N'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak' 
GO

Second I restored with a MOVE using those names returned:

RESTORE DATABASE Davincis3 
FROM DISK = 'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak'
WITH 
   MOVE 'JQueryExampleDb' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.mdf', 
   MOVE 'JQueryExampleDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.ldf', 
REPLACE
GO  

I have no clue as to the name "JQueryExampleDb", but this worked for me.

Nevertheless, backups (and databases) are not backwards compatible with older versions.

Using IS NULL or IS NOT NULL on join conditions - Theory question

Actually NULL filter is not being ignored. Thing is this is how joining two tables work.

I will try to walk down with the steps performed by database server to make it understand. For example when you execute the query which you said is ignoring the NULL condition. SELECT * FROM shipments s LEFT OUTER JOIN returns r
ON s.id = r.id AND r.id is null WHERE s.day >= CURDATE() - INTERVAL 10 DAY

1st thing happened is all the rows from table SHIPMENTS get selected

on next step database server will start selecting one by one record from 2nd(RETURNS) table.

on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)

note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.

And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.

Why does Vim save files with a ~ extension?

The *.ext~ file is a backup file, containing the file as it was before you edited it.

The *.ext.swp file is the swap file, which serves as a lock file and contains the undo/redo history as well as any other internal info Vim needs. In case of a crash you can re-open your file and Vim will restore its previous state from the swap file (which I find helpful, so I don't switch it off).

To switch off automatic creation of backup files, use (in your vimrc):

set nobackup
set nowritebackup

Where nowritebackup changes the default "save" behavior of Vim, which is:

  1. write buffer to new file
  2. delete the original file
  3. rename the new file

and makes Vim write the buffer to the original file (resulting in the risk of destroying it in case of an I/O error). But you prevent "jumping files" on the Windows desktop with it, which is the primary reason for me to have nowritebackup in place.

Delete rows with foreign key in PostgreSQL

One should not recommend this as a general solution, but for one-off deletion of rows in a database that is not in production or in active use, you may be able to temporarily disable triggers on the tables in question.

In my case, I'm in development mode and have a couple of tables that reference one another via foreign keys. Thus, deleting their contents isn't quite as simple as removing all of the rows from one table before the other. So, for me, it worked fine to delete their contents as follows:

ALTER TABLE table1 DISABLE TRIGGER ALL;
ALTER TABLE table2 DISABLE TRIGGER ALL;
DELETE FROM table1;
DELETE FROM table2;
ALTER TABLE table1 ENABLE TRIGGER ALL;
ALTER TABLE table2 ENABLE TRIGGER ALL;

You should be able to add WHERE clauses as desired, of course with care to avoid undermining the integrity of the database.

There's some good, related discussion at http://www.openscope.net/2012/08/23/subverting-foreign-key-constraints-in-postgres-or-mysql/

How to disable action bar permanently

Go to styles.xml Change this DarkActionBar to NoActionBar

style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

is of a type that is invalid for use as a key column in an index

A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:

create table [misc_info]
( 
    [id] INTEGER PRIMARY KEY IDENTITY NOT NULL, 
    [key] nvarchar(450) UNIQUE NOT NULL, 
    [value] nvarchar(max) NOT NULL
)

i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.

How do you assert that a certain exception is thrown in JUnit 4 tests?

Additionally to what NamShubWriter has said, make sure that:

  • The ExpectedException instance is public (Related Question)
  • The ExpectedException isn't instantiated in say, the @Before method. This post clearly explains all the intricacies of JUnit's order of execution.

Do not do this:

@Rule    
public ExpectedException expectedException;

@Before
public void setup()
{
    expectedException = ExpectedException.none();
}

Finally, this blog post clearly illustrates how to assert that a certain exception is thrown.

Converting a date string to a DateTime object using Joda Time library

You can also use SimpleDateFormat, as in DateTimeFormat

Date startDate = null;
Date endDate = null;
try {
    if (validDateStart!= null) startDate = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH).parse(validDateStart + " " + validDateStartTime);
    if (validDateEnd!= null) endDate = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH).parse(validDateEnd + " " + validDateEndTime);
} catch (ParseException e) {
    e.printStackTrace();
}

Split a python list into other "sublists" i.e smaller lists

Actually I think using plain slices is the best solution in this case:

for i in range(0, len(data), 100):
    chunk = data[i:i + 100]
    ...

If you want to avoid copying the slices, you could use itertools.islice(), but it doesn't seem to be necessary here.

The itertools() documentation also contains the famous "grouper" pattern:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.

Adding machineKey to web.config on web-farm sites

If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.

  1. Open IIS manager.
  2. If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
  3. Double-click the Machine Key icon in ASP.NET settings in the middle pane:
  4. MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
  5. Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.

Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…

"Please provide a valid cache path" error in laravel

May be the storage folder doesn't have the app and framework folder and necessary permission. Inside framework folder it contains cache, sessions, testing and views. use following command this will works.

Use command line to go to your project root: 
cd {your_project_root_directory}
Now copy past this command as it is: 
cd storage && mkdir app && cd app && mkdir public && cd ../ && mkdir framework && cd framework && mkdir cache && mkdir sessions && mkdir testing && mkdir views && cd ../../ && sudo chmod -R 777 storage/

I hope this will solve your use.

how to draw smooth curve through N points using javascript HTML5 canvas?

A bit late, but for the record.

You can achieve smooth lines by using cardinal splines (aka canonical spline) to draw smooth curves that goes through the points.

I made this function for canvas - it's split into three function to increase versatility. The main wrapper function looks like this:

function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {

    showPoints  = showPoints ? showPoints : false;

    ctx.beginPath();

    drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));

    if (showPoints) {
        ctx.stroke();
        ctx.beginPath();
        for(var i=0;i<ptsa.length-1;i+=2) 
                ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);
    }
}

To draw a curve have an array with x, y points in the order: x1,y1, x2,y2, ...xn,yn.

Use it like this:

var myPoints = [10,10, 40,30, 100,10]; //minimum two points
var tension = 1;

drawCurve(ctx, myPoints); //default tension=0.5
drawCurve(ctx, myPoints, tension);

The function above calls two sub-functions, one to calculate the smoothed points. This returns an array with new points - this is the core function which calculates the smoothed points:

function getCurvePoints(pts, tension, isClosed, numOfSegments) {

    // use input value if provided, or use a default value   
    tension = (typeof tension != 'undefined') ? tension : 0.5;
    isClosed = isClosed ? isClosed : false;
    numOfSegments = numOfSegments ? numOfSegments : 16;

    var _pts = [], res = [],    // clone array
        x, y,           // our x,y coords
        t1x, t2x, t1y, t2y, // tension vectors
        c1, c2, c3, c4,     // cardinal points
        st, t, i;       // steps based on num. of segments

    // clone array so we don't change the original
    //
    _pts = pts.slice(0);

    // The algorithm require a previous and next point to the actual point array.
    // Check if we will draw closed or open curve.
    // If closed, copy end points to beginning and first points to end
    // If open, duplicate first points to befinning, end points to end
    if (isClosed) {
        _pts.unshift(pts[pts.length - 1]);
        _pts.unshift(pts[pts.length - 2]);
        _pts.unshift(pts[pts.length - 1]);
        _pts.unshift(pts[pts.length - 2]);
        _pts.push(pts[0]);
        _pts.push(pts[1]);
    }
    else {
        _pts.unshift(pts[1]);   //copy 1. point and insert at beginning
        _pts.unshift(pts[0]);
        _pts.push(pts[pts.length - 2]); //copy last point and append
        _pts.push(pts[pts.length - 1]);
    }

    // ok, lets start..

    // 1. loop goes through point array
    // 2. loop goes through each segment between the 2 pts + 1e point before and after
    for (i=2; i < (_pts.length - 4); i+=2) {
        for (t=0; t <= numOfSegments; t++) {

            // calc tension vectors
            t1x = (_pts[i+2] - _pts[i-2]) * tension;
            t2x = (_pts[i+4] - _pts[i]) * tension;

            t1y = (_pts[i+3] - _pts[i-1]) * tension;
            t2y = (_pts[i+5] - _pts[i+1]) * tension;

            // calc step
            st = t / numOfSegments;

            // calc cardinals
            c1 =   2 * Math.pow(st, 3)  - 3 * Math.pow(st, 2) + 1; 
            c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); 
            c3 =       Math.pow(st, 3)  - 2 * Math.pow(st, 2) + st; 
            c4 =       Math.pow(st, 3)  -     Math.pow(st, 2);

            // calc x and y cords with common control vectors
            x = c1 * _pts[i]    + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;
            y = c1 * _pts[i+1]  + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;

            //store points in array
            res.push(x);
            res.push(y);

        }
    }

    return res;
}

And to actually draw the points as a smoothed curve (or any other segmented lines as long as you have an x,y array):

function drawLines(ctx, pts) {
    ctx.moveTo(pts[0], pts[1]);
    for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);
}

_x000D_
_x000D_
var ctx = document.getElementById("c").getContext("2d");_x000D_
_x000D_
_x000D_
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {_x000D_
_x000D_
  ctx.beginPath();_x000D_
_x000D_
  drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));_x000D_
  _x000D_
  if (showPoints) {_x000D_
    ctx.beginPath();_x000D_
    for(var i=0;i<ptsa.length-1;i+=2) _x000D_
      ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);_x000D_
  }_x000D_
_x000D_
  ctx.stroke();_x000D_
}_x000D_
_x000D_
_x000D_
var myPoints = [10,10, 40,30, 100,10, 200, 100, 200, 50, 250, 120]; //minimum two points_x000D_
var tension = 1;_x000D_
_x000D_
drawCurve(ctx, myPoints); //default tension=0.5_x000D_
drawCurve(ctx, myPoints, tension);_x000D_
_x000D_
_x000D_
function getCurvePoints(pts, tension, isClosed, numOfSegments) {_x000D_
_x000D_
  // use input value if provided, or use a default value  _x000D_
  tension = (typeof tension != 'undefined') ? tension : 0.5;_x000D_
  isClosed = isClosed ? isClosed : false;_x000D_
  numOfSegments = numOfSegments ? numOfSegments : 16;_x000D_
_x000D_
  var _pts = [], res = [], // clone array_x000D_
      x, y,   // our x,y coords_x000D_
      t1x, t2x, t1y, t2y, // tension vectors_x000D_
      c1, c2, c3, c4,  // cardinal points_x000D_
      st, t, i;  // steps based on num. of segments_x000D_
_x000D_
  // clone array so we don't change the original_x000D_
  //_x000D_
  _pts = pts.slice(0);_x000D_
_x000D_
  // The algorithm require a previous and next point to the actual point array._x000D_
  // Check if we will draw closed or open curve._x000D_
  // If closed, copy end points to beginning and first points to end_x000D_
  // If open, duplicate first points to befinning, end points to end_x000D_
  if (isClosed) {_x000D_
    _pts.unshift(pts[pts.length - 1]);_x000D_
    _pts.unshift(pts[pts.length - 2]);_x000D_
    _pts.unshift(pts[pts.length - 1]);_x000D_
    _pts.unshift(pts[pts.length - 2]);_x000D_
    _pts.push(pts[0]);_x000D_
    _pts.push(pts[1]);_x000D_
  }_x000D_
  else {_x000D_
    _pts.unshift(pts[1]); //copy 1. point and insert at beginning_x000D_
    _pts.unshift(pts[0]);_x000D_
    _pts.push(pts[pts.length - 2]); //copy last point and append_x000D_
    _pts.push(pts[pts.length - 1]);_x000D_
  }_x000D_
_x000D_
  // ok, lets start.._x000D_
_x000D_
  // 1. loop goes through point array_x000D_
  // 2. loop goes through each segment between the 2 pts + 1e point before and after_x000D_
  for (i=2; i < (_pts.length - 4); i+=2) {_x000D_
    for (t=0; t <= numOfSegments; t++) {_x000D_
_x000D_
      // calc tension vectors_x000D_
      t1x = (_pts[i+2] - _pts[i-2]) * tension;_x000D_
      t2x = (_pts[i+4] - _pts[i]) * tension;_x000D_
_x000D_
      t1y = (_pts[i+3] - _pts[i-1]) * tension;_x000D_
      t2y = (_pts[i+5] - _pts[i+1]) * tension;_x000D_
_x000D_
      // calc step_x000D_
      st = t / numOfSegments;_x000D_
_x000D_
      // calc cardinals_x000D_
      c1 =   2 * Math.pow(st, 3)  - 3 * Math.pow(st, 2) + 1; _x000D_
      c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); _x000D_
      c3 =     Math.pow(st, 3) - 2 * Math.pow(st, 2) + st; _x000D_
      c4 =     Math.pow(st, 3) -    Math.pow(st, 2);_x000D_
_x000D_
      // calc x and y cords with common control vectors_x000D_
      x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;_x000D_
      y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;_x000D_
_x000D_
      //store points in array_x000D_
      res.push(x);_x000D_
      res.push(y);_x000D_
_x000D_
    }_x000D_
  }_x000D_
_x000D_
  return res;_x000D_
}_x000D_
_x000D_
function drawLines(ctx, pts) {_x000D_
  ctx.moveTo(pts[0], pts[1]);_x000D_
  for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);_x000D_
}
_x000D_
canvas { border: 1px solid red; }
_x000D_
<canvas id="c"><canvas>
_x000D_
_x000D_
_x000D_

This results in this:

Example pix

You can easily extend the canvas so you can call it like this instead:

ctx.drawCurve(myPoints);

Add the following to the javascript:

if (CanvasRenderingContext2D != 'undefined') {
    CanvasRenderingContext2D.prototype.drawCurve = 
        function(pts, tension, isClosed, numOfSegments, showPoints) {
       drawCurve(this, pts, tension, isClosed, numOfSegments, showPoints)}
}

You can find a more optimized version of this on NPM (npm i cardinal-spline-js) or on GitLab.

How do I search for names with apostrophe in SQL Server?

SELECT *   FROM Header  WHERE userID LIKE '%' + CHAR(39) + '%' 

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

Flutter: how to make a TextField with HintText but no Underline?

new flutter sdk since after integration of web and desktop support you need to specify individually like this

TextFormField(
    cursorColor: Colors.black,
    keyboardType: inputType,
    decoration: new InputDecoration(
        border: InputBorder.none,
        focusedBorder: InputBorder.none,
        enabledBorder: InputBorder.none,
        errorBorder: InputBorder.none,
        disabledBorder: InputBorder.none,
        contentPadding:
            EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
        hintText: "Hint here"),
  )

Equivalent of Math.Min & Math.Max for Dates?

There's no built in method to do that. You can use the expression:

(date1 > date2 ? date1 : date2)

to find the maximum of the two.

You can write a generic method to calculate Min or Max for any type (provided that Comparer<T>.Default is set appropriately):

public static T Max<T>(T first, T second) {
    if (Comparer<T>.Default.Compare(first, second) > 0)
        return first;
    return second;
}

You can use LINQ too:

new[]{date1, date2, date3}.Max()

Set background color of WPF Textbox in C# code

Have you taken a look at Color.FromRgb?

php stdClass to array

use this function to get a standard array back of the type you are after...

return get_object_vars($booking);

Error: stray '\240' in program

As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:

iconv -f utf-8 -t ascii//translit input.c > output.c

Can an abstract class have a constructor?

Since an abstract class can have variables of all access modifiers, they have to be initialized to default values, so constructor is necessary. As you instantiate the child class, a constructor of an abstract class is invoked and variables are initialized.

On the contrary, an interface does contain only constant variables means they are already initialized. So interface doesn't need a constructor.

jQuery - Detecting if a file has been selected in the file input

You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       $(".filename").html(fileName);
     });
  });
</script>

You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.

Correct way to import lodash

I just put them in their own file and export it for node and webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}

How to make a div with a circular shape?

Demo

css

div {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: red;
}

html

<div></div>

How do you clear the console screen in C?

This should work. Then just call cls(); whenever you want to clear the screen.

(using the method suggested before.)

#include <stdio.h>
void cls()
{
    int x;
    for ( x = 0; x < 10; x++ ) 
    {
        printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    }
}

In SQL, how can you "group by" in ranges?

In postgres (where || is the string concatenation operator):

select (score/10)*10 || '-' || (score/10)*10+9 as scorerange, count(*)
from scores
group by score/10
order by 1

gives:

 scorerange | count 
------------+-------
 0-9        |    11
 10-19      |    14
 20-29      |     3
 30-39      |     2

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.

Build project into a JAR automatically in Eclipse

You want a .jardesc file. They do not kick off automatically, but it's within 2 clicks.

  1. Right click on your project
  2. Choose Export > Java > JAR file
  3. Choose included files and name output JAR, then click Next
  4. Check "Save the description of this JAR in the workspace" and choose a name for the new .jardesc file

Now, all you have to do is right click on your .jardesc file and choose Create JAR and it will export it in the same spot.

How do I exit from a function?

I'd suggest trying to avoid using return/exit if you don't have to. Some people will devoutly tell you to NEVER do it, but sometimes it just makes sense. However if you can structure you checks so that you don't have to enter into them, I think it makes it easier for people to follow your code later.

Filter data.frame rows by a logical condition

You could use the dplyr package:

library(dplyr)
filter(expr, cell_type == "hesc")
filter(expr, cell_type == "hesc" | cell_type == "bj fibroblast")

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

HTML Input Box - Disable

You can Use both disabled or readonly attribute of input . Using disable attribute will omit that value at form submit, so if you want that values at submit event make them readonly instead of disable.

<input type="text" readonly> 

or

 <input type="text" disabled>

How to kill/stop a long SQL query immediately?

I Have Been suffering from same thing since long time. It specially happens when you're connected to remote server(Which might be slow), or you have poor network connection. I doubt if Microsoft knows what the right answer is.

But since I've tried to find the solution. Only 1 layman approach worked

  • Click the close button over the tab of query which you are being suffered of. After a while (If Microsoft is not harsh on you !!!) you might get a window asking this

"The query is currently executing. Do you want to cancel the query?"

  • Click on "Yes"

  • After a while it will ask to whether you want to save this query or not?

  • Click on "Cancel"

And post that, may be you're studio is stable again to execute your query.

What it does in background is disconnecting your query window with the connection. So for running the query again, it will take time for connecting the remote server again. But trust me this trade-off is far better than the suffering of seeing that timer which runs for eternity.

PS: This works for me, Kudos if works for you too. !!!

How to get a float result by dividing two integer values using T-SQL?

Looks like this trick works in SQL Server and is shorter (based in previous answers)

SELECT 1.0*MyInt1/MyInt2

Or:

SELECT (1.0*MyInt1)/MyInt2

Add empty columns to a dataframe with specified names from a vector

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
    df[,i] <- NA

Or more simply:

df[,namevector] <- NA

jquery click event not firing?

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

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

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

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

Print directly from browser without print popup window

I couldn't find solution for other browsers. When I posted this question, IE was on the higher priority and gladly I found one for it. If you have a solution for other browsers (firefox, safari, opera) please do share here. Thanks.

VBSCRIPT is much more convenient than creating an ActiveX on VB6 or C#/VB.NET:

<script language='VBScript'>
Sub Print()
       OLECMDID_PRINT = 6
       OLECMDEXECOPT_DONTPROMPTUSER = 2
       OLECMDEXECOPT_PROMPTUSER = 1
       call WB.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER,1)
End Sub
document.write "<object ID='WB' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'></object>"
</script>

Now, calling:

<a href="javascript:window.print();">Print</a>

will send print without popup print window.

Fastest way to remove first char in a String

The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".

The first option needs a bit more work to understand than the third - I would view the Substring option as the most common and readable.

(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data itself.)

I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring to probably be the fastest here, simply because Substring always ends up creating a string from a single chunk of the original input, whereas Remove has to at least potentially glue together a start chunk and an end chunk.

node.js + mysql connection pooling

You will find this wrapper usefull :)

var pool = mysql.createPool(config.db);

exports.connection = {
    query: function () {
        var queryArgs = Array.prototype.slice.call(arguments),
            events = [],
            eventNameIndex = {};

        pool.getConnection(function (err, conn) {
            if (err) {
                if (eventNameIndex.error) {
                    eventNameIndex.error();
                }
            }
            if (conn) { 
                var q = conn.query.apply(conn, queryArgs);
                q.on('end', function () {
                    conn.release();
                });

                events.forEach(function (args) {
                    q.on.apply(q, args);
                });
            }
        });

        return {
            on: function (eventName, callback) {
                events.push(Array.prototype.slice.call(arguments));
                eventNameIndex[eventName] = callback;
                return this;
            }
        };
    }
};

Require it, use it like this:

db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
          .on('result', function (row) {
            setData(row);
          })
          .on('error', function (err) {
            callback({error: true, err: err});
          });

What is the difference between field, variable, attribute, and property in Java POJOs?

Dietel and Dietel have a nice way of explaining fields vs variables.

“Together a class’s static variables and instance variables are known as its fields.” (Section 6.3)

“Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.” (Section 6.4)

So a class's fields are its static or instance variables - i.e. declared with class scope.

Reference - Dietel P., Dietel, H. - Java™ How To Program (Early Objects), Tenth Edition (2014)

How to wrap async function calls into a sync function in Node.js or Javascript?

I can't find a scenario that cannot be solved using node-fibers. The example you provided using node-fibers behaves as expected. The key is to run all the relevant code inside a fiber, so you don't have to start a new fiber in random positions.

Lets see an example: Say you use some framework, which is the entry point of your application (you cannot modify this framework). This framework loads nodejs modules as plugins, and calls some methods on the plugins. Lets say this framework only accepts synchronous functions, and does not use fibers by itself.

There is a library that you want to use in one of your plugins, but this library is async, and you don't want to modify it either.

The main thread cannot be yielded when no fiber is running, but you still can create plugins using fibers! Just create a wrapper entry that starts the whole framework inside a fiber, so you can yield the execution from the plugins.

Downside: If the framework uses setTimeout or Promises internally, then it will escape the fiber context. This can be worked around by mocking setTimeout, Promise.then, and all event handlers.

So this is how you can yield a fiber until a Promise is resolved. This code takes an async (Promise returning) function and resumes the fiber when the promise is resolved:

framework-entry.js

console.log(require("./my-plugin").run());

async-lib.js

exports.getValueAsync = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Async Value");
    }, 100);
  });
};

my-plugin.js

const Fiber = require("fibers");

function fiberWaitFor(promiseOrValue) {
  var fiber = Fiber.current, error, value;
  Promise.resolve(promiseOrValue).then(v => {
    error = false;
    value = v;
    fiber.run();
  }, e => {
    error = true;
    value = e;
    fiber.run();
  });
  Fiber.yield();
  if (error) {
    throw value;
  } else {
    return value;
  }
}

const asyncLib = require("./async-lib");

exports.run = () => {
  return fiberWaitFor(asyncLib.getValueAsync());
};

my-entry.js

require("fibers")(() => {
  require("./framework-entry");
}).run();

When you run node framework-entry.js it will throw an error: Error: yield() called with no fiber running. If you run node my-entry.js it works as expected.

Edit seaborn legend

Took me a while to read through the above. This was the answer for me:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

How to switch a user per task or set of tasks?

In Ansible >1.4 you can actually specify a remote user at the task level which should allow you to login as that user and execute that command without resorting to sudo. If you can't login as that user then the sudo_user solution will work too.

---
- hosts: webservers
  remote_user: root
  tasks:
    - name: test connection
      ping:
      remote_user: yourname

See http://docs.ansible.com/playbooks_intro.html#hosts-and-users

String to HtmlDocument

You could try with OpenNew and then with Write but that's a bit strange use of that class. More info on MSDN.

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My issue was that I was creating objects that I wanted to be stored in a NSMutableDictionary but I never initialized the dictionary. Therefore the objects were getting deleted by garbage collection and breaking later. Check that you have at least one strong reference to the objects youre interacting with.

'No JUnit tests found' in Eclipse

I think you have created your test classes outside the src folder. You can solve above problem by two way:

  1. Add your package name in java build path->source

  2. Move your package/class in src folder

I have the same problem and solved in this way both solutions working fine.

Why do we need the "finally" clause in Python?

finally is for defining "clean up actions". The finally clause is executed in any event before leaving the try statement, whether an exception (even if you do not handle it) has occurred or not.

I second @Byers's example.

What is a semaphore?

Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.

It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.

Here is a very pedagogic example in C# :-)

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TheNightclub
{
    public class Program
    {
        public static Semaphore Bouncer { get; set; }

        public static void Main(string[] args)
        {
            // Create the semaphore with 3 slots, where 3 are available.
            Bouncer = new Semaphore(3, 3);

            // Open the nightclub.
            OpenNightclub();
        }

        public static void OpenNightclub()
        {
            for (int i = 1; i <= 50; i++)
            {
                // Let each guest enter on an own thread.
                Thread thread = new Thread(new ParameterizedThreadStart(Guest));
                thread.Start(i);
            }
        }

        public static void Guest(object args)
        {
            // Wait to enter the nightclub (a semaphore to be released).
            Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
            Bouncer.WaitOne();          

            // Do some dancing.
            Console.WriteLine("Guest {0} is doing some dancing.", args);
            Thread.Sleep(500);

            // Let one guest out (release one semaphore).
            Console.WriteLine("Guest {0} is leaving the nightclub.", args);
            Bouncer.Release(1);
        }
    }
}

Java: parse int value from a char

That's probably the best from the performance point of view, but it's rough:

String element = "el5";
String s;
int x = element.charAt(2)-'0';

It works if you assume your character is a digit, and only in languages always using Unicode, like Java...

RegEx to exclude a specific string constant

In .NET you can use grouping to your advantage like this:

http://regexhero.net/tester/?id=65b32601-2326-4ece-912b-6dcefd883f31

You'll notice that:

(ABC)|(.)

Will grab everything except ABC in the 2nd group. Parenthesis surround each group. So (ABC) is group 1 and (.) is group 2.

So you just grab the 2nd group like this in a replace:

$2

Or in .NET look at the Groups collection inside the Regex class for a little more control.

You should be able to do something similar in most other regex implementations as well.

UPDATE: I found a much faster way to do this here: http://regexhero.net/tester/?id=997ce4a2-878c-41f2-9d28-34e0c5080e03

It still uses grouping (I can't find a way that doesn't use grouping). But this method is over 10X faster than the first.

Converting NSData to NSString in Objective c

Objective C includes a built-in way to detect a the encoding of a string embedded in NSData.

NSData* data = // Assign your NSData object...

NSString* string;
NSStringEncoding encoding = [NSString stringEncodingForData:data encodingOptions:nil convertedString:&string usedLossyConversion:nil];

CodeIgniter - accessing $config variable in view

If you are trying to accessing config variable into controller than use

$this->config->item('{variable name which you define into config}');

If you are trying to accessing the config variable into outside the controller(helper/hooks) then use

$mms = get_instance();  
$mms->config->item('{variable which you define into config}');

How do I output text without a newline in PowerShell?

It may not be terribly elegant, but it does exactly what OP requested. Note that the ISE messes with StdOut, so there will be no output. In order to see this script work it can't be run within the ISE.

$stdout=[System.Console]::OpenStandardOutput()
$strOutput="Enabling feature XYZ... "
$stdout.Write(([System.Text.Encoding]::ASCII.GetBytes($strOutput)),0,$strOutput.Length)
Enable-SPFeature...
$strOutput="Done"
$stdout.Write(([System.Text.Encoding]::ASCII.GetBytes($strOutput)),0,$strOutput.Length)
$stdout.Close()

How do you find all subclasses of a given class in Java?

Add them to a static map inside (this.getClass().getName()) the parent classes constructor (or create a default one) but this will get updated in runtime. If lazy initialization is an option you can try this approach.

How can I remove text within parentheses with a regex?

s/\([^)]*\)//

So in Python, you'd do:

re.sub(r'\([^)]*\)', '', filename)

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.

from pandas import DataFrame, concat

a = DataFrame([{'a':1,      'c':2,'d':3      }])
b = DataFrame([{'a':4,'b':5,      'd':6,'e':7}])

>>> concat([a,b],sort=False)
   a    c  d    b    e
0  1  2.0  3  NaN  NaN
0  4  NaN  6  5.0  7.0

>>> concat([a,b],sort=True)
   a    b    c  d    e
0  1  NaN  2.0  3  NaN
0  4  5.0  NaN  6  7.0

How to get length of a string using strlen function

For C++ strings, there's no reason to use strlen. Just use string::length:

std::cout << str.length() << std::endl;

You should strongly prefer this to strlen(str.c_str()) for the following reasons:

  1. Clarity: The length() (or size()) member functions unambiguously give back the length of the string. While it's possible to figure out what strlen(str.c_str()) does, it forces the reader to pause for a bit.

  2. Efficiency: length() and size() run in time O(1), while strlen(str.c_str()) will take Θ(n) time to find the end of the string.

  3. Style: It's good to prefer the C++ versions of functions to the C versions unless there's a specific reason to do so otherwise. This is why, for example, it's usually considered better to use std::sort over qsort or std::lower_bound over bsearch, unless some other factors come into play that would affect performance.

The only reason I could think of where strlen would be useful is if you had a C++-style string that had embedded null characters and you wanted to determine how many characters appeared before the first of them. (That's one way in which strlen differs from string::length; the former stops at a null terminator, and the latter counts all the characters in the string). But if that's the case, just use string::find:

size_t index = str.find(0);
if (index == str::npos) index = str.length();
std::cout << index << std::endl;

Hope this helps!

Android Studio - No JVM Installation found

if your "enviornment variables" set well, than try to update Start > All Programs > Android Studio > Android Studio

do right click, click Properties and set android studio sdk path

in

shortcut > Target

How to use custom font in a project written in Android Studio

I think instead of downloading .ttf file we can use Google fonts. It's very easy to implements. only you have to follow these steps. step 1) Open layout.xml of your project and the select font family of text view in attributes (for reference screen shot is attached) enter image description here

step 2) The in font family select More fonts.. option if your font is not there. then you will see a new window will open, there you can type your required font & select the desired font from that list i.e) Regular, Bold, Italic etc.. as shown in below image. enter image description here

step 3) Then you will observe a font folder will be auto generated in /res folder having your selected fonts xml file.

enter image description here

Then you can directly use this font family in xml as

      android:fontFamily="@font/josefin_sans_bold"

or pro grammatically you can achieve this by using

  Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
  fontText.setTypeface(typeface);

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

I had a similar problem:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"sh\": executable file not found in $PATH": unknown.

In my case, I know the image works in other places, then was a corrupted local image. I solved the issue removing the image (docker rmi <imagename>) and pulling it again(docker pull <imagename>).

I did a docker system prune too, but I think it's not mandatory.

How to include multiple js files using jQuery $.getScript() method

Use yepnope.js or Modernizr (which includes yepnope.js as Modernizr.load).

UPDATE

Just to follow up, here's a good equivalent of what you currently have using yepnope, showing dependencies on multiple scripts:

yepnope({
  load: ['script1.js', 'script2.js', 'script3.js'],
  complete: function () {
      // all the scripts have loaded, do whatever you want here
  }
});

failed to open stream: No such file or directory in

include() needs a full file path, relative to the file system's root directory.

This should work:

 include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");

How do I set the version information for an existing .exe, .dll?

I'm doing it with no additional tool. I have just added the following files to my Win32 app project.

One header file which defines some constants than we can reuse on our resource file and even on the program code. We only need to maintain one file. Thanks to the Qt team that showed me how to do it on a Qt project, it now also works on my Win32 app.

----[version.h]----

#ifndef VERSION_H
#define VERSION_H

#define VER_FILEVERSION             0,3,0,0
#define VER_FILEVERSION_STR         "0.3.0.0\0"

#define VER_PRODUCTVERSION          0,3,0,0
#define VER_PRODUCTVERSION_STR      "0.3.0.0\0"

#define VER_COMPANYNAME_STR         "IPanera"
#define VER_FILEDESCRIPTION_STR     "Localiza archivos duplicados"
#define VER_INTERNALNAME_STR        "MyProject"
#define VER_LEGALCOPYRIGHT_STR      "Copyright 2016 [email protected]"
#define VER_LEGALTRADEMARKS1_STR    "All Rights Reserved"
#define VER_LEGALTRADEMARKS2_STR    VER_LEGALTRADEMARKS1_STR
#define VER_ORIGINALFILENAME_STR    "MyProject.exe"
#define VER_PRODUCTNAME_STR         "My project"

#define VER_COMPANYDOMAIN_STR       "www.myurl.com"

#endif // VERSION_H

----[MyProjectVersion.rc]----

#include <windows.h>
#include "version.h"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",        VER_COMPANYNAME_STR
            VALUE "FileDescription",    VER_FILEDESCRIPTION_STR
            VALUE "FileVersion",        VER_FILEVERSION_STR
            VALUE "InternalName",       VER_INTERNALNAME_STR
            VALUE "LegalCopyright",     VER_LEGALCOPYRIGHT_STR
            VALUE "LegalTrademarks1",   VER_LEGALTRADEMARKS1_STR
            VALUE "LegalTrademarks2",   VER_LEGALTRADEMARKS2_STR
            VALUE "OriginalFilename",   VER_ORIGINALFILENAME_STR
            VALUE "ProductName",        VER_PRODUCTNAME_STR
            VALUE "ProductVersion",     VER_PRODUCTVERSION_STR
        END
    END

    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1252
    END
END

ASP.NET MVC Conditional validation

I had the same problem yesterday but I did it in a very clean way which works for both client side and server side validation.

Condition: Based on the value of other property in the model, you want to make another property required. Here is the code

public class RequiredIfAttribute : RequiredAttribute
{
    private String PropertyName { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue)
    {
        PropertyName = propertyName;
        DesiredValue = desiredvalue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString())
        {
            ValidationResult result = base.IsValid(value, context);
            return result;
        }
        return ValidationResult.Success;
    }
}

Here PropertyName is the property on which you want to make your condition DesiredValue is the particular value of the PropertyName (property) for which your other property has to be validated for required

Say you have the following

public class User
{
    public UserType UserType { get; set; }

    [RequiredIf("UserType", UserType.Admin, ErrorMessageResourceName = "PasswordRequired", ErrorMessageResourceType = typeof(ResourceString))]
    public string Password
    {
        get;
        set;
    }
}

At last but not the least , register adapter for your attribute so that it can do client side validation (I put it in global.asax, Application_Start)

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredAttributeAdapter));

How do I use Apache tomcat 7 built in Host Manager gui?

Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in

/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)

instead of the apacahe installation directory.

open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.

    <user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>

restart the server . That's all

The 'json' native gem requires installed build tools

My solution is simplier and checked on Ruby 2.0. It also enable download Json. (run CMD.exe as administrator)

    C:\RubyDev>devkitvars.bat
    Adding the DevKit to PATH...

And then write again gem command.

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

run postgres -D /usr/local/var/postgres and you should see something like:

 FATAL:  lock file "postmaster.pid" already exists
 HINT:   Is another postmaster (PID 379) running in data directory "/usr/local/var/postgres"?

Then run kill -9 PID in HINT

And you should be good to go.

Reading json files in C++

Example (with complete source code) to read a json configuration file:

https://github.com/sksodhi/CodeNuggets/tree/master/json/config_read

 > pwd
/root/CodeNuggets/json/config_read
 > ls
Makefile  README.md  ReadJsonCfg.cpp  cfg.json
 > cat cfg.json 
{
   "Note" : "This is a cofiguration file",
   "Config" : { 
       "server-ip"     : "10.10.10.20",
       "server-port"   : "5555",
       "buffer-length" : 5000
   }   
}
 > cat ReadJsonCfg.cpp 
#include <iostream>
#include <json/value.h>
#include <jsoncpp/json/json.h>
#include <fstream>

void 
displayCfg(const Json::Value &cfg_root);

int
main()
{
    Json::Reader reader;
    Json::Value cfg_root;
    std::ifstream cfgfile("cfg.json");
    cfgfile >> cfg_root;

    std::cout << "______ cfg_root : start ______" << std::endl;
    std::cout << cfg_root << std::endl;
    std::cout << "______ cfg_root : end ________" << std::endl;

    displayCfg(cfg_root);
}       

void 
displayCfg(const Json::Value &cfg_root)
{
    std::string serverIP = cfg_root["Config"]["server-ip"].asString();
    std::string serverPort = cfg_root["Config"]["server-port"].asString();
    unsigned int bufferLen = cfg_root["Config"]["buffer-length"].asUInt();

    std::cout << "______ Configuration ______" << std::endl;
    std::cout << "server-ip     :" << serverIP << std::endl;
    std::cout << "server-port   :" << serverPort << std::endl;
    std::cout << "buffer-length :" << bufferLen<< std::endl;
}
 > cat Makefile 
CXX = g++
PROG = readjsoncfg

CXXFLAGS += -g -O0 -std=c++11

CPPFLAGS += \
        -I. \
        -I/usr/include/jsoncpp

LDLIBS = \
                 -ljsoncpp

LDFLAGS += -L/usr/local/lib $(LDLIBS)

all: $(PROG)
        @echo $(PROG) compilation success!

SRCS = \
        ReadJsonCfg.cpp
OBJS=$(subst .cc,.o, $(subst .cpp,.o, $(SRCS)))

$(PROG): $(OBJS)
        $(CXX) $^ $(LDFLAGS) -o $@

clean:
        rm -f $(OBJS) $(PROG) ./.depend

depend: .depend

.depend: $(SRCS)
        rm -f ./.depend
        $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM $^ >  ./.depend;

include .depend
 > make
Makefile:43: .depend: No such file or directory
rm -f ./.depend
g++ -g -O0 -std=c++11 -I. -I/usr/include/jsoncpp -MM ReadJsonCfg.cpp >  ./.depend;
g++ -g -O0 -std=c++11 -I. -I/usr/include/jsoncpp  -c -o ReadJsonCfg.o ReadJsonCfg.cpp
g++ ReadJsonCfg.o -L/usr/local/lib -ljsoncpp -o readjsoncfg
readjsoncfg compilation success!
 > ./readjsoncfg 
______ cfg_root : start ______
{
        "Config" : 
        {
                "buffer-length" : 5000,
                "server-ip" : "10.10.10.20",
                "server-port" : "5555"
        },
        "Note" : "This is a cofiguration file"
}
______ cfg_root : end ________
______ Configuration ______
server-ip     :10.10.10.20
server-port   :5555
buffer-length :5000
 > 

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

jquery find class and get the value

Class selectors are prefixed with a dot. Your .find() is missing that so jQuery thinks you're looking for <myClass> elements.

var myVar = $("#start").find('.myClass').val();

display Java.util.Date in a specific format

You can use simple date format in Java using the code below

SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);

Convert DataTable to CSV stream

Update 1

I have modified it to use StreamWriter instead, add an option to check if you need column headers in your output.

public static bool DataTableToCSV(DataTable dtSource, StreamWriter writer, bool includeHeader)
{
    if (dtSource == null || writer == null) return false;

    if (includeHeader)
    {
        string[] columnNames = dtSource.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray<string>();
        writer.WriteLine(String.Join(",", columnNames));
        writer.Flush();
    }

    foreach (DataRow row in dtSource.Rows)
    {
        string[] fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray<string>();
        writer.WriteLine(String.Join(",", fields));
        writer.Flush();
    }

    return true;
}

As you can see, you can choose the output by initial StreamWriter, if you use StreamWriter(Stream BaseStream), you can write csv into MemeryStream, FileStream, etc.

Origin

I have an easy datatable to csv function, it serves me well:

    public static void DataTableToCsv(DataTable dt, string csvFile)
    {
        StringBuilder sb = new StringBuilder();

        var columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in dt.Rows)
        {
            var fields = row.ItemArray.Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"").ToArray();
            sb.AppendLine(string.Join(",", fields));
        }

        File.WriteAllText(csvFile, sb.ToString(), Encoding.Default);
    }

Find the index of a dict within a list, by matching the dict's value

def search(itemID,list):
     return[i for i in list if i.itemID==itemID]

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How to redirect user's browser URL to a different page in Nodejs?

You can use res.render() or res.redirect() method to redirect to another page using node.js express

Eg:

var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});

//This reponds a post request for the login page
app.post('/login', function (req, res) {
    console.log("Got a POST request for the login");
    var data = {
        "email": req.body.email,
        "password": req.body.password
    };

    console.log(data);

    //Data insertion code
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/";

    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("college");
        var query = { email: data.email };
        dbo.collection("user").find(query).toArray(function(err, result) {
            if (err) throw err;
            console.log(result);
            if(result[0].password == data.password)


 res.redirect('dashboard.html');
            else


 res.redirect('login-error.html');
            db.close();
        });
    });

});


// This responds a POST request for the add user
app.post('/insert', function (req, res) {
    console.log("Got a POST request for the add user");

    var data = {
        "first_name" : req.body.firstName,
        "second_name" : req.body.secondName,
        "organization" : req.body.organization,
        "email": req.body.email,
        "mobile" : req.body.mobile,
    };

    console.log(data);

    **res.render('success.html',{email:data.email,password:data.password});**

});


//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('service-worker.js', {scope: '/'})
        .then(function (registration) {
            console.log(registration);
        })
        .catch(function (e) {
            console.error(e);
        })
} else {
    console.log('Service Worker is not supported in this browser.');
}


// TODO add service worker code here
if ('serviceWorker' in navigator) {
    navigator.serviceWorker
        .register('service-worker.js')
        .then(function() { console.log('Service Worker Registered'); });
}

var server = app.listen(63342, function () {

    var host = server.address().host;
    var port = server.address().port;

    console.log("Example app listening at http://localhost:%s", port)
});

Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js

Spring JPA @Query with LIKE

Using Query creation from method names, check table 4 where they explain some keywords.

  1. Using Like: select ... like :username

     List<User> findByUsernameLike(String username);
    
  2. StartingWith: select ... like :username%

     List<User> findByUsernameStartingWith(String username);
    
  3. EndingWith: select ... like %:username

     List<User> findByUsernameEndingWith(String username);
    
  4. Containing: select ... like %:username%

     List<User> findByUsernameContaining(String username);
    

Notice that the answer that you are looking for is number 4. You don't have to use @Query

Flask-SQLAlchemy how to delete all rows in a single table

Flask-Sqlalchemy

Delete All Records

#for all records
db.session.query(Model).delete()
db.session.commit()

Deleted Single Row

here DB is the object Flask-SQLAlchemy class. It will delete all records from it and if you want to delete specific records then try filter clause in the query. ex.

#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()

Delete Single Record by Object

record_obj = db.session.query(Model).filter(Model.id==123).first()
db.session.delete(record_obj)
db.session.commit()

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I had this problem with only with redirectMode="ResponseRewrite" (redirectMode="ResponseRedirect" worked fine) and none of the above solutions helped my resolve the issue. However, once I changed the server's application pool's "Managed Pipeline Mode" from "Classic" to "Integrated" the custom error page appeared as expected.

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

JavaScript query string

I like to keep it simple, readable and small.

function searchToObject(search) {
    var pairs = search.substring(1).split("&"),
        obj = {}, pair;

    for (var i in pairs) {
        if (pairs[i] === "") continue;
        pair = pairs[i].split("=");
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return obj;
}

searchToObject(location.search);

Example:

searchToObject('?query=myvalue')['query']; // spits out: 'myvalue'

Restore a postgres backup file using the command line?

try this:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file

Issue with background color and Google Chrome

When you create CSS style using Dreamweaver for web designing, Dreamweaver adds a default code such as

@charset “utf-8";

Try removing this from your stylesheet, the background image or colour should display properly

Source

Block Comments in a Shell Script

I like a single line open and close:

if [ ]; then ##
    ...
    ...
fi; ##

The '##' helps me easily find the start and end to the block comment. I can stick a number after the '##' if I've got a bunch of them. To turn off the comment, I just stick a '1' in the '[ ]'. I also avoid some issues I've had with single-quotes in the commented block.

Remove char at specific index - python

as a sidenote, replace doesn't have to move all zeros. If you just want to remove the first specify count to 1:

'asd0asd0'.replace('0','',1)

Out:

'asdasd0'

How would I access variables from one class to another?

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1



class ClassB(ClassA):
    def __init__(self, class_a):
        self.var1 = class_a.var1
        self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
    var1 = 0
    var2 = 0
    def __init__(self):
        ClassA.var1 = 1
        ClassA.var2 = 2

    def methodA(self):
        ClassA.var1 = ClassA.var1 + ClassA.var2
        return ClassA.var1



class ClassB(ClassA):
    def __init__(self):
        print ClassA.var1
        print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

Note, however, that class variables are shared among all instances of its class.

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

Why use #define instead of a variable

C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

How to export collection to CSV in MongoDB?

Also, you are not allowed spaces between comma separated field names.

BAD: -f firstname, lastname

GOOD: -f firstname,lastname

Sort an array of objects in React and render them

You will need to sort your object before mapping over them. And it can be done easily with a sort() function with a custom comparator definition like

var obj = [...this.state.data];
obj.sort((a,b) => a.timeM - b.timeM);
obj.map((item, i) => (<div key={i}> {item.matchID}  
                      {item.timeM} {item.description}</div>))

Checking if a SQL Server login already exists

First you have to check login existence using syslogins view:

IF NOT EXISTS 
    (SELECT name  
     FROM master.sys.server_principals
     WHERE name = 'YourLoginName')
BEGIN
    CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END

Then you have to check your database existence:

USE your_dbname

IF NOT EXISTS
    (SELECT name
     FROM sys.database_principals
     WHERE name = 'your_dbname')
BEGIN
    CREATE USER [your_dbname] FOR LOGIN [YourLoginName] 
END

Generate random colors (RGB)

Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.

The cv::applyColorMap can easily generate a random RGB palette, and you can choose a favorite color map from the list here

Example for C++11:

#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>

std::random_device rd;
std::default_random_engine re(rd());

// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);

// ...

// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);

Example for Python3:

import numpy as np, cv2

palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...

rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)

If you don't need so many colors, you can just cut the palette to the desired length.

Connection refused on docker container

In Windows, you also normally need to run command line as administrator.

As standard-user:

docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon  106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read: 
>>>connection refused

But as an administrator.

docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon  106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete                                                                                             e936bd534ffb: Pull complete                                                                                             caf64655bcbb: Pull complete                                                                                             d1927dbcbcab: Pull complete                                                                                             Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
 ---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest

JavaScript blob filename without link

I just wanted to expand on the accepted answer with support for Internet Explorer (most modern versions, anyways), and to tidy up the code using jQuery:

$(document).ready(function() {
    saveFile("Example.txt", "data:attachment/text", "Hello, world.");
});

function saveFile (name, type, data) {
    if (data !== null && navigator.msSaveBlob)
        return navigator.msSaveBlob(new Blob([data], { type: type }), name);
    var a = $("<a style='display: none;'/>");
    var url = window.URL.createObjectURL(new Blob([data], {type: type}));
    a.attr("href", url);
    a.attr("download", name);
    $("body").append(a);
    a[0].click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

Here is an example Fiddle. Godspeed.

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region

How to run a PowerShell script from a batch file

You need the -ExecutionPolicy parameter:

Powershell.exe -executionpolicy remotesigned -File  C:\Users\SE\Desktop\ps.ps1

Otherwise PowerShell considers the arguments a line to execute and while Set-ExecutionPolicy is a cmdlet, it has no -File parameter.

Invoke native date picker from web-app on iOS/Android

Give Mobiscroll a try. The scroller style date and time picker was especially created for interaction on touch devices. It is pretty flexible, and easily customizable. It comes with iOS/Android themes.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Handling ExecuteScalar() when no results are returned

/* Select some int which does not exist */
int x = ((int)(SQL_Cmd.ExecuteScalar() ?? 0));

How to find SQL Server running port?

In our enterprise I don't have access to MSSQL Server, so I can'r access the system tables.

What works for me is:

  1. capture the network traffic Wireshark (run as Administrator, select Network Interface),while opening connection to server.
  2. Find the ip address with ping
  3. filter with ip.dst == x.x.x.x

The port is shown in the column info in the format src.port -> dst.port

How to take screenshot of a div with JavaScript?

<script src="/assets/backend/js/html2canvas.min.js"></script>


<script>
    $("#download").on('click', function(){
        html2canvas($("#printform"), {
            onrendered: function (canvas) {
                var url = canvas.toDataURL();

                var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"????????.jpeg").appendTo("body");
                triggerDownload[0].click();
                triggerDownload.remove();
            }
        });
    })
</script>

quotation

IsNullOrEmpty with Object

You may be checking an object null by comparing it with a null value but when you try to check an empty object then you need to string typecast. Below the code, you get the idea.

if(obj == null || (string) obj == string.Empty)
{
   //Obj is null or empty
}

How to get HttpClient to pass credentials along with the request?

What you are trying to do is get NTLM to forward the identity on to the next server, which it cannot do - it can only do impersonation which only gives you access to local resources. It won't let you cross a machine boundary. Kerberos authentication supports delegation (what you need) by using tickets, and the ticket can be forwarded on when all servers and applications in the chain are correctly configured and Kerberos is set up correctly on the domain. So, in short you need to switch from using NTLM to Kerberos.

For more on Windows Authentication options available to you and how they work start at: http://msdn.microsoft.com/en-us/library/ff647076.aspx

How do getters and setters work?

In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':

class Dummy
{
    private String name;

    public Dummy() {}

    public Dummy(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

When and where to use GetType() or typeof()?

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

GetType() is a method you call on individual objects, to get the execution-time type of the object.

Note that unless you only want exactly instances of TextBox (rather than instances of subclasses) you'd usually use:

if (myControl is TextBox)
{
    // Whatever
}

Or

TextBox tb = myControl as TextBox;
if (tb != null)
{
    // Use tb
}

How to match "any character" in regular expression?

Yes, you can. That should work.

  • . = any char except newline
  • \. = the actual dot character
  • .? = .{0,1} = match any char except newline zero or one times
  • .* = .{0,} = match any char except newline zero or more times
  • .+ = .{1,} = match any char except newline one or more times

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

How to grep recursively, but only in files with certain extensions?

Just use the --include parameter, like this:

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]

that should do what you want.

To take the explanation from HoldOffHunger's answer below:

  • grep: command

  • -r: recursively

  • -i: ignore-case

  • -n: each output line is preceded by its relative line number in the file

  • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)

  • ./: Start at current directory.

Convert json to a C# array?

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

handling DATETIME values 0000-00-00 00:00:00 in JDBC

I wrestled with this problem and implemented the 'convertToNull' solutions discussed above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.

SET sql_mode = 'NO_ZERO_DATE';

I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

Ellipsis for overflow text in dropdown boxes

I used this approach in a recent project and I was pretty happy with the result:

.select-wrapper {
    position: relative;
    &::after {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 100%;
        content: "";
        background: linear-gradient(to right, transparent, white);
        pointer-events: none;
    }
}

Basically, wrap the select in a div and insert a pseudo element to overlay the end of the text to create the appearance that the text fades out.

enter image description here

How to add title to subplots in Matplotlib?

In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.

  1. The catch is you can define dynamic axes(ax) as in Line 1 of code and you can set its title inside a loop.
  2. The rows of 2D array is length (len) of axis(ax)
  3. Each row has 2 items i.e. It is list within a list (Point No.2)
  4. set_title can be used to set title, once the proper axes(ax) or subplot is selected.
import matplotlib.pyplot as plt    
fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
for i in range(len(ax)): 
    for j in range(len(ax[i])):
        ## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
        ax[i,j].set_title('Title-' + str(i) + str(j))

How to keep console window open

You forgot calling your method:

static void Main(string[] args)
{          
    StringAddString s = new StringAddString();  
    s.AddString();
}

it should stop your console, but the result might not be what you expected, you should change your code a little bit:

Console.WriteLine(string.Join(",", strings2));

Why is "forEach not a function" for this object?

Object does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:

Object.keys(a).forEach(function (key){
    console.log(a[key]);
});

Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};, Object.keys(v) gives you an array of the keys so you get ["cat","dog","bird"]

Check variable equality against a list of values

You can write if(foo in L(10,20,30)) if you define L to be

var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};

Fastest way to determine if record exists

SELECT TOP 1 products.id FROM products WHERE products.id = ?; will outperform all of your suggestions as it will terminate execution after it finds the first record.

Output an Image in PHP

If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:

header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();

mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.

Remove Item in Dictionary based on Value

In my case I use this

  var key=dict.FirstOrDefault(m => m.Value == s).Key;
            dict.Remove(key);

Create view with primary key?

You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also. Applications requiring a primary key may accept the view as it is the case with Lightswitch.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How to calculate the angle between a line and the horizontal axis?

Based on reference "Peter O".. Here is the java version

private static final float angleBetweenPoints(PointF a, PointF b) {
float deltaY = b.y - a.y;
float deltaX = b.x - a.x;
return (float) (Math.atan2(deltaY, deltaX)); }

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

How do I find all the files that were created today in Unix/Linux?

If you're did something like accidentally rsync'd to the wrong directory, the above suggestions work to find new files, but for me, the easiest was connecting with an SFTP client like Transmit then ordering by date and deleting.

React-router v4 this.props.history.push(...) not working

You need to export the Customers Component not the CustomerList.

    CustomersList = withRouter(Customers);
    export default CustomersList;

SQL Group By with an Order By

You can get around this limit with the deprecated syntax: ORDER BY 1 DESC

This syntax is not deprecated at all, it's E121-03 from SQL99.

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

Limit String Length

From php 4.0.6 , there is a function for the exact same thing

function mb_strimwidth can be used for your requirement

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
//Hello W...
?>

It does have more options though,here is the documentation for this mb_strimwidth

reading from app.config file

Just for the future reference, you just need to add System.Configuration to your references library:

enter image description here

Calling a JavaScript function returned from an Ajax response

I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".

OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:

1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script> block within an existing <div> element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval() your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.

Even if quite dummy, this code explains the idea:

<html>
    <body>
        <div id="div1">
        </div>
        <div id="div2">
            <input type="button" value="Go!" onclick="go()" />
        </div>
        <script type="text/javascript">
            var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
            var e = document.getElementById('div1');
            e.innerHTML = newsc;
            eval(document.getElementById('sc1').innerHTML);
        </script>
    </body>
</html>

I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)

Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.

Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.

Replace tabs with spaces in vim

Once you've got expandtab on as per the other answers, the extremely convenient way to convert existing files according to your new settings is:

:retab

It will work on the current buffer.

Distribution certificate / private key not installed

In my case Xcode was not accessing certificates from the keychain, I followed these steps:

  1. delete certificates from the keychain.
  2. restart the mac.
  3. generate new certificates.
  4. install new certificates.
  5. clean build folder.
  6. build project.
  7. again clean build folder.
  8. archive now. It works That's it.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

In your entity class add @JsonInclude(JsonInclude.Include.NON_NULL) annotation to resolve the problem

it will look like

@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)

Insert PHP code In WordPress Page and Post

You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.

The easiest solution for this is creating a shortcode. Then you can use something like this

function input_func( $atts ) {
    extract( shortcode_atts( array(
        'type' => 'text',
        'name' => '',
    ), $atts ) );

    return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );

See the Shortcode_API.

How does += (plus equal) work?

+= in JavaScript (as well as in many other languages) adds the right hand side to the variable on the left hand side, storing the result in that variable. Your example of 1 +=2 therefore does not make sense. Here is an example:

var x = 5;
x += 4; // x now equals 9, same as writing x = x + 4;
x -= 3; // x now equals 6, same as writing x = x - 3;
x *= 2; // x now equals 12, same as writing x = x * 2;
x /= 3; // x now equals 4, same as writing x = x / 3;

In your specific example the loop is summing the numbers in the array data.

Datagridview full row selection but get single cell value

string value = dataGridVeiw1.CurrentRow.Cells[1].Value.ToString();

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

How to give your program more memory when running from Eclipse

Go to Run / Run Configurations. Select the run configuration for your program. Click on the tab "Arguments". In the "Program arguments" area, add a -Xmx argument, for example -Xmx2048m to give your program a max. of 2048 MB (2 GB) memory.

How to prevent this memory problem

Re-write your program in such a way that it does not need to store so much data in memory. I haven't looked at your code in detail, but it looks like you're storing a lot of data in a HashMap; more than fits in memory when you have a lot of records.

How does RewriteBase work in .htaccess

The clearest explanation I found was not in the current 2.4 apache docs, but in version 2.0.

#  /abc/def/.htaccess -- per-dir config file for directory /abc/def
#  Remember: /abc/def is the physical path of /xyz, i.e., the server
#            has a 'Alias /xyz /abc/def' directive e.g.

RewriteEngine On

#  let the server know that we were reached via /xyz and not
#  via the physical path prefix /abc/def
RewriteBase   /xyz

How does it work? For you apache hackers, this 2.0 doc goes on to give "detailed information about the internal processing steps."

Lesson learned: While we need to be familiar with "current," gems can be found in the annals.

Why should I use a pointer rather than the object itself?

But I can't figure out why should we use it like this?

I will compare how it works inside the function body if you use:

Object myObject;

Inside the function, your myObject will get destroyed once this function returns. So this is useful if you don't need your object outside your function. This object will be put on current thread stack.

If you write inside function body:

 Object *myObject = new Object;

then Object class instance pointed by myObject will not get destroyed once the function ends, and allocation is on the heap.

Now if you are Java programmer, then the second example is closer to how object allocation works under java. This line: Object *myObject = new Object; is equivalent to java: Object myObject = new Object();. The difference is that under java myObject will get garbage collected, while under c++ it will not get freed, you must somewhere explicitly call `delete myObject;' otherwise you will introduce memory leaks.

Since c++11 you can use safe ways of dynamic allocations: new Object, by storing values in shared_ptr/unique_ptr.

std::shared_ptr<std::string> safe_str = make_shared<std::string>("make_shared");

// since c++14
std::unique_ptr<std::string> safe_str = make_unique<std::string>("make_shared"); 

also, objects are very often stored in containers, like map-s or vector-s, they will automatically manage a lifetime of your objects.

CertificateException: No name matching ssl.someUrl.de found

If you're looking for a Kafka error, this might because the upgrade of Kafka's version from 1.x to 2.x.

javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... java.security.cert.CertificateException: No name matching *** found

or

[Producer clientId=producer-1] Connection to node -2 failed authentication due to: SSL handshake failed

The default value for ssl.endpoint.identification.algorithm was changed to https, which performs hostname verification (man-in-the-middle attacks are possible otherwise). Set ssl.endpoint.identification.algorithm to an empty string to restore the previous behaviour. Apache Kafka Notable changes in 2.0.0

Solution: SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

This appears to mostly happens when the MySQL username and password are not correct. Check your MySQL username and password.

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

SQL select only rows with max value on a column

Sorted the rev field in reverse order and then grouped by id which gave the first row of each grouping which is the one with the highest rev value.

SELECT * FROM (SELECT * FROM table1 ORDER BY id, rev DESC) X GROUP BY X.id;

Tested in http://sqlfiddle.com/ with the following data

CREATE TABLE table1
    (`id` int, `rev` int, `content` varchar(11));

INSERT INTO table1
    (`id`, `rev`, `content`)
VALUES
    (1, 1, 'One-One'),
    (1, 2, 'One-Two'),
    (2, 1, 'Two-One'),
    (2, 2, 'Two-Two'),
    (3, 2, 'Three-Two'),
    (3, 1, 'Three-One'),
    (3, 3, 'Three-Three')
;

This gave the following result in MySql 5.5 and 5.6

id  rev content
1   2   One-Two
2   2   Two-Two
3   3   Three-Two

Can HTTP POST be limitless?

HTTP may not have an upper limit, but webservers may have one. In ASP.NET there is a default accept-limit of 4 MB, but you (the developer/webmaster) can change that to be higher or lower.

JavaScript global event mechanism

It seems that window.onerror doesn't provide access to all possible errors. Specifically it ignores:

  1. <img> loading errors (response >= 400).
  2. <script> loading errors (response >= 400).
  3. global errors if you have many other libraries in your app also manipulating window.onerror in an unknown way (jquery, angular, etc.).
  4. probably many cases I haven't run into after exploring this now (iframes, stack overflow, etc.).

Here is the start of a script that catches many of these errors, so that you may add more robust debugging to your app during development.

(function(){

/**
 * Capture error data for debugging in web console.
 */

var captures = [];

/**
 * Wait until `window.onload`, so any external scripts
 * you might load have a chance to set their own error handlers,
 * which we don't want to override.
 */

window.addEventListener('load', onload);

/**
 * Custom global function to standardize 
 * window.onerror so it works like you'd think.
 *
 * @see http://www.quirksmode.org/dom/events/error.html
 */

window.onanyerror = window.onanyerror || onanyerrorx;

/**
 * Hook up all error handlers after window loads.
 */

function onload() {
  handleGlobal();
  handleXMLHttp();
  handleImage();
  handleScript();
  handleEvents();
}

/**
 * Handle global window events.
 */

function handleGlobal() {
  var onerrorx = window.onerror;
  window.addEventListener('error', onerror);

  function onerror(msg, url, line, col, error) {
    window.onanyerror.apply(this, arguments);
    if (onerrorx) return onerrorx.apply(null, arguments);
  }
}

/**
 * Handle ajax request errors.
 */

function handleXMLHttp() {
  var sendx = XMLHttpRequest.prototype.send;
  window.XMLHttpRequest.prototype.send = function(){
    handleAsync(this);
    return sendx.apply(this, arguments);
  };
}

/**
 * Handle image errors.
 */

function handleImage() {
  var ImageOriginal = window.Image;
  window.Image = ImageOverride;

  /**
   * New `Image` constructor. Might cause some problems,
   * but not sure yet. This is at least a start, and works on chrome.
   */

  function ImageOverride() {
    var img = new ImageOriginal;
    onnext(function(){ handleAsync(img); });
    return img;
  }
}

/**
 * Handle script errors.
 */

function handleScript() {
  var HTMLScriptElementOriginal = window.HTMLScriptElement;
  window.HTMLScriptElement = HTMLScriptElementOverride;

  /**
   * New `HTMLScriptElement` constructor.
   *
   * Allows us to globally override onload.
   * Not ideal to override stuff, but it helps with debugging.
   */

  function HTMLScriptElementOverride() {
    var script = new HTMLScriptElement;
    onnext(function(){ handleAsync(script); });
    return script;
  }
}

/**
 * Handle errors in events.
 *
 * @see http://stackoverflow.com/questions/951791/javascript-global-error-handling/31750604#31750604
 */

function handleEvents() {
  var addEventListenerx = window.EventTarget.prototype.addEventListener;
  window.EventTarget.prototype.addEventListener = addEventListener;
  var removeEventListenerx = window.EventTarget.prototype.removeEventListener;
  window.EventTarget.prototype.removeEventListener = removeEventListener;

  function addEventListener(event, handler, bubble) {
    var handlerx = wrap(handler);
    return addEventListenerx.call(this, event, handlerx, bubble);
  }

  function removeEventListener(event, handler, bubble) {
    handler = handler._witherror || handler;
    removeEventListenerx.call(this, event, handler, bubble);
  }

  function wrap(fn) {
    fn._witherror = witherror;

    function witherror() {
      try {
        fn.apply(this, arguments);
      } catch(e) {
        window.onanyerror.apply(this, e);
        throw e;
      }
    }
    return fn;
  }
}

/**
 * Handle image/ajax request errors generically.
 */

function handleAsync(obj) {
  var onerrorx = obj.onerror;
  obj.onerror = onerror;
  var onabortx = obj.onabort;
  obj.onabort = onabort;
  var onloadx = obj.onload;
  obj.onload = onload;

  /**
   * Handle `onerror`.
   */

  function onerror(error) {
    window.onanyerror.call(this, error);
    if (onerrorx) return onerrorx.apply(this, arguments);
  };

  /**
   * Handle `onabort`.
   */

  function onabort(error) {
    window.onanyerror.call(this, error);
    if (onabortx) return onabortx.apply(this, arguments);
  };

  /**
   * Handle `onload`.
   *
   * For images, you can get a 403 response error,
   * but this isn't triggered as a global on error.
   * This sort of standardizes it.
   *
   * "there is no way to get the HTTP status from a 
   * request made by an img tag in JavaScript."
   * @see http://stackoverflow.com/questions/8108636/how-to-get-http-status-code-of-img-tags/8108646#8108646
   */

  function onload(request) {
    if (request.status && request.status >= 400) {
      window.onanyerror.call(this, request);
    }
    if (onloadx) return onloadx.apply(this, arguments);
  }
}

/**
 * Generic error handler.
 *
 * This shows the basic implementation, 
 * which you could override in your app.
 */

function onanyerrorx(entity) {
  var display = entity;

  // ajax request
  if (entity instanceof XMLHttpRequest) {
    // 400: http://example.com/image.png
    display = entity.status + ' ' + entity.responseURL;
  } else if (entity instanceof Event) {
    // global window events, or image events
    var target = entity.currentTarget;
    display = target;
  } else {
    // not sure if there are others
  }

  capture(entity);
  console.log('[onanyerror]', display, entity);
}

/**
 * Capture stuff for debugging purposes.
 *
 * Keep them in memory so you can reference them
 * in the chrome debugger as `onanyerror0` up to `onanyerror99`.
 */

function capture(entity) {
  captures.push(entity);
  if (captures.length > 100) captures.unshift();

  // keep the last ones around
  var i = captures.length;
  while (--i) {
    var x = captures[i];
    window['onanyerror' + i] = x;
  }
}

/**
 * Wait til next code execution cycle as fast as possible.
 */

function onnext(fn) {
  setTimeout(fn, 0);
}

})();

It could be used like this:

window.onanyerror = function(entity){
  console.log('some error', entity);
};

The full script has a default implementation that tries to print out a semi-readable "display" version of the entity/error that it receives. Can be used for inspiration for an app-specific error handler. The default implementation also keeps a reference to the last 100 error entities, so you can inspect them in the web console after they occur like:

window.onanyerror0
window.onanyerror1
...
window.onanyerror99

Note: This works by overriding methods on several browser/native constructors. This can have unintended side-effects. However, it has been useful to use during development, to figure out where errors are occurring, to send logs to services like NewRelic or Sentry during development so we can measure errors during development, and on staging so we can debug what is going on at a deeper level. It can then be turned off in production.

Hope this helps.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

If you try to run 32-bit applications on IIS 7 (and/or 64-bit OS machine), you will get the same error. So, from the IIS 7, right click on the applications' application pool and go to "advanced settings" and change "Enable 32-Bit Applications" to "TRUE".

Restart your website and it should work.

enter image description here

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

In my case (Python 3.4, in a virtual environment, running under macOS 10.10.6) I could not even upgrade pip itself. Help came from this SO answer in the form of the following one-liner:

curl https://bootstrap.pypa.io/get-pip.py | python

(If you do not use a virtual environment, you may need sudo python.)

With this I managed to upgrade pip from Version 1.5.6 to Version 10.0.0 (quite a jump!). This version does not use TLS 1.0 or 1.1 which are not supported any more by the Python.org site(s), and can install PyPI packages nicely. No need to specify --index-url=https://pypi.python.org/simple/.

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

Better way to get type of a Javascript variable?

typeof condition is used to check variable type, if you are check variable type in if-else condition e.g.

if(typeof Varaible_Name "undefined")
{

}

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How can I explicitly free memory in Python?

(del can be your friend, as it marks objects as being deletable when there no other references to them. Now, often the CPython interpreter keeps this memory for later use, so your operating system might not see the "freed" memory.)

Maybe you would not run into any memory problem in the first place by using a more compact structure for your data. Thus, lists of numbers are much less memory-efficient than the format used by the standard array module or the third-party numpy module. You would save memory by putting your vertices in a NumPy 3xN array and your triangles in an N-element array.

How to use wait and notify in Java without IllegalMonitorStateException?

Simple use if you want How to execute threads alternatively :-

public class MyThread {
    public static void main(String[] args) {
        final Object lock = new Object();
        new Thread(() -> {
            try {
                synchronized (lock) {
                    for (int i = 0; i <= 5; i++) {
                        System.out.println(Thread.currentThread().getName() + ":" + "A");
                        lock.notify();
                        lock.wait();
                    }
                }
            } catch (Exception e) {}
        }, "T1").start();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    for (int i = 0; i <= 5; i++) {
                        System.out.println(Thread.currentThread().getName() + ":" + "B");
                        lock.notify();
                        lock.wait();
                    }
                }
            } catch (Exception e) {}
        }, "T2").start();
    }
}

response :-

T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B
T1:A
T2:B

Run exe file with parameters in a batch file

Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe program, which won't open unnecessary windows.

Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2

Otherwise, just quote stuff as Andrew points out.


In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):

"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2

How to find top three highest salary in emp table in oracle?

SELECT  Name, Salary
FROM 
    (
    SELECT  Name, Salary
    FROM         emp 
    ORDER BY Salary desc
    )
WHERE rownum <= 3
ORDER BY Salary ;

Check that an email address is valid on iOS

To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.

Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$

How you can use regular expressions depends on the version of iOS you are using.

iOS 4.x and Later

You can use NSRegularExpression, which allows you to compile and test against a regular expression directly.

iOS 3.x

Does not include the NSRegularExpression class, but does include NSPredicate, which can match against regular expressions.

NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];

Read a full article about this approach at cocoawithlove.com.

iOS 2.x

Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.

What's a clean way to stop mongod on Mac OS X?

This is an old question, but its one I found while searching as well.

If you installed with brew then the solution would actually be the this:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I use XAMPP and had the same error. I used Paul Gobée solution above and it worked for me. I navigated to C:\xampp\mysql\bin\mysqld-debug.exe and upon starting the .exe my Windows Firewall popped up asking for permission. Once I allowed it, it worked fine. I would have commented under his post but I do not have that much rep yet... sry! Just wanted to let everyone know this worked for me as well.

How do you uninstall a python package that was installed using distutils?

The three things that get installed that you will need to delete are:

  1. Packages/modules
  2. Scripts
  3. Data files

Now on my linux system these live in:

  1. /usr/lib/python2.5/site-packages
  2. /usr/bin
  3. /usr/share

But on a windows system they are more likely to be entirely within the Python distribution directory. I have no idea about OSX except it is more likey to follow the linux pattern.

Center Align on a Absolutely Positioned Div

If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

Remember that in order to position an element absolutely, the parent element must be positioned relatively.

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.