Programs & Examples On #Datagridviewcomboboxcell

DataGridViewComboBoxCell allows you to select a value for the respective DataGridView cell, from the list of values (available in popup displayed). The user can select item by clicking on an item or can use arrow keys to pick up from the available list or can type a value.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Define an alias in fish shell

Just use alias. Here's a basic example:

# Define alias in shell
alias rmi "rm -i"

# Define alias in config file
alias rmi="rm -i"

# This is equivalent to entering the following function:
function rmi
    rm -i $argv
end

# Then, to save it across terminal sessions:
funcsave rmi

This last command creates the file ~/.config/fish/functions/rmi.fish.

Interested people might like to find out more about fish aliases in the official manual.

How to dismiss the dialog with click on outside of the dialog?

dialog.setCanceledOnTouchOutside(true); 

to close dialog on touch outside.

And if you don't want to close on touch outside, use the code below:

dialog.setCanceledOnTouchOutside(false);

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

Hibernate, @SequenceGenerator and allocationSize

I would check the DDL for the sequence in the schema. JPA Implementation is responsible only creation of the sequence with the correct allocation size. Therefore, if the allocation size is 50 then your sequence must have the increment of 50 in its DDL.

This case may typically occur with the creation of a sequence with allocation size 1 then later configured to allocation size 50 (or default) but the sequence DDL is not updated.

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

Creating a config file in PHP

Here is my way.

    <?php

    define('DEBUG',0);

    define('PRODUCTION',1);



    #development_mode : DEBUG / PRODUCTION

    $development_mode = PRODUCTION;



    #Website root path for links

    $app_path = 'http://192.168.0.234/dealer/';



    #User interface files path

    $ui_path = 'ui/';

    #Image gallery path

    $gallery_path = 'ui/gallery/';


    $mysqlserver = "localhost";
    $mysqluser = "root";
    $mysqlpass = "";
    $mysqldb = "dealer_plus";

   ?>

Any doubts please comment

Redirect from a view to another view

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); }

How to initialise a string from NSData in Swift

Objective - C

NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);

Swift

//This your data containing the string
   let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)

   //Use this method to convert the data into String
   let myStringFromData =  String(data:myStringData!, encoding: NSUTF8StringEncoding)

   print("My string value:" + myStringFromData!)

http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html

Image inside div has extra space below the image

You can use several methods for this issue like

  1. Using line-height

    #wrapper {  line-height: 0px;  }
    
  2. Using display: flex

    #wrapper {  display: flex;         }
    #wrapper {  display: inline-flex;  }
    
  3. Using display: block, table, flex and inherit

    #wrapper img {  display: block;    }
    #wrapper img {  display: table;    }
    #wrapper img {  display: flex;     }
    #wrapper img {  display: inherit;  }
    

scale fit mobile web content using viewport meta tag

Try adding a style="width:100%;" to the img tag. That way the image will fill up the entire width of the page, thus scaling down if the image is larger than the viewport.

How to subtract hours from a date in Oracle so it affects the day also

Try this:

SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL

To test it using a new date instance:

SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL

Output is: 06-10-2015 22:00, which is the previous day.

HTML.HiddenFor value set

Strange but, Try with @Value , capital "V"

e.g. (working on MVC4)

@Html.HiddenFor(m => m.Id, new { @Value = Model.Id })

Update:

Found that @Value (capital V) is creating another attribute with "Value" along with "value", using small @value seems to be working too!

Need to check the MVC source code to find more.


Update, After going through how it works internally:

First of all forget all these workarounds (I have kept in for the sake of continuity here), now looks silly :)

Basically, it happens when a model is posted and the model is returned back to same page.

The value is accessed (and formed into html) in InputHelper method (InputExtensions.cs) using following code fragment

string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));

The GetModelStateValue method (in Htmlelper.cs) retrieves the value as

ViewData.ModelState.TryGetValue(key, out modelState)

Here is the issue, since the value is accessed from ViewData.ModelState dictionary. This returns the value posted from the page instead of modified value!!

i.e. If your posted value of the variable (e.g. Person.Id) is 0 but you set the value inside httpPost action (e.g. Person.Id = 2), the ModelState still retains the old value "0" and the attemptedValue contains "0" ! so the field in rendered page will contain "0" as value!!

Workaround if you are returning model to same page : Clear the item from ModelState,

e.g.

ModelState.Remove("Id"); 

This will remove the item from dictionary and the ViewData.ModelState.TryGetValue(key, out modelState) returns null, and the next statement (inside InputExtensions.cs) takes the actual value (valueParameter) passed to HiddenFor(m => m.Id)

this is done in the following line in InputExtensions.cs

tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName, format) : valueParameter), isExplicitValue);

Summary:

Clear the item in ModelState using:

ModelState.Remove("...");

Hope this is helpful.

How do I connect to my existing Git repository using Visual Studio Code?

Use the Git GUI in the Git plugin.

Clone your online repository with the URL which you have.

After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.

Fetch from the remote (to check if anything is updated while you are working).

If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.

Push your changes to the upstream remote repository by making a push operation.

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

Be aware, using NSAllowsArbitraryLoads = true in the project's info.plist allows all connection to any server to be insecure. If you want to make sure only a specific domain is accessible through an insecure connection, try this:

enter image description here

Or, as source code:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>domain.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Clean & Build project after editing.

Getting current device language in iOS?

This will probably give you what you want:

NSLocale *locale = [NSLocale currentLocale];

NSString *language = [locale displayNameForKey:NSLocaleIdentifier 
                                         value:[locale localeIdentifier]];

It will show the name of the language, in the language itself. For example:

Français (France)
English (United States)

Can the Android drawable directory contain subdirectories?

  1. Right click on Drawable
  2. Select New ---> Directory
  3. Enter the directory name. Eg: logo.png(the location will already show the drawable folder by default)
  4. Copy and paste the images directly into the drawable folder. While pasting you get an option to choose mdpi/xhdpi/xxhdpi etc for each of the images from a list. Select the appropriate option and enter the name of the image. Make sure to keep the same name as the directory name i.e logo.png
  5. Do the same for the remaining images. All of them will be placed under the logo.png main folder.

How Can I Truncate A String In jQuery?

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }

Java: convert List<String> to a String

Not out of the box, but many libraries have similar:

Commons Lang:

org.apache.commons.lang.StringUtils.join(list, conjunction);

Spring:

org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);

Identify if a string is a number

I guess this answer will just be lost in between all the other ones, but anyway, here goes.

I ended up on this question via Google because I wanted to check if a string was numeric so that I could just use double.Parse("123") instead of the TryParse() method.

Why? Because it's annoying to have to declare an out variable and check the result of TryParse() before you know if the parse failed or not. I want to use the ternary operator to check if the string is numerical and then just parse it in the first ternary expression or provide a default value in the second ternary expression.

Like this:

var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;

It's just a lot cleaner than:

var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
    //whatever you want to do with doubleValue
}

I made a couple extension methods for these cases:


Extension method one

public static bool IsParseableAs<TInput>(this string value) {
    var type = typeof(TInput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return false;

    var arguments = new[] { value, Activator.CreateInstance(type) };
    return (bool) tryParseMethod.Invoke(null, arguments);
}

Example:

"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;

Because IsParseableAs() tries to parse the string as the appropriate type instead of just checking if the string is "numeric" it should be pretty safe. And you can even use it for non numeric types that have a TryParse() method, like DateTime.

The method uses reflection and you end up calling the TryParse() method twice which, of course, isn't as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.

This method can also be used to easily parse a list of numeric strings into a list of double or some other type with a default value without having to catch any exceptions:

var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);

Extension method two

public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
    var type = typeof(TOutput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return defaultValue;

    var arguments = new object[] { value, null };
    return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}

This extension method lets you parse a string as any type that has a TryParse() method and it also lets you specify a default value to return if the conversion fails.

This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though...

Examples:

"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);

Outputs:

123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00

How to drop a database with Mongoose?

There is no method for dropping a collection from mongoose, the best you can do is remove the content of one :

Model.remove({}, function(err) { 
   console.log('collection removed') 
});

But there is a way to access the mongodb native javascript driver, which can be used for this

mongoose.connection.collections['collectionName'].drop( function(err) {
    console.log('collection dropped');
});

Warning

Make a backup before trying this in case anything goes wrong!

How to clear the cache in NetBeans

Before 7.2, the cache is at C:\Users\username\.netbeans\7.0\var\cache. Deleting this directory should clear the cache for you.

Convert the first element of an array to a string in PHP

Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    $my_array = array(4, 1, 8);
    
    print_r($my_array);
    Array
    (
        [0] => 4
        [1] => 1
        [2] => 8
    )
    
    $result_string = join(',', $my_array);
    echo $result_string;
    

    Which delimits the items in the array by comma into a string:

    4,1,8
    
  2. Or use the PHP implode function like this:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    php> $keyvalues = array();
    
    php> $keyvalues['foo'] = "bar";
    
    php> $keyvalues['pyramid'] = "power";
    
    php> print_r($keyvalues);
    Array
    (
        [foo] => bar
        [pyramid] => power
    )
    
    php> echo join(',', $keyvalues);
    bar,power
    php> echo implode($keyvalues);
    barpower
    php>
    

Python's equivalent of && (logical-and) in an if-statement

Python uses and and or conditionals.

i.e.

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

Beamer: How to show images as step-by-step images

I found a solution to my problem, by using the visble-command.

EDITED:

\visible<2->{
   \textbf{Some text}
   \begin{figure}[ht]
       \includegraphics[width=5cm]{./path/to/image}
    \end{figure}
 }

How can I write these variables into one line of code in C#?

Look into composite formatting:

Console.WriteLine("{0}.{1}.{2}", mon, da, yer);

You could also write (although it's not really recommended):

Console.WriteLine(mon + "." + da + "." + yer);

And, with the release of C# 6.0, you have string interpolation expressions:

Console.WriteLine($"{mon}.{da}.{yer}");  // note the $ prefix.

PostgreSQL: insert from another table

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

How to rsync only a specific list of files?

Edit: atp's answer below is better. Please use that one!

You might have an easier time, if you're looking for a specific list of files, putting them directly on the command line instead:

# rsync -avP -e ssh `cat deploy/rsync_include.txt` [email protected]:/var/www/

This is assuming, however, that your list isn't so long that the command line length will be a problem and that the rsync_include.txt file contains just real paths (i.e. no comments, and no regexps).

Signing a Windows EXE file

You can get a free cheap code signing certificate from Certum if you're doing open source development.

I've been using their certificate for over a year, and it does get rid of the unknown publisher message from Windows.

As far as signing code I use signtool.exe from a script like this:

signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll /f "MyCert.pfx" /p MyPassword /d SignedFile.exe SignedFile.exe

Escape quote in web.config connection string

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

Since the web.config is XML, you need to escape the five special characters:

&amp; -> & ampersand, U+0026
&lt; -> < left angle bracket, less-than sign, U+003C
&gt; -> > right angle bracket, greater-than sign, U+003E
&quot; -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027

+ is not a problem, I suppose.


Duc Filan adds: You should also wrap your password with single quote ':

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

Could not complete the operation due to error 80020101. IE

when do you call timerReset()? Perhaps you get that error when trying to call it after setTimeout() has already done its thing?

wrap it in

if (window.myTimeout) { 
  clearTimeout(myTimeout);
  myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

edit: Actually, upon further reflection, since you did mention jQuery (and yet don't have any actual jQuery code here... I wonder if you have this nested within some jQuery (like inside a $(document).ready(.. and this is a matter of variable scope. If so, try this:

window.message="Logged in";
window.myTimeout = setTimeout("timerDone()",1000 * 1440);
function timerDone()
{
    window.message="Logged out";   
}
function timerReset()
{


    clearTimeout(window.myTimeout);
    window.myTimeout = setTimeout("timerDone()", 1000 * 1440);
}

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

How do I select an element that has a certain class?

h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

Your want to note it like this:

.myClass h2

Which selects all children of myClass which have the tagname h2

While loop in batch

It was very useful for me i have used in the following way to add user in active directory:

:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q

@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "

cls

:while1

if %x% leq %lent% (

    dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
    echo User %Uname%%x% with DC %DcName% is created
    set /a "x = x + 1"
    goto :while1
)

endlocal

Is there a way to access an iteration-counter in Java's for-each loop?

I'm afraid this isn't possible with foreach. But I can suggest you a simple old-styled for-loops:

    List<String> l = new ArrayList<String>();

    l.add("a");
    l.add("b");
    l.add("c");
    l.add("d");

    // the array
    String[] array = new String[l.size()];

    for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
    {
        array[it.nextIndex()] = it.next();
    }

Notice that, the List interface gives you access to it.nextIndex().

(edit)

To your changed example:

    for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
    {
        int i = it.nextIndex();
        doSomethingWith(it.next(), i);
    }

How to shrink/purge ibdata1 file in MySQL

If your goal is to monitor MySQL free space and you can't stop MySQL to shrink your ibdata file, then get it through table status commands. Example:

MySQL > 5.1.24:

mysqlshow --status myInnodbDatabase myTable | awk '{print $20}'

MySQL < 5.1.24:

mysqlshow --status myInnodbDatabase myTable | awk '{print $35}'

Then compare this value to your ibdata file:

du -b ibdata1

Source: http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html

Eclipse "Invalid Project Description" when creating new project from existing source

paste the project source and support libs to any other newly created folder and try to import from there. It worked for me.

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

Which one is better and what is the difference between these two Its almost imposibble to me, someone just want to get the number of records without re-touching or perform another query which involved same resource. Furthermore, the memory used by these two function is in same way after all, since with count_all_result you still performing get (in CI AR terms), so i recomend you using the other one (or use count() instead) which gave you reusability benefits.

How to get the current date without the time?

I think you need separately date parts like (day, Month, Year)

DateTime today = DateTime.Today;

Will not work for your case. You can get date separately so you don't need variable today to be as a DateTimeType, so lets just give today variable int Type because the day is only int. So today is 10 March 2020 then the result of

int today = DateTime.Today.Day;

int month = DateTime.Today.Month;

int year = DateTime.Today.Year;

MessageBox.Show(today.ToString()+ " - this is day. "+month.ToString()+ " - this is month. " + year.ToString() + " - this is year");

would be "10 - this is day. 3 - this is month. 2020 - this is year"

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Your dialog should not be a "long-lived object that needs a context". The documentation is confusing. Basically if you do something like:

static Dialog sDialog;

(note the static)

Then in an activity somewhere you did

 sDialog = new Dialog(this);

You would likely be leaking the original activity during a rotation or similar that would destroy the activity. (Unless you clean up in onDestroy, but in that case you probably wouldn't make the Dialog object static)

For some data structures it would make sense to make them static and based off the application's context, but generally not for UI related things, like dialogs. So something like this:

Dialog mDialog;

...

mDialog = new Dialog(this);

Is fine and shouldn't leak the activity as mDialog would be freed with the activity since it's not static.

How can I get (query string) parameters from the URL in Next.js?

import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}

We can find the query object inside a router using which we can get all query string parameters.

Can't bind to 'ngModel' since it isn't a known property of 'input'

For my scenario, I had to import both [CommonModule] and [FormsModule] to my module

import { NgModule } from '@angular/core' 
import { CommonModule } from '@angular/common'; 
import { FormsModule } from '@angular/forms'; 

import { MyComponent } from './mycomponent'

@NgModule({
    imports: [
        CommonModule,
        FormsModule
    ],
    declarations: [
        MyComponent 
    ]
 }) 
export class MyModule { }

Get element of JS object with an index

JS objects have no defined order, they are (by definition) an unsorted set of key-value pairs.

If by "first" you mean "first in lexicographical order", you can however use:

var sortedKeys = Object.keys(myobj).sort();

and then use:

var first = myobj[sortedKeys[0]];

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

Curiously, I was able to solve the same issue by doing the exact opposite move to svc's ! I had to :

1) replace the FQDN hostname in my tnsnames.ora / listener.ora files with localhost, and restart the listener service, and

2) two, I had to use "SYS as SYSDBA" as the username in the SQL Developer input textbox

to finally be able to have SQL Developer hook to my local instance.

Java - Create a new String instance with specified length and filled with specific character. Best solution?

using Dollar is simple:

String filled = $("=").repeat(10).toString(); // produces "=========="

angular.service vs angular.factory

app.factory('fn', fn) vs. app.service('fn',fn)

Construction

With factories, Angular will invoke the function to get the result. It is the result that is cached and injected.

 //factory
 var obj = fn();
 return obj;

With services, Angular will invoke the constructor function by calling new. The constructed function is cached and injected.

  //service
  var obj = new fn();
  return obj;

Implementation

Factories typically return an object literal because the return value is what's injected into controllers, run blocks, directives, etc

  app.factory('fn', function(){
         var foo = 0;
         var bar = 0;
         function setFoo(val) {
               foo = val;
         }
         function setBar (val){
               bar = val;
         }
         return {
                setFoo: setFoo,
                serBar: setBar
         }
  });

Service functions typically do not return anything. Instead, they perform initialization and expose functions. Functions can also reference 'this' since it was constructed using 'new'.

app.service('fn', function () {
         var foo = 0;
         var bar = 0;
         this.setFoo = function (val) {
               foo = val;
         }
         this.setBar = function (val){
               bar = val;
         }
});

Conclusion

When it comes to using factories or services they are both very similar. They are injected into a controllers, directives, run block, etc, and used in client code in pretty much the same way. They are also both singletons - meaning the same instance is shared between all places where the service/factory is injected.

So which should you prefer? Either one - they are so similar that the differences are trivial. If you do choose one over the other, just be aware how they are constructed, so that you can implement them properly.

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

TSQL Default Minimum DateTime

"Perhaps I should leave it null"

Don't use magic numbers - it's bad practice - if you don't have a value leave it null

Otherwise if you really want a default date - use one of the other techniques posted to set a default date

Connecting to SQL Server with Visual Studio Express Editions

If you are using this to get a LINQ to SQL which I do and wanted for my Visual Developer, 1) get the free Visual WEB Developer, use that to connect to SQL Server instance, create your LINQ interface, then copy the generated files into your Vis-Dev project (I don't use VD because it sounds funny). Include only the *.dbml files. The Vis-Dev environment will take a second or two to recognize the supporting files. It is a little extra step but for sure better than doing it by hand or giving up on it altogether or EVEN WORSE, paying for it. Mooo ha ha haha.

How do I concatenate two lists in Python?

If you want to merge the two lists in sorted form, you can use the merge function from the heapq library.

from heapq import merge

a = [1, 2, 4]
b = [2, 4, 6, 7]

print list(merge(a, b))

HttpRequest maximum allowable size in tomcat?

Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at <%GERONIMO_HOME%>/var/catalina/server.xml.

The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize still displays 2097152 (the default value)

Update with two tables?

Your query does not work because you have no FROM clause that specifies the tables you are aliasing via A/B.

Please try using the following:

UPDATE A
    SET A.NAME = B.NAME
FROM TableNameA A, TableNameB B
WHERE A.ID = B.ID

Personally I prefer to use more explicit join syntax for clarity i.e.

UPDATE A
    SET A.NAME = B.NAME
FROM TableNameA A
    INNER JOIN TableName B ON 
        A.ID = B.ID

How to count TRUE values in a logical vector

There are some problems when logical vector contains NA values.
See for example:

z <- c(TRUE, FALSE, NA)
sum(z) # gives you NA
table(z)["TRUE"] # gives you 1
length(z[z == TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)

So I think the safest is to use na.rm = TRUE:

sum(z, na.rm = TRUE) # best way to count TRUE values

(which gives 1). I think that table solution is less efficient (look at the code of table function).

Also, you should be careful with the "table" solution, in case there are no TRUE values in the logical vector. Suppose z <- c(NA, FALSE, NA) or simply z <- c(FALSE, FALSE), then table(z)["TRUE"] gives you NA for both cases.

OR, AND Operator

If what interests you is bitwise operations look here for a brief tutorial : http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)

If you want logical operation answers are already given.

Preferred way to create a Scala list

And for simple cases:

val list = List(1,2,3) 

:)

Popup window in PHP?

PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.

So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.

Difference between Static methods and Instance methods

The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :) Same is the case with variables.

How To change the column order of An Existing Table in SQL Server 2008

This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).

Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.

The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:

a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns

OR

b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along

The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.

I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

ASP.NET Background image

Just a heads up, while some of the answers posted here are correct (in a sense) one thing that you may need to do is go back to the root folder to delve down into the folder holding the image you want to set as the background. In other words, this code is correct in accomplishing your goal:

body {
    background-image:url('images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

But you may also need to add a little more to the code, like this:

body {
    background-image:url('../images/background.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
}

The difference, as you can see, is that you may need to add “../” in front of the “images/background.png” call. This same rule also applies in HTML5 web pages. So if you are trying the first sample code listed here and you are still not getting the background image, try adding the “../” in front of “images”. Hope this helps .

What to do on TransactionTooLargeException

I have also lived TransactionTooLargeException. Firstly I have worked on understand where it occurs. I know the reason why it occurs. Every of us know because of large content. My problem was like that and I solved. Maybe this solution can be useful for anybody. I have an app that get content from api. I am getting result from API in first screen and send it to second screen. I can send this content to second screen in successful. After second screen if I want to go third screen this exception occurs. Each of my screen is created from Fragment. I noticed that when I leave from second screen. It saves its bundle content. if this content is too large this exception happens. My solution is after I got content from bundle I clear it.

class SecondFragment : BaseFragment() {

    lateinit var myContent: MyContent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        myContent = arguments?.getParcelable("mycontent")
        arguments?.clear()
    }

Find Process Name by its Process ID

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
    tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
    tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.

tasklist /fi "idp eq 4444" 

Sieve of Eratosthenes - Finding Primes Python

Much faster:

import time
def get_primes(n):
  m = n+1
  #numbers = [True for i in range(m)]
  numbers = [True] * m #EDIT: faster
  for i in range(2, int(n**0.5 + 1)):
    if numbers[i]:
      for j in range(i*i, m, i):
        numbers[j] = False
  primes = []
  for i in range(2, m):
    if numbers[i]:
      primes.append(i)
  return primes

start = time.time()
primes = get_primes(10000)
print(time.time() - start)
print(get_primes(100))

In a unix shell, how to get yesterday's date into a variable?

You have atleast 2 options

  1. Use perl:

    perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)'
    
  2. Install GNU date (it's in the sh_utils package if I remember correctly)

    date --date yesterday "+%a %d/%m/%Y" | read dt
    echo ${dt}
    
  3. Not sure if this works, but you might be able to use a negative timezone. If you use a timezone that's 24 hours before your current timezone than you can simply use date.

getResources().getColor() is deprecated

It looks like the best approach is to use:

ContextCompat.getColor(context, R.color.color_name)

eg:

yourView.setBackgroundColor(ContextCompat.getColor(applicationContext,
                            R.color.colorAccent))

This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.

How to resolve "Waiting for Debugger" message?

The Dialog Waiting for Debugger is shown if you are building a debug application or somewhere in your source code, you called Debug.waitingForDebugger();

Inside Android Studio 2.0 and above, there is an option of Attach Debugger to Android Process. It is the last menu item in the Run menu.

Screen shot of Run menu options in Android Studio

How can I move all the files from one folder to another using the command line?

Be sure to use quotes if there are spaces in the file path:

move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"

That will move the contents of C:\Users\MyName\My Old Folder\ to C:\Users\MyName\My New Folder

Processing Symbol Files in Xcode

I know that this is not a technical solution but I had my iphone connected with the computer by cable and disconnecting the device from the computer and connecting it again (by cable again) worked for me as I could not solved it with the solutions that are provided before.

How to specify HTTP error code?

You can use res.send('OMG :(', 404); just res.send(404);

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

Java: Reading integers from a file into an array

It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?

You could probably fix the code like this

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

How can I pass a member function where a free function is expected?

You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.

http://cpp.sh/9jhk3

// Example program
#include <iostream>
#include <string>

using namespace std;

typedef int FooCooker_ (int);

// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
    cout << "Cooking 10 Foo ..." << endl;
    cout << "FooCooker:" << endl;
    FooCooker (10);
}

struct Bar_ {
    Bar_ (int Foo = 0) : Foo (Foo) {};
    int cook (int Foo) {
        cout << "This Bar got " << this->Foo << endl;
        if (this->Foo >= Foo) {
            this->Foo -= Foo;
            cout << Foo << " cooked" << endl;
            return Foo;
        } else {
            cout << "Can't cook " <<  Foo << endl;
            return 0;
        }
    }
    int Foo = 0;
};

// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* BarPtr = NULL;
static int cook_in_Bar (int Foo) {
    return BarPtr->cook (Foo);
}

thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
    return Bar2Ptr->cook (Foo);
}

int main () {
  BarPtr = new Bar_ (20);
  cook_10_foo (cook_in_Bar);

  Bar2Ptr = new Bar_ (40);
  cook_10_foo (cook_in_Bar2);

  delete BarPtr;
  delete Bar2Ptr;
  return 0;
}

Please comment on any issues with this approach.

Other answers fail to call existing plain C functions: http://cpp.sh/8exun

How to read a CSV file from a URL with Python?

I am also using this approach for csv files (Python 3.6.9):

import csv
import io
import requests

r = requests.get(url)
buff = io.StringIO(r.text)
dr = csv.DictReader(buff)
for row in dr:
    print(row)

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.

SomeDate.Value.GetDateTimeFormats()[5]

GetDateTimeFormats

How to write log to file

os.Open() must have worked differently in the past, but this works for me:

f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("error opening file: %v", err)
}
defer f.Close()

log.SetOutput(f)
log.Println("This is a test log entry")

Based on the Go docs, os.Open() can't work for log.SetOutput, because it opens the file "for reading:"

func Open

func Open(name string) (file *File, err error) Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

EDIT

Moved defer f.Close() to after if err != nil check

How do I connect to an MDF database file?

Go to server explorer > Your Database > Right Click > properties > ConnectionString and copy the connection string and past the copied to connectiongstring code :)

Way to insert text having ' (apostrophe) into a SQL table

In SQL, the way to do this is to double the apostrophe:

'he doesn''t work for me'

If you are doing this programmatically, you should use an API that accepts parameters and escapes them for you, like prepared statements or similar, rather that escaping and using string concatenation to assemble a query.

How do you add Boost libraries in CMakeLists.txt?

Put this in your CMakeLists.txt file (change any options from OFF to ON if you want):

set(Boost_USE_STATIC_LIBS OFF) 
set(Boost_USE_MULTITHREADED ON)  
set(Boost_USE_STATIC_RUNTIME OFF) 
find_package(Boost 1.45.0 COMPONENTS *boost libraries here*) 

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS}) 
    add_executable(progname file1.cxx file2.cxx) 
    target_link_libraries(progname ${Boost_LIBRARIES})
endif()

Obviously you need to put the libraries you want where I put *boost libraries here*. For example, if you're using the filesystem and regex library you'd write:

find_package(Boost 1.45.0 COMPONENTS filesystem regex)

What is managed or unmanaged code in programming?

Managed code is what C#.Net, VB.Net, F#.Net etc compilers create. It runs on the CLR, which among other things offers services like garbage collection, and reference checking, and much more. So think of it as, my code is managed by the CLR.

On the other hand, unmanaged code compiles straight to machine code. It doesn't manage by CLR.

Converting java.util.Properties to HashMap<String,String>

I would use following Guava API: com.google.common.collect.Maps#fromProperties

Properties properties = new Properties();
Map<String, String> map = Maps.fromProperties(properties);

UML diagram shapes missing on Visio 2013

CTRL+N-- to open a new document.

Right Edge find "MORE SHAPES" then "SOFTWARES AND DATABASES" and finaly "SOFTWARES". All UML DIAGRAMS are available here.

Sorting hashmap based on keys

TreeMap will automatically sort in ascending order. If you want to sort in descending order, use the following code:

Copy the below code within your class and outside of the main execute method:

static class DescOrder implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {      
        return o2.compareTo(o1);
    }
    }

Then in your logic:

TreeMap<String, String> map = new TreeMap<String, String>(new DescOrder());
map.put("A", "test1");
map.put("C", "test3");
map.put("E", "test5");
map.put("B", "test2");
map.put("D", "test4");

Setting dropdownlist selecteditem programmatically

var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);

OR

foreach (var listItem in ctx.Items)
  listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);

Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!

JavaScript string with new line - but not using \n

you can use the following function:

  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
  } 

like so:

var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line<br>another line<br>another line

the source of the function is from here: http://phpjs.org/functions/nl2br:480

this imitates the nl2br function in php...

PHP PDO: charset, set names?

This is probably the most elegant way to do it.
Right in the PDO constructor call, but avoiding the buggy charset option (as mentioned above):

$connect = new PDO(
  "mysql:host=$host;dbname=$db", 
  $user, 
  $pass, 
  array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
  )
);

Works great for me.

How to create a oracle sql script spool file

With spool:

  set heading off
  set arraysize 1
  set newpage 0
  set pages 0
  set feedback off
  set echo off
  set verify off

variable cd varchar2(10);
variable d number;

 declare
 ab varchar2(10) := 'Raj';
 a number := 10;
 c number;
 begin
 c := a+10;
 select ab,c into :cd,:d from dual;
 end;

 SPOOL 
 select :cd,:d from dual;
 SPOOL OFF
 EXIT;

excel plot against a date time x series

[excel 2010] separate the date and time into separate columns and select both as X-Axis and data as graph series see http://www.79783.mrsite.com/USERIMAGES/horizontal_axis_date_and_time2.xlsx

How to declare a global variable in React?

I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:

Carrying values between functions, on the same page

In your constructor, bind your setter:

this.setSomeVariable = this.setSomeVariable.bind(this);

Then declare a function just below your constructor:

setSomeVariable(propertyTextToAdd) {
    this.setState({
        myProperty: propertyTextToAdd
    });
}

When you want to set it, call this.setSomeVariable("some value");

(You might even be able to get away with this.state.myProperty = "some value";)

When you want to get it, call var myProp = this.state.myProperty;

Using alert(myProp); should give you some value .

Extra scaffolding method to carry values across pages/components

You can assign a model to this (technically this.stores), so you can then reference it with this.state:

import Reflux from 'reflux'
import Actions from '~/actions/actions`

class YourForm extends Reflux.Store
{
    constructor()
    {
        super();
        this.state = {
            someGlobalVariable: '',
        };
        this.listenables = Actions;
        this.baseState = {
            someGlobalVariable: '',
        };
    }

    onUpdateFields(name, value) {
        this.setState({
            [name]: value,
        });
    }

    onResetFields() {
        this.setState({
           someGlobalVariable: '',
        });
    }
}
const reqformdata = new YourForm

export default reqformdata

Save this to a folder called stores as yourForm.jsx.

Then you can do this in another page:

import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'

Reflux.defineReact(React)

class SomePage extends Reflux.Component {
    constructor(props) {
        super(props);
        this.state = {
            someLocalVariable: '',
        }
        this.stores = [
            YourForm,
        ]
    }
    render() {

        const myVar = this.state.someGlobalVariable;
        return (
            <Form>
                <div>{myVar}</div>
            </Form>
        )
    }
}
export default SomePage

If you had set this.state.someGlobalVariable in another component using a function like:

setSomeVariable(propertyTextToAdd) {
    this.setState({
       myGlobalVariable: propertyTextToAdd
   });
}

that you bind in the constructor with:

this.setSomeVariable = this.setSomeVariable.bind(this);

the value in propertyTextToAdd would be displayed in SomePage using the code shown above.

Request Permission for Camera and Library in iOS 10 - Info.plist

File: Info.plist

For Camera:

<key>NSCameraUsageDescription</key>
<string>You can take photos to document your job.</string>

For Photo Library, you will want this one to allow app user to browse the photo library.

<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach to reports.</string>

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";

Spring @Transactional - isolation, propagation

I have run outerMethod,method_1 and method_2 with different propagation mode.

Below is the output for different propagation mode.

  • Outer Method

    @Transactional
    @Override
    public void outerMethod() {
        customerProfileDAO.method_1();
        iWorkflowDetailDao.method_2();
    }
    
  • Method_1

    @Transactional(propagation=Propagation.MANDATORY)
    public void method_1() {
        Session session = null;
        try {
            session = getSession();
            Temp entity = new Temp(0l, "XXX");
            session.save(entity);
            System.out.println("Method - 1 Id "+entity.getId());
        } finally {
            if (session != null && session.isOpen()) {
            }
        }
    }
    
  • Method_2

    @Transactional()
    @Override
    public void method_2() {
        Session session = null;
        try {
            session = getSession();
            Temp entity = new Temp(0l, "CCC");
            session.save(entity);
            int i = 1/0;
            System.out.println("Method - 2 Id "+entity.getId());
        } finally {
            if (session != null && session.isOpen()) {
            }
        }
    }
    
      • outerMethod - Without transaction
      • method_1 - Propagation.MANDATORY) -
      • method_2 - Transaction annotation only
      • Output: method_1 will throw exception that no existing transaction
      • outerMethod - Without transaction
      • method_1 - Transaction annotation only
      • method_2 - Propagation.MANDATORY)
      • Output: method_2 will throw exception that no existing transaction
      • Output: method_1 will persist record in database.
      • outerMethod - With transaction
      • method_1 - Transaction annotation only
      • method_2 - Propagation.MANDATORY)
      • Output: method_2 will persist record in database.
      • Output: method_1 will persist record in database. -- Here Main Outer existing transaction used for both method 1 and 2
      • outerMethod - With transaction
      • method_1 - Propagation.MANDATORY) -
      • method_2 - Transaction annotation only and throws exception
      • Output: no record persist in database means rollback done.
      • outerMethod - With transaction
      • method_1 - Propagation.REQUIRES_NEW)
      • method_2 - Propagation.REQUIRES_NEW) and throws 1/0 exception
      • Output: method_2 will throws exception so method_2 record not persisted.
      • Output: method_1 will persist record in database.
      • Output: There is no rollback for method_1

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

Explicitly set column value to null SQL Developer

It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).

I came upon this post when I wanted to know the same thing.

Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.

So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?

I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.

Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.

Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:

Tools->Preferences->Advanced->Display Null Using Background Color

or even the VALUE it shows when it's null:

Tools->Preferences->Advanced->Display Null Value As

Hope that helps in your transition.

How to get current available GPUs in tensorflow?

The accepted answer gives you the number of GPUs but it also allocates all the memory on those GPUs. You can avoid this by creating a session with fixed lower memory before calling device_lib.list_local_devices() which may be unwanted for some applications.

I ended up using nvidia-smi to get the number of GPUs without allocating any memory on them.

import subprocess

n = str(subprocess.check_output(["nvidia-smi", "-L"])).count('UUID')

How to fix "set SameSite cookie to none" warning?

I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)

EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):

$cookie_options = array(
  'expires' => time() + 60*60*24*30,
  'path' => '/',
  'domain' => '.domain.com', // leading dot for compatibility or use subdomain
  'secure' => true, // or false
  'httponly' => false, // or false
  'samesite' => 'None' // None || Lax || Strict
);

setcookie('cors-cookie', 'my-site-cookie', $cookie_options);

If you have PHP 7.2 or lower (as Robert's answered below):

setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):

setcookie('cookieName', 'cookieValue', [
  'expires' => time()+(7*24*3600,
  'path' => '/',
  'domain' => 'domain.com',
  'samesite' => 'None',
  'secure' => true,
  'httponly' => true
]);

Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":

chrome://flags/#cookie-deprecation-messages

See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies too.

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Editing dictionary values in a foreach loop

Setting a value in a dictionary updates its internal "version number" - which invalidates the iterator, and any iterator associated with the keys or values collection.

I do see your point, but at the same time it would be odd if the values collection could change mid-iteration - and for simplicity there's only one version number.

The normal way of fixing this sort of thing is to either copy the collection of keys beforehand and iterate over the copy, or iterate over the original collection but maintain a collection of changes which you'll apply after you've finished iterating.

For example:

Copying keys first

List<string> keys = new List<string>(colStates.Keys);
foreach(string key in keys)
{
    double percent = colStates[key] / TotalCount;    
    if (percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

Or...

Creating a list of modifications

List<string> keysToNuke = new List<string>();
foreach(string key in colStates.Keys)
{
    double percent = colStates[key] / TotalCount;    
    if (percent < 0.05)
    {
        OtherCount += colStates[key];
        keysToNuke.Add(key);
    }
}
foreach (string key in keysToNuke)
{
    colStates[key] = 0;
}

Meaning of *& and **& in C++

To understand those phrases let's look at the couple of things:

typedef double Foo;
void fooFunc(Foo &_bar){ ... }

So that's passing a double by reference.

typedef double* Foo;
void fooFunc(Foo &_bar){ ... }

now it's passing a pointer to a double by reference.

typedef double** Foo;
void fooFunc(Foo &_bar){ ... }

Finally, it's passing a pointer to a pointer to a double by reference. If you think in terms of typedefs like this you'll understand the proper ordering of the & and * plus what it means.

Unicode characters in URLs

Not sure if it is a good idea, but as mentioned in other comments and as I interpret it, many Unicode chars are valid in HTML5 URLs.

E.g., href docs say http://www.w3.org/TR/html5/links.html#attr-hyperlink-href:

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

Then the definition of "valid URL" points to http://url.spec.whatwg.org/, which defines URL code points as:

ASCII alphanumeric, "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", and code points in the ranges U+00A0 to U+D7FF, U+E000 to U+FDCF, U+FDF0 to U+FFFD, U+10000 to U+1FFFD, U+20000 to U+2FFFD, U+30000 to U+3FFFD, U+40000 to U+4FFFD, U+50000 to U+5FFFD, U+60000 to U+6FFFD, U+70000 to U+7FFFD, U+80000 to U+8FFFD, U+90000 to U+9FFFD, U+A0000 to U+AFFFD, U+B0000 to U+BFFFD, U+C0000 to U+CFFFD, U+D0000 to U+DFFFD, U+E1000 to U+EFFFD, U+F0000 to U+FFFFD, U+100000 to U+10FFFD.

The term "URL code points" is then used in a few parts of the parsing algorithm, e.g. for the relative path state:

If c is not a URL code point and not "%", parse error.

Also the validator http://validator.w3.org/ passes for URLs like "??", and does not pass for URLs with characters like spaces "a b"

Related: Which characters make a URL invalid?

Sort array by value alphabetically php

Note that sort() operates on the array in place, so you only need to call

sort($a);
doSomething($a);

This will not work;

$a = sort($a);
doSomething($a);

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

How to add anything in <head> through jquery/javascript?

You can use innerHTML to just concat the extra field string;

document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'

However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.

I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.

design a stack such that getMinimum( ) should be O(1)

class FastStack {

    private static class StackNode {
        private Integer data;
        private StackNode nextMin;

        public StackNode(Integer data) {
            this.data = data;
        }

        public Integer getData() {
            return data;
        }

        public void setData(Integer data) {
            this.data = data;
        }

        public StackNode getNextMin() {
            return nextMin;
        }

        public void setNextMin(StackNode nextMin) {
            this.nextMin = nextMin;
        }

    }

    private LinkedList<StackNode> stack = new LinkedList<>();

    private StackNode currentMin = null;

    public void push(Integer item) {
        StackNode node = new StackNode(item);
        if (currentMin == null) {
            currentMin = node;
            node.setNextMin(null);
        } else if (item < currentMin.getData()) {
            StackNode oldMinNode = currentMin;
            node.setNextMin(oldMinNode);
            currentMin = node;
        }

        stack.addFirst(node);
    }

    public Integer pop() {
        if (stack.isEmpty()) {
            throw new EmptyStackException();
        }
        StackNode node = stack.peek();
        if (currentMin == node) {
            currentMin = node.getNextMin();
        }
        stack.removeFirst();
        return node.getData();
    }

    public Integer getMinimum() {
        if (stack.isEmpty()) {
            throw new NoSuchElementException("Stack is empty");
        }
        return currentMin.getData();
    }
}

How to get body of a POST in php?

return value in array

 $data = json_decode(file_get_contents('php://input'), true);

Multiline input form field using Bootstrap

The answer by Nick Mitchinson is for Bootstrap version 2.

If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-6">
            <textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
        </div>
    </div>
</div>

Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.

Deep copy, shallow copy, clone

The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.

As an example, let's say you have a person class:

class Person {
    String name;
    List<String> emailAddresses
}

How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses in the new object. But if you modified the contents of the emailAddresses list, you would be modifying the list in both copies (since that's how object references work).

A deep copy would mean that you recursively copy every member, so you would need to create a new List for the new Person, and then copy the contents from the old to the new object.

Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.

Import CSV file as a pandas DataFrame

pandas to the rescue:

import pandas as pd
print pd.read_csv('value.txt')

        Date    price  factor_1  factor_2
0  2012-06-11  1600.20     1.255     1.548
1  2012-06-12  1610.02     1.258     1.554
2  2012-06-13  1618.07     1.249     1.552
3  2012-06-14  1624.40     1.253     1.556
4  2012-06-15  1626.15     1.258     1.552
5  2012-06-16  1626.15     1.263     1.558
6  2012-06-17  1626.15     1.264     1.572

This returns pandas DataFrame that is similar to R's.

How to set session attribute in java?

Java file : Jclass.java

package Jclasspackage

public class Jclass {

    public String uname ;
    /**
     * @return the uname
     */
    public String getUname() {
        return uname;
    }

    /**
     * @param uname the uname to set
     */
    public void setUname(String uname) {
        this.uname = uname;
    }

    public Jclass() {
        this.uname = null;
    }

    public static void main(String[] args) {

    }
}

JSP file: sample.jsp

    <%@ page language="java"
    import="java.util.*,java.io.*"
    pageEncoding="ISO-8859-1"%>

<jsp:directive.page import="Jclasspackage.Jclass.java" />   
<% Jclass jc = new Jclass();
String username = (String)request.getAttribute("un")
jc.setUname(username);
%>

-----------------

In this way you can access the username in the java file using "this.username" in the class

Delete empty lines using sed

This works in awk as well.

awk '!/^$/' file
xxxxxx
yyyyyy
zzzzzz

Advantages of using display:inline-block vs float:left in CSS

In 3 words: inline-block is better.

Inline Block

The only drawback to the display: inline-block approach is that in IE7 and below an element can only be displayed inline-block if it was already inline by default. What this means is that instead of using a <div> element you have to use a <span> element. It's not really a huge drawback at all because semantically a <div> is for dividing the page while a <span> is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block and text-align:right is trying to accomplish than a float:left or float:right statement. My favorite benefit of the inline-block approach is that it's easy to use vertical-align: middle, line-height and text-align: center to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.

Float

The reason that using the float method is not suited for layout of your page is because the float CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.

Any white space problems mentioned in the link above could easily be fixed with the white-space CSS property.

Edit:

SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:

If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.

Don’t be fooled. You’re being brainwashed.

http://www.sitepoint.com/give-floats-the-flick-in-css-layouts/

2015 Update - Flexbox is a good alternative for modern browsers:

.container {
  display: flex; /* or inline-flex */
}

.item {
  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}

More info

Dec 21, 2016 Update

Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.

Pull request #21389

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

Using %f with strftime() in Python to get microseconds

With Python's time module you can't get microseconds with %f.

For those who still want to go with time module only, here is a workaround:

now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))

You should get something like 2017-01-16 16:42:34.625 EET (yes, I use milliseconds as it's fairly enough).

To break the code into details, paste the below code into a Python console:

import time

# Get current timestamp
now = time.time()

# Debug now
now
print now
type(now)

# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)

# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)

# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec

# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp

For clarification purposes, I also paste my Python 2.7.12 result here:

>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>

What is (functional) reactive programming?

This article by Andre Staltz is the best and clearest explanation I've seen so far.

Some quotes from the article:

Reactive programming is programming with asynchronous data streams.

On top of that, you are given an amazing toolbox of functions to combine, create and filter any of those streams.

Here's an example of the fantastic diagrams that are a part of the article:

Click event stream diagram

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

Remove a prefix from a string

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

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

How do you determine the ideal buffer size when using FileInputStream?

Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.

Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

Is there a difference between x++ and ++x in java?

Yes.

public class IncrementTest extends TestCase {

    public void testPreIncrement() throws Exception {
        int i = 0;
        int j = i++;
        assertEquals(0, j);
        assertEquals(1, i);
    }

    public void testPostIncrement() throws Exception {
        int i = 0;
        int j = ++i;
        assertEquals(1, j);
        assertEquals(1, i);
    }
}

Removing elements with Array.map in JavaScript

Array Filter method

_x000D_
_x000D_
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
_x000D_
_x000D_

Parsing JSON from XmlHttpRequest.responseJSON

You can simply set xhr.responseType = 'json';

_x000D_
_x000D_
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
  if (this.status == 200) {_x000D_
    console.log('response', this.response); // JSON response  _x000D_
  }_x000D_
};_x000D_
xhr.send();_x000D_
  
_x000D_
_x000D_
_x000D_

Documentation for responseType

window.close() doesn't work - Scripts may close only the windows that were opened by it

You can't close a current window or any window or page that is opened using '_self' But you can do this

var customWindow = window.open('', '_blank', '');
    customWindow.close();

Malformed String ValueError ast.literal_eval() with String representation of Tuple

I know this is an old question, but I think found a very simple answer, in case anybody needs it.

If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.

You can use a simple function:

    def doubleStringify(a):
        b = "\'" + a + "\'"
        return b

Or probably more suitable for this example:

    def perfectEval(anonstring):
        try:
            ev = ast.literal_eval(anonstring)
            return ev
        except ValueError:
            corrected = "\'" + anonstring + "\'"
            ev = ast.literal_eval(corrected)
            return ev

Java Replace Line In Text File

I was going to answer this question. Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here.

Keeping in mind that you have to re-write the text file. First I read the entire file, and store it in a string. Then I store each line as a index of a string array, ex line one = array index 0. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string. Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. below is the code I used.

public class App {

public static void main(String[] args) {

    String file = "file.txt";
    String newLineContent = "Hello my name is bob";
    int lineToBeEdited = 3;

    ChangeLineInFile changeFile = new ChangeLineInFile();
    changeFile.changeALineInATextFile(file, newLineContent, lineToBeEdited);



}

}

And the class.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class ChangeLineInFile {

public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
        String content = new String();
        String editedContent = new String();
        content = readFile(fileName);
        editedContent = editLineInContent(content, newLine, lineNumber);
        writeToFile(fileName, editedContent);

    }

private static int numberOfLinesInFile(String content) {
    int numberOfLines = 0;
    int index = 0;
    int lastIndex = 0;

    lastIndex = content.length() - 1;

    while (true) {

        if (content.charAt(index) == '\n') {
            numberOfLines++;

        }

        if (index == lastIndex) {
            numberOfLines = numberOfLines + 1;
            break;
        }
        index++;

    }

    return numberOfLines;
}

private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
    String[] array = new String[lines];
    int index = 0;
    int tempInt = 0;
    int startIndext = 0;
    int lastIndex = content.length() - 1;

    while (true) {

        if (content.charAt(index) == '\n') {
            tempInt++;

            String temp2 = new String();
            for (int i = 0; i < index - startIndext; i++) {
                temp2 += content.charAt(startIndext + i);
            }
            startIndext = index;
            array[tempInt - 1] = temp2;

        }

        if (index == lastIndex) {

            tempInt++;

            String temp2 = new String();
            for (int i = 0; i < index - startIndext + 1; i++) {
                temp2 += content.charAt(startIndext + i);
            }
            array[tempInt - 1] = temp2;

            break;
        }
        index++;

    }

    return array;
}

private static String editLineInContent(String content, String newLine, int line) {

    int lineNumber = 0;
    lineNumber = numberOfLinesInFile(content);

    String[] lines = new String[lineNumber];
    lines = turnFileIntoArrayOfStrings(content, lineNumber);

    if (line != 1) {
        lines[line - 1] = "\n" + newLine;
    } else {
        lines[line - 1] = newLine;
    }
    content = new String();

    for (int i = 0; i < lineNumber; i++) {
        content += lines[i];
    }

    return content;
}

private static void writeToFile(String file, String content) {

    try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
        writer.write(content);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static String readFile(String filename) {
    String content = null;
    File file = new File(filename);
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return content;
}

}

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.

What is Model in ModelAndView from Spring MVC?

The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.

Example 1

If you have...

return new ModelAndView("welcomePage","WelcomeMessage","Welcome!");

... then in your jsp, to display the message, you will do:-

Hello Stranger! ${WelcomeMessage} // displays Hello Stranger! Welcome!

Example 2

If you have...

MyBean bean = new MyBean();
bean.setName("Mike!");
bean.setMessage("Meow!");

return new ModelAndView("welcomePage","model",bean);

... then in your jsp, you can do:-

Hello ${model.name}! {model.message} // displays Hello Mike! Meow!

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

I restarted my phone after uninstalling the app and it worked

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Is there any way to wait for AJAX response and halt execution?

Method 1:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        },
        complete: function(){
              // do the job here
         }
    });
}

var response = functABC();

Method 2

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async: false,
        success: function(data) {
            return data;
        }        
    });

   // do the job here
}

css h1 - only as wide as the text

Somewhat like the other suggestions you could use the following code. However, if you do go the margin: 0 auto; route I'd recommend having the margin for the top and bottom of an H1 be set to something other than 0. So, perhaps margin: 6px auto; or something.

.centercol h1{
    display: inline-block;
    color: #006bb6;
    font-weight: normal;
    font-size: 18px;
    padding:3px 3px 3px 6px;
    border-left:3px solid #c6c1b8;
    background:#f2efe9;
    display:block;
}

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

I just had the exact same issue and it was down to me being completely stupid. I had disabled all of the form fields (rather than just the submit button) via javascript before submitting said form! This, of course, resulted in the all the form elements not being submitted (including the hidden _token field) which in turn brought up the 419 error!

I hope this helps someone from a few hours of head scratching!

Disabled form inputs do not appear in the request

Get list of a class' instance methods

To get only own methods, and exclude inherited ones:

From within the instance:

self.methods - self.class.superclass.instance_methods

From outside:

TestClass.instance_methods - TestClass.superclass.instance_methods

Add it to the class:

class TestClass
  class << self
    def own_methods
      self.instance_methods - self.superclass.instance_methods
    end
  end
end

TestClass.own_methods
=> [:method1, :method2, :method3]

(with ruby 2.6.x)

Iterating over dictionaries using 'for' loops

I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:

d = {'x': 1, 'y': 2, 'z': 3} 
for i, (key, value) in enumerate(d.items()):
   print(i, key, value)

Note that the parentheses around the key, value are important, without them, you'd get an ValueError "not enough values to unpack".

Sending event when AngularJS finished loading

If you are using Angular UI Router, you can listen for the $viewContentLoadedevent.

"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link

$scope.$on('$viewContentLoaded', 
function(event){ ... });

Best way to remove duplicate entries from a data table

Do dtEmp on your current working DataTable:

DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);

It's nice.

Best way to format if statement with multiple conditions

The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.

I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".

If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line

Eg.

if user.hasPermission(Admin()) {
   if (x >= 0) && (x < 100) {
      // do something
   }
}

Why I got " cannot be resolved to a type" error?

I had wrong package names:

main.java.hello and main.test.hello rather than com.blabla.hello.

  1. I renamed my src-folder to src/main/java and created another src-folder src/test/java.
  2. I renamed my package within src/main/java to com.blabla.hello
  3. I created another package with the same name in src/test/java.

How to convert decimal to hexadecimal in JavaScript

Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the # elsewhere for HTML/CSS):

function rgb2hex(r,g,b) {
    if (g !== undefined)
        return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
    else
        return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}

Bash scripting missing ']'

I got this error while trying to use the && operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

Java - Check Not Null/Empty else assign default value

Use Java 8 Optional (no filter needed):

public static String orElse(String defaultValue) {
  return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}

"Unable to acquire application service" error while launching Eclipse

I received this message trying to run STS 3.7.0 on java 6 jdk, after pointing to java jdk 7 (-vm param in STS.ini) the issue disappeared.

Do the parentheses after the type name make a difference with new?

Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • In C++1998 there are 2 types of initialization: zero and default
  • In C++2003 a 3rd type of initialization, value initialization was added.

Assume:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

In a C++98 compiler, the following should occur:

  • new A - indeterminate value
  • new A() - zero-initialize

  • new B - default construct (B::m is uninitialized)

  • new B() - default construct (B::m is uninitialized)

  • new C - default construct (C::m is zero-initialized)

  • new C() - default construct (C::m is zero-initialized)

In a C++03 conformant compiler, things should work like so:

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.

  • new B - default-initializes (leaves B::m uninitialized)

  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

  • new C - default-initializes C, which calls the default ctor.

  • new C() - value-initializes C, which calls the default ctor.

So in all versions of C++ there's a difference between new A and new A() because A is a POD.

And there's a difference in behavior between C++98 and C++03 for the case new B().

This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

How can I update my ADT in Eclipse?

Reason to that is with the new update, they changed the URL for the Android Developer Tools update site to require HTTPS. If you are updating ADT, make sure you use HTTPS in the URL for the Android Developer Tools update site.

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

You can use Named Sections.

_Layout.cshtml

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

_SomeView.cshtml

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

What is the meaning of the word logits in TensorFlow?

Summary

In context of deep learning the logits layer means the layer that feeds in to softmax (or other such normalization). The output of the softmax are the probabilities for the classification task and its input is logits layer. The logits layer typically produces values from -infinity to +infinity and the softmax layer transforms it to values from 0 to 1.

Historical Context

Where does this term comes from? In 1930s and 40s, several people were trying to adapt linear regression to the problem of predicting probabilities. However linear regression produces output from -infinity to +infinity while for probabilities our desired output is 0 to 1. One way to do this is by somehow mapping the probabilities 0 to 1 to -infinity to +infinity and then use linear regression as usual. One such mapping is cumulative normal distribution that was used by Chester Ittner Bliss in 1934 and he called this "probit" model, short for "probability unit". However this function is computationally expensive while lacking some of the desirable properties for multi-class classification. In 1944 Joseph Berkson used the function log(p/(1-p)) to do this mapping and called it logit, short for "logistic unit". The term logistic regression derived from this as well.

The Confusion

Unfortunately the term logits is abused in deep learning. From pure mathematical perspective logit is a function that performs above mapping. In deep learning people started calling the layer "logits layer" that feeds in to logit function. Then people started calling the output values of this layer "logit" creating the confusion with logit the function.

TensorFlow Code

Unfortunately TensorFlow code further adds in to confusion by names like tf.nn.softmax_cross_entropy_with_logits. What does logits mean here? It just means the input of the function is supposed to be the output of last neuron layer as described above. The _with_logits suffix is redundant, confusing and pointless. Functions should be named without regards to such very specific contexts because they are simply mathematical operations that can be performed on values derived from many other domains. In fact TensorFlow has another similar function sparse_softmax_cross_entropy where they fortunately forgot to add _with_logits suffix creating inconsistency and adding in to confusion. PyTorch on the other hand simply names its function without these kind of suffixes.

Reference

The Logit/Probit lecture slides is one of the best resource to understand logit. I have also updated Wikipedia article with some of above information.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

What is the difference between DSA and RSA?

With reference to man ssh-keygen, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.

In conclusion, a 2048 bit RSA key is currently the best choice.

MORE PRECAUTIONS TO TAKE

Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.

To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.

Add Facebook Share button to static HTML page

This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.

Here is an example:

<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
    <img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>

Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.

Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.

Setting max width for body using Bootstrap

In responsive.less, you can comment out the line that imports responsive-1200px-min.less.

// Large desktops

@import "responsive-1200px-min.less";

Like so:

// Large desktops

// @import "responsive-1200px-min.less";

R - argument is of length zero in if statement

The simplest solution to the problem is to change your for loop statement :

Instead of using

      for (i in **0**:n))

Use

      for (i in **1**:n))

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

Use of PUT vs PATCH methods in REST API real life scenarios

In my humble opinion, idempotence means:

  • PUT:

I send a compete resource definition, so - the resulting resource state is exactly as defined by PUT params. Each and every time I update the resource with the same PUT params - the resulting state is exactly the same.

  • PATCH:

I sent only part of the resource definition, so it might happen other users are updating this resource's OTHER parameters in a meantime. Consequently - consecutive patches with the same parameters and their values might result with different resource state. For instance:

Presume an object defined as follows:

CAR: - color: black, - type: sedan, - seats: 5

I patch it with:

{color: 'red'}

The resulting object is:

CAR: - color: red, - type: sedan, - seats: 5

Then, some other users patches this car with:

{type: 'hatchback'}

so, the resulting object is:

CAR: - color: red, - type: hatchback, - seats: 5

Now, if I patch this object again with:

{color: 'red'}

the resulting object is:

CAR: - color: red, - type: hatchback, - seats: 5

What is DIFFERENT to what I've got previously!

This is why PATCH is not idempotent while PUT is idempotent.

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

FPDF utf-8 encoding (HOW-TO)

There is an extension of FPDF called mPDF that allows Unicode fonts.

http://www.mpdf1.com/mpdf/index.php

Razor View throwing "The name 'model' does not exist in the current context"

In my case, I removed web.config file from Views folder by accident. I added it back , and it was OK.

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

I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.

The following will create an iterator that yields five, and then every item in some_list.

def __iter__(self):
   yield 5
   yield from some_list

Pre-3.3, yield from didn't exist, so you would have to do:

def __iter__(self):
   yield 5
   for x in some_list:
      yield x

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

Same as the other answers (disabled isn't sent to the server, readonly is) but some browsers prevent highlighting of a disabled form, while read-only can still be highlighted (and copied).

http://www.w3schools.com/tags/att_input_disabled.asp

http://www.w3schools.com/tags/att_input_readonly.asp

A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.

Rails 4: how to use $(document).ready() with turbo-links

Here's what I have done to ensure things aren't executed twice:

$(document).on("page:change", function() {
     // ... init things, just do not bind events ...
     $(document).off("page:change");
});

I find using the jquery-turbolinks gem or combining $(document).ready and $(document).on("page:load") or using $(document).on("page:change") by itself behaves unexpectedly--especially if you're in development.

How to make a script wait for a pressed key?

I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:

import msvcrt
c = msvcrt.getch()
print 'you entered', c

mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if there's a corresponding curses function). Under UNIX, there is the curses package, but not sure if you can use it without using it for all of the screen output. This code works under UNIX:

import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()

Note that curses.getch() returns the ordinal of the key pressed so to make it have the same output I had to cast it.

Groovy method with optional parameters

Can't be done as it stands... The code

def myMethod(pParm1='1', pParm2='2'){
    println "${pParm1}${pParm2}"
}

Basically makes groovy create the following methods:

Object myMethod( pParm1, pParm2 ) {
    println "$pParm1$pParm2"
}

Object myMethod( pParm1 ) {
    this.myMethod( pParm1, '2' )
}

Object myMethod() {
    this.myMethod( '1', '2' )
}

One alternative would be to have an optional Map as the first param:

def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
    println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}

myMethod( 'a', 'b' )                // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

You must give a name to your submit button

<input type="submit" value"Submit" name="login">

Then you can call the button with $_POST['login']

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

How can I get onclick event on webview in android?

I have tried almost all the answers and some of them almost worked for me but none of these answers work perfectly. So here is my solution. For this solution, you will need to add onclick attribute in the HTML body tag. So if you can not modify the HTML file then this solution won't work for you.

Step 1: add onclick attribute in the HTML body tag like this:

<body onclick="ok.performClick(this.value);">
    <h1>This is heading 1</h1>
    <p>This is para 1</p>
</body>

Step 2: implement addJavascriptInterface in your app to handle click listener:

webView.addJavascriptInterface(new Object() {
    @JavascriptInterface
    public void performClick(String string) {
        handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 0);
    }
}, "ok");

Step 3: We can not perform any action on main thread from performClick method so need to add Handler class:

private final Handler handler = new Handler(this); // class-level variable 
private static final int CLICK_ON_WEBVIEW = 1; // class-level variable 

implement Handler.Callback to your class and the override handleMessage

@Override
public boolean handleMessage(Message message) {
    if (message.what == CLICK_ON_WEBVIEW) {
        Toast.makeText(getActivity(), "WebView clicked", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

In Tkinter is there any way to make a widget not visible?

I was not using grid or pack.
I used just place for my widgets as their size and positioning was fixed.
I wanted to implement hide/show functionality on frame.
Here is demo

from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
    graph_state_chosen=show_graph_checkbox_value.get()
    if graph_state_chosen==0:
        frame.place_forget()
    else:
        frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()

Note that in above example when 'show graph' is ticked then there is vertical scrollbar.
Graph disappears when checkbox is unselected.
I was fitting some bar graph in that area which I have not shown to keep example simple.
Most important thing to learn from above is the use of frame.place_forget() to hide and frame.place(x=x_pos,y=y_pos) to show back the content.

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

filter items in a python dictionary where keys contain a specific string

Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.

If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:

I'm using iteritems() since you tagged your question with

results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])

Now the result will be in a list with some_function applied to each key/value pair of the dictionary, that has foo in its key.

If you just want to deal with the values and ignore the keys, just change the list comprehension:

results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])

some_function can be any callable, so a lambda would work as well:

results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])

The inner list is actually not required, as you can pass a generator expression to map as well:

>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]

How to distinguish between left and right mouse click with jQuery

$("body").on({
    click: function(){alert("left click");},
    contextmenu: function(){alert("right click");}   
});

How to pass parameters to a partial view in ASP.NET MVC?

Just:

@Html.Partial("PartialName", Model);

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);

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

Add FormsModule in Imports Array.
i.e

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

Or this can be done without using [(ngModel)] by using

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">

instead of

<input [(ngModel)]="hero.name" placeholder="Name">

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

In case anyone else comes by this issue, the default port on MAMP for mysql is 8889, but the port that php expects to use for mysql is 3306. So you need to open MAMP, go to preferences, and change the MAMP mysql port to 3306, then restart the mysql server. Now the connection should be successful with host=localhost, user=root, pass=root.

How do I use sudo to redirect output to a location I don't have permission to write to?

The problem is that the command gets run under sudo, but the redirection gets run under your user. This is done by the shell and there is very little you can do about it.

sudo command > /some/file.log
`-----v-----'`-------v-------'
   command       redirection

The usual ways of bypassing this are:

  • Wrap the commands in a script which you call under sudo.

    If the commands and/or log file changes, you can make the script take these as arguments. For example:

    sudo log_script command /log/file.txt
    
  • Call a shell and pass the command line as a parameter with -c

    This is especially useful for one off compound commands. For example:

    sudo bash -c "{ command1 arg; command2 arg; } > /log/file.txt"
    

get the value of "onclick" with jQuery?

I'm not quite sure how to do this in jQuery... but this works:

var x = document.getElementById('google').attributes;
for (var i in x) {
 if (x[i].name == "onclick") alert(x[i].firstChild.data);
}

but like Harshath said it would be better if you used event listeners, as removing and adding this function back into the onclick event may be troublesome.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

Make sure that the folder name does not contain .c extension. When I removed the .c extension in my folder name it worked automatically.

how to display none through code behind

try this

<div id="login_div" runat="server">

and on the code behind.

login_div.Style.Add("display", "none");

.htaccess redirect www to non-www with SSL/HTTPS

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy

Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS

Done in this order, it follows logic and no error occurs.

HERE is my FULL version in side htaccess with WordPress:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Unix's 'ls' sort by name

You can try:

ls -lru

-u with -lt: sort by, and show, access time;

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

How to use Ajax.ActionLink?

@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Then add this code to your View:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")

Is it acceptable and safe to run pip install under sudo?

I had a problem installing virtualenvwrapper after successfully installing virtualenv.

My terminal complained after I did this:

pip install virtualenvwrapper

So, I unsuccessfully tried this (NOT RECOMMENDED):

sudo pip install virtualenvwrapper

Then, I successfully installed it with this:

pip install --user virtualenvwrapper

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

You can use these steps to import the key to an existing keystore. The instructions are combined from answers in this thread and other sites. These instructions worked for me (the java keystore):

  1. Run

openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root

(If required put the -chain option. Putting that failed for me). This will ask for the password - you must give the correct password else you will get an error (heading error or padding error etc).

  1. It will ask you to enter a new password - you must enter a password here - enter anything but remember it. (Let us assume you enter Aragorn).
  2. This will create the server.p12 file in the pkcs format.
  3. Now to import it into the *.jks file run:
    keytool -importkeystore -srckeystore server.p12 -srcstoretype PKCS12 -destkeystore yourexistingjavakeystore.jks -deststoretype JKS -deststorepass existingjavastorepassword -destkeypass existingjavastorepassword
    (Very important - do not leave out the deststorepass and the destkeypass parameters.)
  4. It will ask you for the src key store password. Enter Aragorn and hit enter. The certificate and key is now imported into your existing java keystore.

Query to list all users of a certain group

For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName -- to use the query (&(objectCategory=group)(CN=GroupCN)). This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.

The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499 attribute to be returned, then for the member;range=1500-2999 attribute.

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Shorten string without cutting words in JavaScript

shorten(str, maxLen, appendix, separator = ' ') {
if (str.length <= maxLen) return str;
let strNope = str.substr(0, str.lastIndexOf(separator, maxLen));
return (strNope += appendix);

}

var s= "this is a long string and I cant explain all"; shorten(s, 10, '...')

/* "this is .." */

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Note that the mode of opening files is 'a' or some other have alphabet 'a' will also make error because of the overwritting.

pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')

UICollectionView spacing margins

To put space between CollectionItems use this

write this two Line in viewdidload

UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(<CGFloat top>, <CGFloat left>, <CGFloat bottom>, <CGFloat right>)

What's the difference between a null pointer and a void pointer?

Usually a null pointer (which can be of any type, including a void pointer !) points to:

  • the address 0, against which most CPU instructions sets can do a very fast compare-and-branch (to check for uninitialized or invalid pointers, for instance) with optimal code size/performance for the ISA.

  • an address that's illegal for user code to access (such as 0x00000000 in many cases), so that if a code actually tries to access data at or near this address, the OS or debugger can easily stop or trap a program with this bug.

A void pointer is usually a method of cheating or turning-off compiler type checking, for instance if you want to return a pointer to one type, or an unknown type, to use as another type. For instance malloc() returns a void pointer to a type-less chunk of memory, the type of which you can cast to later use as a pointer to bytes, short ints, double floats, typePotato's, or whatever.

'Static readonly' vs. 'const'

My preference is to use const whenever I can, which, as mentioned in previous answers, is limited to literal expressions or something that does not require evaluation.

If I hit up against that limitation, then I fallback to static readonly, with one caveat. I would generally use a public static property with a getter and a backing private static readonly field as Marc mentions here.

Want to move a particular div to right

This will do the job:

_x000D_
_x000D_
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
_x000D_
_x000D_

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

How do I check if a column is empty or null in MySQL?

Check for null

$column is null
isnull($column)

Check for empty

$column != ""

However, you should always set NOT NULL for column,
mysql optimization can handle only one IS NULL level

What is the difference between a hash join and a merge join (Oracle RDBMS )?

A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.

A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.

(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).

The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:

  1. The size of each hash table is reduced, hence reducing the maximum amount of memory required and potentially removing the need for the operation to require temporary disk space.
  2. For parallel query operations the amount of inter-process messaging is vastly reduced, reducing CPU usage and improving performance, as each hash join can be performed by one pair of PQ processes.
  3. For non-parallel query operations the memory requirement is reduced by a factor of n, and the first rows are projected from the query earlier.

You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.

In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.

This topic is very well covered in the documentation.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523

12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm

Auto-increment primary key in SQL tables

Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):

CREATE TABLE "dbo"."TableName"
(
   id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
   name varchar(20),
);

the insert statement should list all columns except the id column (it will be filled with autoincremented value):

INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');

and the result of

SELECT id, name FROM "dbo"."TableName";

will be

id    name
--------------------------
1     alpha
2     beta