Programs & Examples On #Elementname

Gets or sets the name of the element to use as the wpf binding source object.

Implement Validation for WPF TextBoxes

When I needed to do this, I followed Microsoft's example using Binding.ValidationRules and it worked first time.

See their article, How to: Implement Binding Validation: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-binding-validation?view=netframeworkdesktop-4.8

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

TypeScript: casting HTMLElement

Rather than using a type assertion, type guard, or any to work around the issue, a more elegant solution would be to use generics to indicate the type of element you're selecting.

Unfortunately, getElementsByName is not generic, but querySelector and querySelectorAll are. (querySelector and querySelectorAll are also far more flexible, and so might be preferable in most cases.)

If you pass a tag name alone into querySelector or querySelectorAll, it will automatically be typed properly due to the following line in lib.dom.d.ts:

querySelector<K extends keyof HTMLElementTagNameMap>(selectors: K): HTMLElementTagNameMap[K] | null;

For example, to select the first script tag on the page, as in your question, you can do:

const script = document.querySelector('script')!;

And that's it - TypeScript can now infer that script is now an HTMLScriptElement.

Use querySelector when you need to select a single element. If you need to select multiple elements, use querySelectorAll. For example:

document.querySelectorAll('script')

results in a type of NodeListOf<HTMLScriptElement>.

If you need a more complicated selector, you can pass a type parameter to indicate the type of the element you're going to select. For example:

const ageInput = document.querySelector<HTMLInputElement>('form input[name="age"]')!;

results in ageInput being typed as an HTMLInputElement.

Serialize Property as Xml Attribute in Element

Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

<SomeModel SomeStringElementName="testData"> 
</SomeModel> 

The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

// TODO: make the class generic so that an int or string can be used.
[Serializable]  
public class SerializationClass
{
    public SerializationClass(string value)
    {
        this.Value = value;
    }

    [XmlAttribute("value")]
    public string Value { get; }
}


[Serializable]                     
public class SomeModel                     
{                     
    [XmlIgnore]                     
    public string SomeString { get; set; }                     

    [XmlIgnore]                      
    public int SomeInfo { get; set; }  

    [XmlElement]
    public SerializationClass SomeStringElementName
    {
        get { return new SerializationClass(this.SomeString); }
    }               
}

WSDL/SOAP Test With soapui

  • yes, first ensure you added "?wsdl" to your "http......whatever.svc" link.
    • That didn't fix my problem, though. I had to create a new WCF project from the beginning and manually copy the code. That fixed it. Good luck.

And most important!!!

When you change a namespace in your code, also make sure you change it in web.config!

Access parent DataContext from DataTemplate

the issue is that a DataTemplate isn't part of an element its applied to it.

this means if you bind to the template you're binding to something that has no context.

however if you put a element inside the template then when that element is applied to the parent it gains a context and the binding then works

so this will not work

<DataTemplate >
    <DataTemplate.Resources>
        <CollectionViewSource x:Key="projects" Source="{Binding Projects}" >

but this works perfectly

<DataTemplate >
    <GroupBox Header="Projects">
        <GroupBox.Resources>
            <CollectionViewSource x:Key="projects" Source="{Binding Projects}" >

because after the datatemplate is applied the groupbox is placed in the parent and will have access to its Context

so all you have to do is remove the style from the template and move it into an element in the template

note that the context for a itemscontrol is the item not the control ie ComboBoxItem for ComboBox not the ComboBox itself in which case you should use the controls ItemContainerStyle instead

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

The error message is so vague, for me I had this code:

var streamReader = new StreamReader(response.GetResponseStream());
var xmlSerializer = new XmlSerializer(typeof(aResponse));
theResponse = (bResponse) xmlSerializer.Deserialize(streamReader);

Notice xmlSerializer is instantiated with aResponse but on deserializing I accidentally casted it to bResonse.

Set focus on TextBox in WPF from view model

public class DummyViewModel : ViewModelBase
    {
        private bool isfocused= false;
        public bool IsFocused
        {
            get
            {
                return isfocused;
            }
            set
            {
                isfocused= value;
                OnPropertyChanged("IsFocused");
            }
        }
    }

Passing two command parameters using a WPF binding

In the converter of the chosen solution, you should add values.Clone() otherwise the parameters in the command end null

public class YourConverter : IMultiValueConverter
{
    public object Convert(object[] values, ...)
    {
        return values.Clone();
    }

    ...
}

Serialize Class containing Dictionary member

You can't serialize a class that implements IDictionary. Check out this link.

Q: Why can't I serialize hashtables?

A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

So I think you need to create your own version of the Dictionary for this. Check this other question.

Javascript to check whether a checkbox is being checked or unchecked

I am not sure what the problem is, but I am pretty sure this will fix it.

for (i=0; i<arrChecks.length; i++)
    {
        var attribute = arrChecks[i].getAttribute("xid")
        if (attribute == elementName)
        {
            if (arrChecks[i].checked == 0)  
            {
                arrChecks[i].checked = 1;
            } else {
                arrChecks[i].checked = 0;
            }

        } else {
            arrChecks[i].checked = 0;
        }
    }

Server did not recognize the value of HTTP Header SOAPAction

We had renamed some of our webservice project namespaces and forgot to update the website httphandlers config section with the namespace of the renamed projects.

What's the best way to build a string of delimited items in Java?

You can use Java's StringBuilder type for this. There's also StringBuffer, but it contains extra thread safety logic that is often unnecessary.

How do I free my port 80 on localhost Windows?

Skype likes to use port 80 and blocks IIS. That was my prob.

Can't connect Nexus 4 to adb: unauthorized

Had the same issue. Not sure if these are the same steps for Windows as I'm using an OS X device but you can try:

  1. Reboot your phone into recovery mode.
  2. Connect it to your computer.
  3. Open the terminal and type:

    cd ~/.android
    adb push adbkey.pub /data/misc/adb/adb_keys
    
  4. All done! Just adb shell reboot and feel the power!

How to open a second activity on click of button in android app

just follow this step (i am not writing code just Bcoz you may do copy and paste and cant learn)..

  1. first at all you need to declare a button which you have in layout

  2. Give reference to that button by finding its id (using findviewById) in oncreate

  3. setlistener for button (like setonclick listener)

  4. last handle the click event (means start new activity by using intent as you know already)

  5. Dont forget to add activity in manifest file

BTW this is just simple i would like to suggest you that just start from simple tutorials available on net will be better for you..

Best luck for Android

How to exit from Python without traceback?

Use the built-in python function quit() and that's it. No need to import any library. I'm using python 3.4

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

Dynamically add properties to a existing object

If you have a class with an object property, or if your property actually casts to an object, you can reshape the object by reassigning its properties, as in:

  MyClass varClass = new MyClass();
  varClass.propObjectProperty = new { Id = 1, Description = "test" };

  //if you need to treat the class as an object
  var varObjectProperty = ((dynamic)varClass).propObjectProperty;
  ((dynamic)varClass).propObjectProperty = new { Id = varObjectProperty.Id, Description = varObjectProperty.Description, NewDynamicProperty = "new dynamic property description" };

  //if your property is an object, instead
  var varObjectProperty = varClass.propObjectProperty;
  varClass.propObjectProperty = new { Id = ((dynamic)varObjectProperty).Id, Description = ((dynamic)varObjectProperty).Description, NewDynamicProperty = "new dynamic property description" };

With this approach, you basically rewrite the object property adding or removing properties as if you were first creating the object with the

new { ... }

syntax.

In your particular case, you're probably better off creating an actual object to which you assign properties like "dob" and "address" as if it were a person, and at the end of the process, transfer the properties to the actual "Person" object.

Maintaining Session through Angular.js

Typically for a use case which involves a sequence of pages and in the final stage or page we post the data to the server. In this scenario we need to maintain the state. In the below snippet we maintain the state on the client side

As mentioned in the above post. The session is created using the factory recipe.

Client side session can be maintained using the value provider recipe as well.

Please refer to my post for the complete details. session-tracking-in-angularjs

Let's take an example of a shopping cart which we need to maintain across various pages / angularjs controller.

In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.

Here we create the custom injectable service having a cart inside using the "value provider recipe".

'use strict';
function Cart() {
    return {
        'cartId': '',
        'cartItem': []
    };
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart 

app.value('sessionService', {
    cart: new Cart(),
    clear: function () {
        this.cart = new Cart();
        // mechanism to create the cart id 
        this.cart.cartId = 1;
    },
    save: function (session) {
        this.cart = session.cart;
    },
    updateCart: function (productId, productQty) {
        this.cart.cartItem.push({
            'productId': productId,
            'productQty': productQty
        });
    },
    //deleteItem and other cart operations function goes here...
});

Best way to copy from one array to another

There are lots of solutions:

b = Arrays.copyOf(a, a.length);

Which allocates a new array, copies over the elements of a, and returns the new array.

Or

b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);

Which copies the source array content into a destination array that you allocate yourself.

Or

b = a.clone();

which works very much like Arrays.copyOf(). See this thread.

Or the one you posted, if you reverse the direction of the assignment in the loop:

b[i] = a[i]; // NOT a[i] = b[i];

Add CSS box shadow around the whole DIV

Yes, don't offset vertically or horizontally, and use a relatively large blur radius: fiddle

Also, you can use multiple box-shadows if you separate them with a comma. This will allow you to fine-tune where they blur and how much they extend. The example I provide is indistinguishable from a large outline, but it can be fine-tuned significantly more: fiddle

You missed the last and most relevant property of box-shadow, which is spread-distance. You can specify a value for how much the shadow expands or contracts (makes my second example obsolete): fiddle

The full property list is:

box-shadow: [horizontal-offset] [vertical-offset] [blur-radius] [spread-distance] [color] inset?

But even better, read through the spec.

how to change text in Android TextView

The first line of new text view is unnecessary

t=new TextView(this); 

you can just do this

TextView t = (TextView)findViewById(R.id.TextView01);

as far as a background thread that sleeps here is an example, but I think there is a timer that would be better for this. here is a link to a good example using a timer instead http://android-developers.blogspot.com/2007/11/stitch-in-time.html

    Thread thr = new Thread(mTask);
    thr.start();
}

Runnable mTask = new Runnable() {
    public void run() {
        // just sleep for 30 seconds.
                    try {
                        Thread.sleep(3000);
                        runOnUiThread(done);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    };

    Runnable done = new Runnable() {
        public void run() {
                   // t.setText("done");
            }
        };

How do you easily horizontally center a <div> using CSS?

you can use the position:relative; and then set the left and the top values:

.cenverDiv{
    position:relative;
    left:30%;
    top:0px;
}

How to Multi-thread an Operation Within a Loop in Python

import numpy as np
import threading


def threaded_process(items_chunk):
    """ Your main process which runs in thread for each chunk"""
    for item in items_chunk:                                               
        try:                                                                    
            api.my_operation(item)                                              
        except Exception:                                                       
            print('error with item')  

n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
    thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
    thread_list.append(thread)
    thread_list[thr].start()

for thread in thread_list:
    thread.join()

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Server certificate verification failed: issuer is not trusted

during command line works. I'm using Ant to commit an artifact after build completes. Experienced the same issue... Manually excepting the cert did not work (Jenkins is funny that way). Add these options to your svn command:

--non-interactive

--trust-server-cert

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2
etc...

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

Getting a list of files in a directory with a glob

You can achieve this pretty easily with the help of NSPredicate, like so:

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

If you need to do it with NSURL instead it looks like this:

NSURL *bundleRoot = [[NSBundle mainBundle] bundleURL];
NSArray * dirContents = 
      [fm contentsOfDirectoryAtURL:bundleRoot
        includingPropertiesForKeys:@[] 
                           options:NSDirectoryEnumerationSkipsHiddenFiles
                             error:nil];
NSPredicate * fltr = [NSPredicate predicateWithFormat:@"pathExtension='jpg'"];
NSArray * onlyJPGs = [dirContents filteredArrayUsingPredicate:fltr];

Very Simple, Very Smooth, JavaScript Marquee

I made my own version, based in the code presented above by @Tats_innit . The difference is the pause function. Works a little better in that aspect.

(function ($) {
var timeVar, width=0;

$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};

$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        },
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        },
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);

    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            i++;
            if (i <= args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width=width-2;
        }
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };
    };

    if (args.leftToRight) {
        width = textWidth * -1;
        width++;
        stop = offset;
    } else {
        width--;
    }
    that.css(marqueeCss);

    timeVar = setTimeout(function () { go() }, 100);

    return dfd.promise();
};
})(jQuery);

usage:

for start: $('#Text1').marquee()

pause: $('#Text1').marquee({ pause: true })

resume: $('#Text1').marquee({ pause: false })

Vagrant stuck connection timeout retrying

Check your CPU's virtualization in BIOS setup is enabled.

Convert Text to Uppercase while typing in Text box

I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
        {
            int iPos = textBox1.SelectionStart;
            int iLen = textBox1.SelectionLength;
            textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
            textBox1.SelectionStart = iPos + 1;
            e.Handled = true;
        }
    }

It works even if you type a lowercase character in a textbox where some characters are selected. I don't know if the code works with a Multiline textbox.

How to get the insert ID in JDBC?

With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query

INSERT INTO bla (a,b) VALUES (2,3) RETURNING id

like

INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1

if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Equivalent of LIMIT for DB2

Developed this method:

You NEED a table that has an unique value that can be ordered.

If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:

int start = 40000 - 10000;

int total = 25000 - 10000;

And then pass these by code to the query:

SELECT * FROM 
(SELECT * FROM schema.mytable 
ORDER BY userId DESC fetch first {start} rows only ) AS mini 
ORDER BY mini.userId ASC fetch first {total} rows only

Plotting with C#

There is OxyPlot which I recommend. It has packages for WPF, Metro, Silverlight, Windows Forms, Avalonia UI, XWT. Besides graphics it can export to SVG, PDF, Open XML, etc. And it even supports Mono and Xamarin for Android and iOS. It is actively developed too.

There is also a new (at least for me) open source .NET plotting library called Live-Charts. The plots are pretty interactive. Library suports WPF, WinForms and UWP. Xamarin is planned. The design is made towards MV* patterns. But @Pawel Audionysos suggests not such a good performance of Live-Charts WPF.

How do I convert a C# List<string[]> to a Javascript array?

For one dimension array

Controller:

using Newtonsoft.Json;
var listOfIds = _dbContext.Countries.Where(x => x.Id == Country.USA).First().Cities.Where(x => x.IsCoveredByCompany).Select(x => x.Id).ToList();
string strArrayForJS = JsonConvert.SerializeObject(listOfIds); //  [1,2,6,7,8,18,25,61,129]
//Now pass it to the view through the model or ViewBag 

View:

<script>
    $(function () {
        var myArray = @HTML.Raw(Model.strArrayForJS);
        console.log(myArray); // [1, 2, 6, 7, 8, 18, 25, 61, 129]
        console.log(typeof (myArray)); //object
    });
</script>

Breaking/exit nested for in vb.net

For i As Integer = 0 To 100
    bool = False
    For j As Integer = 0 To 100
        If check condition Then
            'if condition match
            bool = True
            Exit For 'Continue For
        End If
    Next
    If bool = True Then Continue For
Next

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Here is how I did it (that's to prompt browser to download the csv file):

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=file.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
echo $csv_file_content;
exit();

The only thing it fixed UTF8 encoding problem in CSV preview when you hit space bar on Mac.. but not in Excel Mac 2008... don't know why

How do I escape reserved words used as column names? MySQL/Create Table

If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.

Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:

  • Write all you SQL queries in ANSI SQL
  • Enclose them in the following MySQL specific queries:

    SET @OLD_SQL_MODE=@@SQL_MODE;
    SET SESSION SQL_MODE='ANSI';
    -- ANSI SQL queries
    SET SESSION SQL_MODE=@OLD_SQL_MODE;
    

This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.

How can you integrate a custom file browser/uploader with CKEditor?

An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:

So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);

For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage); </script>

If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

How to loop through a dataset in powershell?

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"

Android - Pulling SQlite database android device

A common way to achieve what you desire is to use the ADB pull command.

Another way I prefer in most cases is to copy the database by code to SD card:

try {
    File sd = Environment.getExternalStorageDirectory();

    if (sd.canWrite()) {
        String currentDBPath = "/data/data/" + getPackageName() + "/databases/yourdatabasename";
        String backupDBPath = "backupname.db";
        File currentDB = new File(currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) {
            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
        }
    }
} catch (Exception e) {

}

Don't forget to set the permission to write on SD in your manifest, like below.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to post query parameters with Axios?

As of 2021 insted of null i had to add {} in order to make it work!

axios.post(
        url,
        {},
        {
          params: {
            key,
            checksum
          }
        }
      )
      .then(response => {
        return success(response);
      })
      .catch(error => {
        return fail(error);
      });

How to cache Google map tiles for offline usage?

If you are trying to cache the tiles that Google serves, that may be a violation of Google's Terms of Service (unless, under certain circumstances, if you've purchased their enterprise Maps API Premier). That's why gmapcatcher has it crossed off their list. See http://code.google.com/p/gmapcatcher/issues/detail?id=210.

At the gmapcatcher URL above, you will also find a shell script that can download tiles (or so its author says).

There are also other projects that try to make Google Maps available offline:

http://code.google.com/p/ogmaps/

http://code.google.com/p/gmapoffline/

Lastly, if Google Earth can meet your needs, then you can use that. Offline usage of Google Earth requires a Google Earth Enterprise license according to http://www.google.com/permissions/geoguidelines.html.

Note that the preceding page also says: "You may not scrape or otherwise export Content from Google Maps or Earth or save it for offline use." So if you try to cache tiles, that will almost certainly be considered (by Google, anyway) a violation of the Terms of Service.

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

How can I force clients to refresh JavaScript files?

Use a version GET variable to prevent browser caching.

Appending ?v=AUTO_INCREMENT_VERSION to the end of your url prevents browser caching - avoiding any and all cached scripts.

Calling a PHP function from an HTML form in the same file

This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.

test.php

<form action="javascript:void(0);" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" />
</form>

<script type="text/javascript">
    $("form").submit(function(){
        var str = $(this).serialize();
        $.ajax('getResult.php', str, function(result){
            alert(result); // The result variable will contain any text echoed by getResult.php
        }
        return(false);
    });
</script>

It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.

getResult.php

<?php
    echo "The name you typed is: " . $_REQUEST['user'];
?>

NOTE

This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.

Finding the path of the program that will execute from the command line in Windows

Use the where command. The first result in the list is the one that will execute.

C:\> where notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe

According to this blog post, where.exe is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.

On Linux, the equivalent is the which command, e.g. which ssh.

How can I set a custom date time format in Oracle SQL Developer?

You can change this in preferences:

  1. From Oracle SQL Developer's menu go to: Tools > Preferences.
  2. From the Preferences dialog, select Database > NLS from the left panel.
  3. From the list of NLS parameters, enter DD-MON-RR HH24:MI:SS into the Date Format field.
  4. Save and close the dialog, done!

Here is a screenshot:

Changing Date Format preferences in Oracle SQL Developer

Java difference between FileWriter and BufferedWriter

You are right. Here is how write() method of BufferedWriter looks:

public void write(int c) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (nextChar >= nChars)
            flushBuffer();
        cb[nextChar++] = (char) c;
    }
}

As you can see it indeed checks whether the buffer is full (if (nextChar >= nChars)) and flushes the buffer. Then it adds new character to buffer (cb[nextChar++] = (char) c;).

How do you get the current project directory from C# code when creating a custom MSBuild task?

This will also give you the project directory by navigating two levels up from the current executing directory (this won't return the project directory for every build, but this is the most common).

System.IO.Path.GetFullPath(@"..\..\")

Of course you would want to contain this inside some sort of validation/error handling logic.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

iOS: How to store username/password within an app?

The following should work just fine:

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData]; 
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

How to stop default link click behavior with jQuery

$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Two Decimal places using c#

Use Math.Round() for rounding to two decimal places

decimal DEBITAMT = Math.Round(1156.547m, 2);

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

How to make System.out.println() shorter

Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.

Why does Eclipse complain about @Override on interface methods?

Using the @Override annotation on methods that implement those declared by an interface is only valid from Java 6 onward. It's an error in Java 5.

Make sure that your IDE projects are setup to use a Java 6 JRE, and that the "source compatibility" is set to 1.6 or greater:

  1. Open the Window > Preferences dialog
  2. Browse to Java > Compiler.
  3. There, set the "Compiler compliance level" to 1.6.

Remember that Eclipse can override these global settings for a specific project, so check those too.


Update:

The error under Java 5 isn't just with Eclipse; using javac directly from the command line will give you the same error. It is not valid Java 5 source code.

However, you can specify the -target 1.5 option to JDK 6's javac, which will produce a Java 5 version class file from the Java 6 source code.

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

Redirect on select option in select box

For someone who doesn't want to use inline JS.

<select data-select-name>
    <option value="">Select...</option>
    <option value="http://google.com">Google</option>
    <option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded',function() {
        document.querySelector('select[data-select-name]').onchange=changeEventHandler;
    },false);

    function changeEventHandler(event) {
        window.location.href = this.options[this.selectedIndex].value;
    }
</script>

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

if you want to redirect it to some other url lets google.com then make your like as happy to help other says rikin <a href="//google.com">happy to help other says rikin</a> this will remove self site url form the href.

AngularJS: Service vs provider vs factory

Essentially, Provider, Factory, and Service are all Services. A Factory is a special case of a Service when all you need is a $get() function, allowing you to write it with less code.

The major differences among Services, Factories, and Providers are their complexities. Services are the simplest form, Factories are a little more robust, and Providers are configurable at runtime.

Here is a summary of when to use each:

Factory: The value you are providing needs to be calculated based on other data.

Service: You are returning an object with methods.

Provider: You want to be able to configure, during the config phase, the object that is going to be created before it’s created. Use the Provider mostly in the app config, before the app has fully initialized.

Add data dynamically to an Array

You should use method array_push to add value or array to array exists

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

/** GENERATED OUTPUT
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
*/

How to install CocoaPods?

Simple Steps to installed pod file:

  1. Open terminal 2.Command on terminal: sudo gem install cocoapods

  2. set your project path on terminal.

  3. command : pod init

  4. go to pod file of your project and adding pod which you want to install

  5. added in pod file : pod 'AFNetworking', '~> 3.0

  6. Command : Pod install

  7. Close project of Xcode

  8. open your Project from terminals

  9. Command : open PodDemos.xcworkspace

Reading data from DataGridView in C#

string[,] myGridData = new string[dataGridView1.Rows.Count,3];

int i = 0;

foreach(DataRow row in dataGridView1.Rows)

{

    myGridData[i][0] = row.Cells[0].Value.ToString();
    myGridData[i][1] = row.Cells[1].Value.ToString();
    myGridData[i][2] = row.Cells[2].Value.ToString();

    i++;
}

Hope this helps....

single line comment in HTML

No, <!-- ... --> is the only comment syntax in HTML.

How do I disable form fields using CSS?

This can be helpful:

<input type="text" name="username" value="admin" >

<style type="text/css">
input[name=username] {
    pointer-events: none;
 }
</style>

Update:

and if want to disable from tab index you can use it this way:

 <input type="text" name="username" value="admin" tabindex="-1" >

 <style type="text/css">
  input[name=username] {
    pointer-events: none;
   }
 </style>

How do I shut down a python simpleHTTPserver?

When you run a program as a background process (by adding an & after it), e.g.:

python -m SimpleHTTPServer 8888 &

If the terminal window is still open you can do:

jobs

To get a list of all background jobs within the running shell's process.

It could look like this:

$ jobs
[1]+  Running                 python -m SimpleHTTPServer 8888 &

To kill a job, you can either do kill %1 to kill job "[1]", or do fg %1 to put the job in the foreground (fg) and then use ctrl-c to kill it. (Simply entering fg will put the last backgrounded process in the foreground).

With respect to SimpleHTTPServer it seems kill %1 is better than fg + ctrl-c. At least it doesn't protest with the kill command.

The above has been tested in Mac OS, but as far as I can remember it works just the same in Linux.

Update: For this to work, the web server must be started directly from the command line (verbatim the first code snippet). Using a script to start it will put the process out of reach of jobs.

./xx.py: line 1: import: command not found

It's not an issue related to authentication at the first step. Your import is not working. So, try writing this on first line:

#!/usr/bin/python

and for the time being run using

python xx.py

For you here is one explanation:

>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>> 

>>> print "%s" %xyz

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print "%s" %xyz
NameError: name 'xyz' is not defined

At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!

How do I use WPF bindings with RelativeSource?

If an element is not part of the visual tree, then RelativeSource will never work.

In this case, you need to try a different technique, pioneered by Thomas Levesque.

He has the solution on his blog under [WPF] How to bind to data when the DataContext is not inherited. And it works absolutely brilliantly!

In the unlikely event that his blog is down, Appendix A contains a mirror copy of his article.

Please do not comment here, please comment directly on his blog post.

Appendix A: Mirror of blog post

The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…

Let’s illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding ShowPrice,
                Converter={StaticResource visibilityConverter}}"/>

Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)

The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of the DataGrid.

We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding DataContext.ShowPrice,
                Converter={StaticResource visibilityConverter},
                RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>

Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to the IsChecked property by specifying the element name:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding IsChecked,
                Converter={StaticResource visibilityConverter},
                ElementName=chkShowPrice}"/>

But none of these workarounds seems to work, we always get the same result…

At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider

The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…

The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:

public class BindingProxy : Freezable
{
    #region Overrides of Freezable
 
    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }
 
    #endregion
 
    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }
 
    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

The last step is to specify this BindingProxy object (easily accessible with StaticResource) as the Source for the binding:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding Data.ShowPrice,
                Converter={StaticResource visibilityConverter},
                Source={StaticResource proxy}}"/>

Note that the binding path has been prefixed with “Data”, since the path is now relative to the BindingProxy object.

The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice property.

Delimiter must not be alphanumeric or backslash and preg_match

The pattern must have delimiters. Delimiters can be a forward slash (/) or any non alphanumeric characters(#,$,*,...). Examples

$pattern = "/My name is '(.*)' and im fine/"; 
$pattern = "#My name is '(.*)' and im fine#";
$pattern = "@My name is '(.*)' and im fine@";  

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

CSS Background Image Not Displaying

If your path is correct then I think you don't have any element in you body section. Just define the height of the body and your code will work.

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

Sometimes you just don't have a choice about having to store numbers mixed with text. In one of our applications, the web site host we use for our e-commerce site makes filters dynamically out of lists. There is no option to sort by any field but the displayed text. When we wanted filters built off a list that said things like 2" to 8" 9" to 12" 13" to 15" etc, we needed it to sort 2-9-13, not 13-2-9 as it will when reading the numeric values. So I used the SQL Server Replicate function along with the length of the longest number to pad any shorter numbers with a leading space. Now 20 is sorted after 3, and so on.

I was working with a view that gave me the minimum and maximum lengths, widths, etc for the item type and class, and here is an example of how I did the text. (LBnLow and LBnHigh are the Low and High end of the 5 length brackets.)

REPLICATE(' ', LEN(LB5Low) - LEN(LB1High)) + CONVERT(NVARCHAR(4), LB1High) + '" and Under' AS L1Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB2Low)) + CONVERT(NVARCHAR(4), LB2Low) + '" to ' + CONVERT(NVARCHAR(4), LB2High) + '"' AS L2Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB3Low)) + CONVERT(NVARCHAR(4), LB3Low) + '" to ' + CONVERT(NVARCHAR(4), LB3High) + '"' AS L3Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB4Low)) + CONVERT(NVARCHAR(4), LB4Low) + '" to ' + CONVERT(NVARCHAR(4), LB4High) + '"' AS L4Text,
CONVERT(NVARCHAR(4), LB5Low) + '" and Over' AS L5Text

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

How do I (or can I) SELECT DISTINCT on multiple columns?

If you put together the answers so far, clean up and improve, you would arrive at this superior query:

UPDATE sales
SET    status = 'ACTIVE'
WHERE  (saleprice, saledate) IN (
    SELECT saleprice, saledate
    FROM   sales
    GROUP  BY saleprice, saledate
    HAVING count(*) = 1 
    );

Which is much faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).

But this is still far from optimal. Use a NOT EXISTS (anti-)semi-join for even better performance. EXISTS is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:

UPDATE sales s
SET    status = 'ACTIVE'
WHERE  NOT EXISTS (
   SELECT FROM sales s1                     -- SELECT list can be empty for EXISTS
   WHERE  s.saleprice = s1.saleprice
   AND    s.saledate  = s1.saledate
   AND    s.id <> s1.id                     -- except for row itself
   )
AND    s.status IS DISTINCT FROM 'ACTIVE';  -- avoid empty updates. see below

db<>fiddle here
Old SQL Fiddle

Unique key to identify row

If you don't have a primary or unique key for the table (id in the example), you can substitute with the system column ctid for the purpose of this query (but not for some other purposes):

   AND    s1.ctid <> s.ctid

Every table should have a primary key. Add one if you didn't have one, yet. I suggest a serial or an IDENTITY column in Postgres 10+.

Related:

How is this faster?

The subquery in the EXISTS anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes way more efficient.

Exclude empty updates

For rows that already have status = 'ACTIVE' this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another WHERE condition like demonstrated above to avoid this and make it even faster:

If status is defined NOT NULL, you can simplify to:

AND status <> 'ACTIVE';

The data type of the column must support the <> operator. Some types like json don't. See:

Subtle difference in NULL handling

This query (unlike the currently accepted answer by Joel) does not treat NULL values as equal. The following two rows for (saleprice, saledate) would qualify as "distinct" (though looking identical to the human eye):

(123, NULL)
(123, NULL)

Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:

OTOH, GROUP BY, DISTINCT or DISTINCT ON () treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with IS NOT DISTINCT FROM instead of = for any or all comparisons to make NULL compare equal. More:

If all columns being compared are defined NOT NULL, there is no room for disagreement.

How can I pass some data from one controller to another peer controller

You need to use

 $rootScope.$broadcast()

in the controller that must send datas. And in the one that receive those datas, you use

 $scope.$on

Here is a fiddle that i forked a few time ago (I don't know who did it first anymore

http://jsfiddle.net/patxy/RAVFM/

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

How to hide scrollbar in Firefox?

Just in case, if someone is looking for a hack to somehow make the scrollbar invisible in firefox(79.0).

Here's a solution that successfully works for Chrome, IE, Safari, and makes the scrollbar transparent in Firefox. None of the above worked for firefox(79.0) in truly hiding the scrollbar.

Please if anyone finds a way to do it without changing the color, it will be very helpful. Pls comment below.

.scrollhost::-webkit-scrollbar {
  display: none;
}

.scrollhost ::-moz-scrollbar {
  display: none;
 
}
 
.scrollhost {
  overflow: auto;
  -ms-overflow-style: none;
  scrollbar-color: transparent transparent; /*just hides the scrollbar for firefox */
}

Disabling vertical scrolling in UIScrollView

Just set the y to be always on top. Need to conform with UIScrollViewDelegate

func scrollViewDidScroll(scrollView: UIScrollView) {
        scrollView.contentOffset.y = 0.0
}

This will keep the Deceleration / Acceleration effect of the scrolling.

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

How to Rotate a UIImage 90 degrees?

If you want to add a photo rotate button that'll keep rotating the photo in 90 degree increments, here you go. (finalImage is a UIImage that's already been created elsewhere.)

- (void)rotatePhoto {
    UIImage *rotatedImage;

    if (finalImage.imageOrientation == UIImageOrientationRight)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationDown];
    else if (finalImage.imageOrientation == UIImageOrientationDown)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationLeft];
    else if (finalImage.imageOrientation == UIImageOrientationLeft)
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                              scale: 1.0
                                        orientation: UIImageOrientationUp];
    else
        rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
                                                     scale: 1.0
                                               orientation: UIImageOrientationRight];
    finalImage = rotatedImage;
}

How to find file accessed/created just few minutes ago

To find files accessed 1, 2, or 3 minutes ago use -3

find . -cmin -3

How to access remote server with local phpMyAdmin client?

As stated in answer c.hill answer, if you want a secure solution I would advise to open an SSH tunnel to your server.

Here is the way to do it for Windows users:

  1. Download Plink and Putty from the Putty website and place the files in the folder of your choice (In my example C:\Putty)

  2. Open the Windows console and cd to Plink folder: cd C:\Putty

  3. Open the SSH tunnel and redirect to the port 3307:

    plink -L 3307:localhost:3306 username@server_ip -i path_to_your_private_key.ppk

Where:

  • 3307 is the local port you want to redirect to
  • localhost is the address of the MySQL DB on the remote server (localhost by default)
  • 3306 is the port use for PhpMyAdmin on the remote server (3306 by default)

Finally you can setup PhpMyAdmin:

  1. Add the remote server to your local PhpMyAdmin configuration by adding the following line at the end of config.inc.php

Lines to add:

$i++;   
$cfg['Servers'][$i]['verbose']          = 'Remote Dev server';
$cfg['Servers'][$i]['host']             = 'localhost';
$cfg['Servers'][$i]['port']             = '3307';
$cfg['Servers'][$i]['connect_type']     = 'tcp';
$cfg['Servers'][$i]['extension']        = 'mysqli';
$cfg['Servers'][$i]['compress']         = FALSE;
$cfg['Servers'][$i]['auth_type']        = 'cookie';
  1. You should be able to connect now at http://127.0.0.1/phpmyadmin

If you do not want to open the console each time you need to connect to your remote server, just create a batch file (by saving the 2 command lines in a .bat file).

Oracle : how to subtract two dates and get minutes of the result

For those who want to substrat two timestamps (instead of dates), there is a similar solution:

SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 1440 AS minutesInBetween
FROM ...

or

SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 86400 AS secondsInBetween
FROM ...

How do you search an amazon s3 bucket?

The way I did it is: I have thousands of files in s3. I saw the properties panel of one file in the list. You can see the URI of that file and I copy pasted that to the browser - it was a text file and it rendered nicely. Now I replaced the uuid in the url with the uuid that I had at hand and boom there the file is.

I wish AWS had a better way to search a file, but this worked for me.

How to write UTF-8 in a CSV file

A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:

    fd = codecs.open(tempfilename, 'wb', 'utf-8')  
    for c in whatever :
        fd.write( json.dumps(c) [1:-1] )   # json dumps writes ["a",..]
        fd.write('\n')
    fd.close()

Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

Convert ndarray from float64 to integer

There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype() does) definitely check out the link.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

Where is SQL Profiler in my SQL Server 2008?

first get the profiler Exe from: http://expressprofiler.codeplex.com

then you can add it simply to the Management studio:

Tools -> External tools... ->

a- locate the exe file on your disk (If installed, it's typically C:\Program Files (x86)\ExpressProfiler\ExpressProfiler.exe)

b- give it a name e.g. Express Profiler

that's it :) you have your Profiler with your sql express edition

enter image description here

Deleting records before a certain date

DELETE FROM table WHERE date < '2011-09-21 08:21:22';

How to simulate "Press any key to continue?"

In windows, this short program accomplishes the goal: getch pauses the console until a key is pressed (https://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/)

#include<iostream.h>
#include<conio.h>

using namespace std;

void  check()
{
    char chk; int j;
    cout<<"\n\nPress any key to continue...";
    chk=getch();
    j=chk;
    for(int i=1;i<=256;i++)
      if(i==j) break;
    clrscr();
}

void main()
{
    clrscr();
    check();
    cout<<"\n\nIt works!";
    getch();
}

It should be noted that getch is not part of the standard library.

Java 8 NullPointerException in Collectors.toMap

If the value is a String, then this might work: map.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> Optional.ofNullable(e.getValue()).orElse("")))

How to get the EXIF data from a file using C#

You can use TagLib# which is used by applications such as F-Spot. Besides Exif, it will read a good amount of metadata formats for image, audio and video.

I also like ExifUtils API but it is buggy and is not actively developed.

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

Open Excel file for reading with VBA without display

Open the workbook as hidden and then set it as "saved" so that users are not prompted when they close out.

Dim w As Workbooks

Private Sub Workbook_Open()
    Application.ScreenUpdating = False
    Set w = Workbooks
    w.Open Filename:="\\server\PriceList.xlsx", UpdateLinks:=False, ReadOnly:=True 'this is the data file were going to be opening
    ActiveWindow.Visible = False
    ThisWorkbook.Activate
    Application.ScreenUpdating = True
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    w.Item(2).Saved = True 'this will suppress the safe prompt for the data file only
End Sub

This is somewhat derivative of the answer posted by Ashok.

By doing it this way though you will not get prompted to save changes back to the Excel file your reading from. This is great if the Excel file your reading from is intended as a data source for validation. For example if the workbook contains product names and price data it can be hidden and you can show an Excel file that represents an invoice with drop downs for product that validates from that price list.

You can then store the price list on a shared location on a network somewhere and make it read-only.

General error: 1364 Field 'user_id' doesn't have a default value

In my case, the error was because I had not declared the field in my $fillable array in the model. Well, it seems to be something basic, but for us who started with laravel it could work.

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

What does .shape[] do in "for i in range(Y.shape[0])"?

In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data
train.shape[0]

Number of columns is given by

train.shape[1]

Which port(s) does XMPP use?

According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.

The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.

How to parse/format dates with LocalDateTime? (Java 8)

You can also use LocalDate.parse() or LocalDateTime.parse() on a String without providing it with a pattern, if the String is in ISO-8601 format.

for example,

String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);

String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);

Output,

Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30

and use DateTimeFormatter only if you have to deal with other date patterns.

For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:

DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);

Output

04 Aug 2015 parses to 2015-08-04

also remember that the DateTimeFormatter object is bidirectional; it can both parse input and format output.

String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));

Output

2015-08-04 formats as 04 Aug 2015

(see complete list of Patterns for Formatting and Parsing DateFormatter)

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
   Y       week-based-year             year              1996; 96
   w       week-of-week-based-year     number            27
   W       week-of-month               number            4
   E       day-of-week                 text              Tue; Tuesday; T
   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
   F       week-of-month               number            3

   a       am-pm-of-day                text              PM
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-am-pm (1-24)  number            0

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   A       milli-of-day                number            1234
   n       nano-of-second              number            987654321
   N       nano-of-day                 number            1234000000

   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;

   p       pad next                    pad modifier      1

   '       escape for text             delimiter
   ''      single quote                literal           '
   [       optional section start
   ]       optional section end
   #       reserved for future use
   {       reserved for future use
   }       reserved for future use

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

If you use chrome, you can make a shortcut,right click and edit the shortcut's target, append this after target's string:

--ignore-certificate-errors

The complete string looks like this:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors

Are static methods inherited in Java?

Many have voiced out their answer in words. This is an extended explanation in codes:

public class A {
    public static void test() {
        System.out.println("A");
    }
    public static void test2() {
        System.out.println("Test");
    }
}

public class B extends A {
    public static void test() {
        System.out.println("B");
    }
}

// Called statically
A.test();
B.test();
System.out.println();

// Called statically, testing static inheritance
A.test2();
B.test2();
System.out.println();

// Called via instance object
A a = new A();
B b = new B();
a.test();
b.test();
System.out.println();

// Testing inheritance via instance call
a.test2();
b.test2();
System.out.println();

// Testing whether calling static method via instance object is dependent on compile or runtime type
((A) b).hi();
System.out.println();

// Testing whether null instance works
A nullObj = null;
nullObj.hi();

Results:

A
B

Test
Test

A
B

Test
Test

A

A

Therefore, this is the conclusion:

  1. When we call the static in a static manner via ., it will look for the static defined in that class, or the class nearest to that in the inheritance chain. This proves that static methods are inherited.
  2. When static method is called from an instance, it calls the static method defined in the compile-time type.
  3. Static method can be called from a null instance. My guess is that the compiler will use the variable type to find the class during compilation, and translate that to the appropriate static method call.

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

biggest integer that can be stored in a double

DECIMAL_DIG from <float.h> should give at least a reasonable approximation of that. Since that deals with decimal digits, and it's really stored in binary, you can probably store something a little larger without losing precision, but exactly how much is hard to say. I suppose you should be able to figure it out from FLT_RADIX and DBL_MANT_DIG, but I'm not sure I'd completely trust the result.

How to send a model in jQuery $.ajax() post request to MVC controller method

you can create a variable and send to ajax.

var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

The cleanest way I found to do this is create a child of 'ThemeOverlay.AppCompat.Dark.ActionBar'. In the example, I set the Toolbar's background color to RED and text's color to BLUE.

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#FF0000</item>
    <item name="android:textColorPrimary">#0000FF</item>
</style>

You can then apply your theme to the toolbar:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    app:theme="@style/MyToolbar"
    android:minHeight="?attr/actionBarSize"/>

PostgreSQL: days/months/years between two dates

@WebWanderer 's answer is very close to the DateDiff using SQL server, but inaccurate. That is because of the usage of age() function.

e.g. days between '2019-07-29' and '2020-06-25' should return 332, however, using the age() function it will returns 327. Because the age() returns '10 mons 27 days" and it treats each month as 30 days which is incorrect.

You shold use the timestamp to get the accurate result. e.g.

ceil((select extract(epoch from (current_date::timestamp - <your_date>::timestamp)) / 86400))

RandomForestClassfier.fit(): ValueError: could not convert string to float

As your input is in string you are getting value error message use countvectorizer it will convert data set in to sparse matrix and train your ml algorithm you will get the result

Remove trailing comma from comma-separated string

You can use this:

String abc = "kushalhs , mayurvm , narendrabz ,";
String a = abc.substring(0, abc.lastIndexOf(","));

Removing ul indentation with CSS

-webkit-padding-start: 0;

will remove padding added by webkit engine

Color Tint UIButton Image

Swift 4 with customType:

let button = UIButton(frame: aRectHere)
    let buttonImage = UIImage(named: "imageName")
    button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
    button.tintColor = .white

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

The format specifers matter: "%s" says that the next string is a narrow string ("ascii" and typically 8 bits per character). "%S" means wide char string. Mixing the two will give "undefined behaviour", which includes printing garbage, just one character or nothing.

One character is printed because wide chars are, for example, 16 bits wide, and the first byte is non-zero, followed by a zero byte -> end of string in narrow strings. This depends on byte-order, in a "big endian" machine, you'd get no string at all, because the first byte is zero, and the next byte contains a non-zero value.

How to consume REST in Java

The code below will help to consume rest api via Java. URL - end point rest If you dont need any authentication you dont need to write the authStringEnd variable

The method will return a JsonObject with your response

public JSONObject getAllTypes() throws JSONException, IOException {
        String url = "/api/atlas/types";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        javax.ws.rs.client.Client client = ClientBuilder.newClient();
        WebTarget webTarget = client.target(host + url);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header("Authorization", "Basic " + authStringEnc);

        Response response = invocationBuilder.get();
        String output = response.readEntity(String.class
        );

        System.out.println(response.toString());
        JSONObject obj = new JSONObject(output);

        return obj;
    }

How to get name of calling function/method in PHP?

The debug_backtrace() function is the only way to know this, if you're lazy it's one more reason you should code the GetCallingMethodName() yourself. Fight the laziness! :D

How to simplify a null-safe compareTo() implementation?

I would implement a null safe comparator. There may be an implementation out there, but this is so straightforward to implement that I've always rolled my own.

Note: Your comparator above, if both names are null, won't even compare the value fields. I don't think this is what you want.

I would implement this with something like the following:

// primarily by name, secondarily by value; null-safe; case-insensitive
public int compareTo(final Metadata other) {

    if (other == null) {
        throw new NullPointerException();
    }

    int result = nullSafeStringComparator(this.name, other.name);
    if (result != 0) {
        return result;
    }

    return nullSafeStringComparator(this.value, other.value);
}

public static int nullSafeStringComparator(final String one, final String two) {
    if (one == null ^ two == null) {
        return (one == null) ? -1 : 1;
    }

    if (one == null && two == null) {
        return 0;
    }

    return one.compareToIgnoreCase(two);
}

EDIT: Fixed typos in code sample. That's what I get for not testing it first!

EDIT: Promoted nullSafeStringComparator to static.

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>
}

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

What is the runtime performance cost of a Docker container?

An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.

The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).

Docker NAT overhead

They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.

Docker Redis Latency Overhead

Just because it’s a really useful paper, here are some other figures. Please download it for full access.

Taking a look at Disk I/O:

Docker vs. KVM vs. Native I/O Performance

Now looking at CPU overhead:

Docker CPU Overhead

Now some examples of memory (read the paper for details, memory can be extra tricky):

Docker Memory Comparison

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

Could someone explain this for me - for (int i = 0; i < 8; i++)

That's a loop that says, okay, for every time that i is smaller than 8, I'm going to do whatever is in the code block. Whenever i reaches 8, I'll stop. After each iteration of the loop, it increments i by 1 (i++), so that the loop will eventually stop when it meets the i < 8 (i becomes 8, so no longer is smaller than) condition.

For example, this:

for (int i = 0; i < 8; i++)
{
   Console.WriteLine(i);
}

Will output: 01234567

See how the code was executed 8 times?

In terms of arrays, this can be helpful when you don't know the size of the array, but you want to operate on every item of it. You can do:

Disclaimer: This following code will vary dependent upon language, but the principle remains the same

Array yourArray;

for (int i = 0; i < yourArray.Count; i++)
{
    Console.WriteLine(yourArray[i]);
}

The difference here is the number of execution times is entirely dependent on the size of the array, so it's dynamic.

Create table with jQuery - append

You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.

$('#here_table').append(  '<table />' );

 for(i=0;i<3;i++){
    $('#here_table table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

The main problem was that you were appending the tr to the div here_table.

Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop

var doc = document;

var fragment = doc.createDocumentFragment();

for (i = 0; i < 3; i++) {
    var tr = doc.createElement("tr");

    var td = doc.createElement("td");
    td.innerHTML = "content";

    tr.appendChild(td);

    //does not trigger reflow
    fragment.appendChild(tr);
}

var table = doc.createElement("table");

table.appendChild(fragment);

doc.getElementById("here_table").appendChild(table);

java.net.ConnectException: Connection refused

One point that I would like to add to the answers above is my experience-

"I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error"

Point to note - When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response

so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.


To get IP for your local machine, you can use ipconfig command on cmd you will get IPv4 something like 192.68.xx.yy Voila ..that's your machine's IP where you have your server hosted. use it then instead of localhost

http://192.168.72.66/my_api/login.php


Note - you won't be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

How to show first commit by 'git log'?

You can just reverse your log and just head it for the first result.

git log --pretty=oneline --reverse | head -1

Global variables in header file

@glglgl already explained why what you were trying to do was not working. Actually, if you are really aiming at defining a variable in a header, you can trick using some preprocessor directives:

file1.c:

#include <stdio.h>

#define DEFINE_I
#include "global.h"

int main()
{
    printf("%d\n",i);
    foo();
    return 0;
}

file2.c:

#include <stdio.h>
#include "global.h"

void foo()
{
    i = 54;
    printf("%d\n",i);
}

global.h:

#ifdef DEFINE_I
int i = 42;
#else
extern int i;
#endif

void foo();

In this situation, i is only defined in the compilation unit where you defined DEFINE_I and is declared everywhere else. The linker does not complain.

I have seen this a couple of times before where an enum was declared in a header, and just below was a definition of a char** containing the corresponding labels. I do understand why the author preferred to have that definition in the header instead of putting it into a specific source file, but I am not sure whether the implementation is so elegant.

insert password into database in md5 format?

Don't use MD5 as it is insecure. I would recommend using SHA or bcrypt with a salt:

SHA256('".$password."')

http://en.wikipedia.org/wiki/Salt_(cryptography)

How to rename a pane in tmux?

The easiest option for me was to rename the title of the terminal instead. Please see: https://superuser.com/questions/362227/how-to-change-the-title-of-the-mintty-window

In this answer, they mention to modify the PS1 variable. Note: my situation was particular to cygwin.

TL;DR Put this in your .bashrc file:

function settitle() {
      export PS1="\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n$ "
      echo -ne "\e]0;$1\a"
}

Put this in your .tmux.conf file, or similar formatting:

set -g pane-border-status bottom
set -g pane-border-format "#P #T #{pane_current_command}"

Then you can change the title of the pane by typing this in the console:

settitle titlename

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

I was trying to run a code where i wanted to read excel sheets. Issue was, if there is a file which has no sheet named say : SheetSum I am not able to move it to error location!! Code i wrote was:

def read_file(data_file):
    # data_file = '\rr\ex.xlsx'
    sheets = {}
    try:
        print("Reading file: "+data_file)
        sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
    except Exception as excpt:
        print("Exception occurred", exc_info=True)
    return sheets

read_file(file)
shutil.move( file, dirpath +'\\processed_files')

Giving Error :

[WinError 32] The process cannot access the file because it is being used by another process

I had to add full try except with finally block and tell finally i need to close the file in any case like:

def read_file(data_file):
    # data_file = '\rr\ex.xlsx'
    sheets = {}
    try:
        print("Reading file: "+data_file)
        sheets_file = open(data_file,'rb')
        sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
    except Exception as excpt:
        print("Exception occurred", exc_info=True)
    finally:
        sheets_file.close()
    return sheets

read_file(file)
shutil.move( file, dirpath +'\\processed_files')

Otherwise, file still remains open is the background.

If finally is present, it specifies a cleanup handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception.

..More Here

Javascript find json value

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;
    });
};

Example:

getObjectByValue(data, "code", "DZ" );

How can I listen for a click-and-hold in jQuery?

var timeoutId = 0;

$('#myElement').on('mousedown', function() {
    timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
    clearTimeout(timeoutId);
});

Edit: correction per AndyE...thanks!

Edit 2: using bind now for two events with same handler per gnarf

How to style SVG with external CSS?

What works for me: style tag with @import rule

<defs>
    <style type="text/css">
        @import url("svg-common.css");
    </style>
</defs>

What is the height of iPhone's onscreen keyboard?

The keyboard height depends on the model, the QuickType bar, user settings... The best approach is calculate dinamically:

Swift 3.0

    var heightKeyboard : CGFloat?

    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    }

    func keyboardShown(notification: NSNotification) {
           if let infoKey  = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
               let rawFrame = (infoKey as AnyObject).cgRectValue {
               let keyboardFrame = view.convert(rawFrame, from: nil)
               self.heightKeyboard = keyboardFrame.size.height
               // Now is stored in your heightKeyboard variable
           }
    }

OpenCV & Python - Image too big to display

Try with this code:

from PIL import Image

Image.fromarray(image).show()

How do I access command line arguments in Python?

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.

Promise Error: Objects are not valid as a React child

You can't do this: {this.state.arrayFromJson} As your error suggests what you are trying to do is not valid. You are trying to render the whole array as a React child. This is not valid. You should iterate through the array and render each element. I use .map to do that.

I am pasting a link from where you can learn how to render elements from an array with React.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Hope it helps!

How to check if a column exists in Pandas

To check if one or more columns all exist, you can use set.issubset, as in:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

As @brianpck points out in a comment, set([]) can alternatively be constructed with curly braces,

if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.

Or, you can use a list comprehension, as in:

if all([item in df.columns for item in ['A','C']]):

'cl' is not recognized as an internal or external command,

You will have to set environmental variables properly for each compiler. There are commands on your Program menu for each compiler that does that, while opening a command prompt.

Another option is of course to use the IDE for building your application.

SQL Server query to find all current database names

You can also use these ways:

EXEC sp_helpdb

and:

SELECT name FROM sys.sysdatabases

Recommended Read:

Don't forget to have a look at sysdatabases VS sys.sysdatabases

A similar thread.

How can I resize an image using Java?

The Java API does not provide a standard scaling feature for images and downgrading image quality.

Because of this I tried to use cvResize from JavaCV but it seems to cause problems.

I found a good library for image scaling: simply add the dependency for "java-image-scaling" in your pom.xml.

<dependency>
    <groupId>com.mortennobel</groupId>
    <artifactId>java-image-scaling</artifactId>
    <version>0.8.6</version>
</dependency>

In the maven repository you will get the recent version for this.

Ex. In your java program

ResampleOp resamOp = new ResampleOp(50, 40);
BufferedImage modifiedImage = resamOp.filter(originalBufferedImage, null);

What's the right way to create a date in Java?

The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);

ng-repeat finish event

<div ng-repeat="i in items">
        <label>{{i.Name}}</label>            
        <div ng-if="$last" ng-init="ngRepeatFinished()"></div>            
</div>

My solution was to add a div to call a function if the item was the last in a repeat.

Relative imports for the billionth time

I had a similar problem where I didn't want to change the Python module search path and needed to load a module relatively from a script (in spite of "scripts can't import relative with all" as BrenBarn explained nicely above).

So I used the following hack. Unfortunately, it relies on the imp module that became deprecated since version 3.4 to be dropped in favour of importlib. (Is this possible with importlib, too? I don't know.) Still, the hack works for now.

Example for accessing members of moduleX in subpackage1 from a script residing in the subpackage2 folder:

#!/usr/bin/env python3

import inspect
import imp
import os

def get_script_dir(follow_symlinks=True):
    """
    Return directory of code defining this very function.
    Should work from a module as well as from a script.
    """
    script_path = inspect.getabsfile(get_script_dir)
    if follow_symlinks:
        script_path = os.path.realpath(script_path)
    return os.path.dirname(script_path)

# loading the module (hack, relying on deprecated imp-module)
PARENT_PATH = os.path.dirname(get_script_dir())
(x_file, x_path, x_desc) = imp.find_module('moduleX', [PARENT_PATH+'/'+'subpackage1'])
module_x = imp.load_module('subpackage1.moduleX', x_file, x_path, x_desc)

# importing a function and a value
function = module_x.my_function
VALUE = module_x.MY_CONST

A cleaner approach seems to be to modify the sys.path used for loading modules as mentioned by Federico.

#!/usr/bin/env python3

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    # __file__ should be defined in this case
    PARENT_DIR = path.dirname(path.dirname(path.abspath(__file__)))
   sys.path.append(PARENT_DIR)
from subpackage1.moduleX import *

Table header to stay fixed at the top when user scrolls it out of view with jQuery

I found a simple jQuery library called Sticky Table Headers. Two lines of code and it did exactly what I wanted. The solutions above don't manage the column widths, so if you have table cells that take up a lot of space, the resulting size of the persistent header will not match your table's width.

http://plugins.jquery.com/StickyTableHeaders/

Usage info here: https://github.com/jmosbech/StickyTableHeaders

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

ASP.NET Core 1.0 on IIS error 502.5

So I got a new server, this time it's Windows 2008R2 and my app works fine.

I can't say for sure what the problem was with the old server but I have one idea.

So because I previously compiled the app without any platform in mind it gave me the dll version which only works if the target host has .Net Core Windows Hosting package installed. In my case it was installed and that was fine.

After the app didn't work I decieded to compile it as a console app with win7-x64 as runtime. This time the moment I ran the exe of my app on the server, it crashed with an error about a missing dll:

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing

That dll is from Universal C Runtime that's included in the Visual C++ Redistributable for Visual Studio 2015.

I tried to install that package (both x64 & x86) but it failed each time (don't know why) on Windows Server 2012 R2.

But when I tried to install them in the new server, Windows Server 2008 R2, they successfully installed. That might have been the reason behind it, but still can't say for sure.

Non-static variable cannot be referenced from a static context

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn't have specific keyword.

Javascript how to split newline

Good'ol javascript:

 var m = "Hello World";  
 var k = m.split(' ');  // I have used space, you can use any thing.
 for(i=0;i<k.length;i++)  
    alert(k[i]);  

REST API 404: Bad URI, or Missing Resource?

As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.

First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13, http://mywebsite/restapi/user/13 is the same as the difference between http://mywebsite/api/user/13 and http://mywebsite/api/user/14 i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14 (if there is no such user) but not necessarily the only appropriate response.

You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14 has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.

There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 is better than http://mywebsite/api/user/14. Doing that, you could use your technique of returning 200's without giving much away.

How to create Windows EventLog source from command line?

Try "eventcreate.exe"

An example:

eventcreate /ID 1 /L APPLICATION /T INFORMATION  /SO MYEVENTSOURCE /D "My first log"

This will create a new event source named MYEVENTSOURCE under APPLICATION event log as INFORMATION event type.

I think this utility is included only from XP onwards.

Further reading

regular expression to validate datetime format (MM/DD/YYYY)

you can look into this link and I hope this may be of great help as its was for me.

If you are using the regex given in the above link in Java code then use the following regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$"

As I noticed in your example you are using js function then this use regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"

This will match a date in mm/dd/yyyy format from between 1900-01-01 and 2099-12-31, with a choice of four separators. and not to forget the

return regex.test(testdate);

process.waitFor() never returns

I think I observed a similar problem: some processes started, seemed to run successfully but never completed. The function waitFor() was waiting forever except if I killed the process in Task Manager.
However, everything worked well in cases the length of the command line was 127 characters or shorter. If long file names are inevitable you may want to use environmental variables, which may allow you keeping the command line string short. You can generate a batch file (using FileWriter) in which you set your environmental variables before calling the program you actually want to run. The content of such a batch could look like:

    set INPUTFILE="C:\Directory 0\Subdirectory 1\AnyFileName"
    set OUTPUTFILE="C:\Directory 2\Subdirectory 3\AnotherFileName"
    set MYPROG="C:\Directory 4\Subdirectory 5\ExecutableFileName.exe"
    %MYPROG% %INPUTFILE% %OUTPUTFILE%

Last step is running this batch file using Runtime.

How to make a dropdown readonly using jquery?

It´s work very well

$('#cf_1268591 option:not(:selected)').prop('disabled', true);

With this I can see the options but I can't select it

Adding asterisk to required fields in Bootstrap 3

Assuming this is what the HTML looks like

<div class="form-group required">
   <label class="col-md-2 control-label">E-mail</label>
   <div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>

To display an asterisk on the right of the label:

.form-group.required .control-label:after { 
    color: #d00;
    content: "*";
    position: absolute;
    margin-left: 8px;
    top:7px;
}

Or to the left of the label:

.form-group.required .control-label:before{
   color: red;
   content: "*";
   position: absolute;
   margin-left: -15px;
}

To make a nice big red asterisks you can add these lines:

font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;

Or if you are using Font Awesome add these lines (and change the content line):

font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";

Automatic confirmation of deletion in powershell

The default is: no prompt.

You can enable it with -Confirm or disable it with -Confirm:$false

However, it will still prompt, when the target:

  • is a directory
  • and it is not empty
  • and the -Recurse parameter is not specified.

-Force is required to also remove hidden and read-only items etc.

To sum it up:

Remove-Item -Recurse -Force -Confirm:$false

...should cover all scenarios.

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

Reverse Contents in Array

Your loop will run only for count/2 times. So it will not print the whole array.

Also, temp=ar[i] should be used instead of ar[i]=temp as value of ar[i] is not getting stored anywhere in the latter statement, hence it is getting destroyed.

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

How do I pass JavaScript variables to PHP?

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

What does it mean to inflate a view from an xml file?

A layman definition for inflation might be to convert the XML code to Java code. Just a way to understand, e.g., if we have a tag in XML, OS has to create a corresponding Java object in memory, so inflatter reads the XMLtags, and creates the corresponding objects in Java.

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Ruby: Calling class method from instance

To access a class method inside a instance method, do the following:

self.class.default_make

Here is an alternative solution for your problem:

class Truck

  attr_accessor :make, :year

  def self.default_make
    "Toyota"
  end

  def make
    @make || self.class.default_make
  end

  def initialize(make=nil, year=nil)
    self.year, self.make = year, make
  end
end

Now let's use our class:

t = Truck.new("Honda", 2000)
t.make
# => "Honda"
t.year
# => "2000"

t = Truck.new
t.make
# => "Toyota"
t.year
# => nil

PHP output showing little black diamonds with a question mark

This is a charset issue. As such, it can have gone wrong on many different levels, but most likely, the strings in your database are utf-8 encoded, and you are presenting them as iso-8859-1. Or the other way around.

The proper way to fix this problem, is to get your character-sets straight. The simplest strategy, since you're using PHP, is to use iso-8859-1 throughout your application. To do this, you must ensure that:

  • All PHP source-files are saved as iso-8859-1 (Not to be confused with cp-1252).
  • Your web-server is configured to serve files with charset=iso-8859-1
  • Alternatively, you can override the webservers settings from within the PHP-document, using header.
  • In addition, you may insert a meta-tag in you HTML, that specifies the same thing, but this isn't strictly needed.
  • You may also specify the accept-charset attribute on your <form> elements.
  • Database tables are defined with encoding as latin1
  • The database connection between PHP to and database is set to latin1

If you already have data in your database, you should be aware that they are probably messed up already. If you are not already in production phase, just wipe it all and start over. Otherwise you'll have to do some data cleanup.

A note on meta-tags, since everybody misunderstands what they are:

When a web-server serves a file (A HTML-document), it sends some information, that isn't presented directly in the browser. This is known as HTTP-headers. One such header, is the Content-Type header, which specifies the mimetype of the file (Eg. text/html) as well as the encoding (aka charset). While most webservers will send a Content-Type header with charset info, it's optional. If it isn't present, the browser will instead interpret any meta-tags with http-equiv="Content-Type". It's important to realise that the meta-tag is only interpreted if the webserver doesn't send the header. In practice this means that it's only used if the page is saved to disk and then opened from there.

This page has a very good explanation of these things.

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

Applying .gitignore to committed files

Be sure that your actual repo is the lastest version

  1. Edit .gitignore as you wish
  2. git rm -r --cached . (remove all files)
  3. git add . (re-add all files)

then commit as usual

C# Encoding a text string with line breaks

Try \n\n , it will work! :)

public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}

Change value of input onchange?

for jQuery we can use below:

by input name:

$('input[name="textboxname"]').val('some value');

by input class:

$('input[type=text].textboxclass').val('some value');

by input id:

$('#textboxid').val('some value');

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

The following interface became deprecated in pip 10:

from pip.req import parse_requirements
from pip.download import PipSession

So I switched it just to simple text parsing:

with open('requirements.txt', 'r') as f:
    install_reqs = [
        s for s in [
            line.split('#', 1)[0].strip(' \t\n') for line in f
        ] if s != ''
    ]

Use 'class' or 'typename' for template parameters?

In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:

template <class IntegerType>
class smart_integer {
public: 
    typedef integer_traits<Integer> traits;
    IntegerType operator+=(IntegerType value){
        typedef typename traits::larger_integer_t larger_t;
        larger_t interm = larger_t(myValue) + larger_t(value); 
        if(interm > traits::max() || interm < traits::min())
            throw overflow();
        myValue = IntegerType(interm);
    }
}

larger_integer_t is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t is a type. class, on the otherhand, has no such overloaded meaning.

That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.

Force uninstall of Visual Studio

This is an odd solution, but it worked for me.

I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.

I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.

Using SVG as background image

You have set a fixed width and height in your svg tag. This is probably the root of your problem. Try not removing those and set the width and height (if needed) using CSS instead.

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

JavaScript Infinitely Looping slideshow with delays?

Here's a nice, tidy solution for you: (also see the live demo ->)

window.onload = function start() {
    slide();
}

function slide() {
    var currMarg = 0,
        contStyle = document.getElementById('container').style;
    setInterval(function() {
        currMarg = currMarg == 1800 ? 0 : currMarg + 600;
        contStyle.marginLeft = '-' + currMarg + 'px';
    }, 3000);
}

Since you are trying to learn, allow me to explain how this works.

First we declare two variables: currMarg and contStyle. currMarg is an integer that we will use to track/update what left margin the container should have. We declare it outside the actual update function (in a closure), so that it can be continuously updated/access without losing its value. contStyle is simply a convenience variable that gives us access to the containers styles without having to locate the element on each interval.

Next, we will use setInterval to establish a function which should be called every 3 seconds, until we tell it to stop (there's your infinite loop, without freezing the browser). It works exactly like setTimeout, except it happens infinitely until cancelled, instead of just happening once.

We pass an anonymous function to setInterval, which will do our work for us. The first line is:

currMarg = currMarg == 1800 ? 0 : currMarg + 600;

This is a ternary operator. It will assign currMarg the value of 0 if currMarg is equal to 1800, otherwise it will increment currMarg by 600.

With the second line, we simply assign our chosen value to containers marginLeft, and we're done!

Note: For the demo, I changed the negative values to positive, so the effect would be visible.

How to execute mongo commands through shell scripts?

There is an official documentation page about this as well.

Examples from that page include:

mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"

C++ template constructor

You could do this:

class C 
{
public:
    template <typename T> C(T*);
};
template <typename T> T* UseType() 
{
    static_cast<T*>(nullptr);
}

Then to create an object of type C using int as the template parameter to the constructor:

C obj(UseType<int>());

Since you can't pass template parameters to a constructor, this solution essentially converts the template parameter to a regular parameter. Using the UseType<T>() function when calling the constructor makes it clear to someone looking at the code that the purpose of that parameter is to tell the constructor what type to use.

One use case for this would be if the constructor creates a derived class object and assigns it to a member variable that is a base class pointer. (The constructor needs to know which derived class to use, but the class itself doesn't need to be templated since the same base class pointer type is always used.)

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

scroll image with continuous scrolling using marquee tag

I think you set the marquee width related to 5 images total width. It works fine

ex: <marquee style="width:700px"></marquee>

How do I allow HTTPS for Apache on localhost?

For those using macOS this is a great guide https://getgrav.org/blog/macos-sierra-apache-multiple-php-versions to set up your local web dev environment. In its 3rd part https://getgrav.org/blog/macos-sierra-apache-ssl Andy Miller explains how to set up apache with a self-signed certificate:

This is the key command:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt

But there are a few steps you need to follow, so check that out and good luck! ;)

Loading resources using getClass().getResource()

You can request a path in this format:

/package/path/to/the/resource.ext

Even the bytes for creating the classes in memory are found this way:

my.Class -> /my/Class.class

and getResource will give you a URL which can be used to retrieve an InputStream.

But... I'd recommend using directly getClass().getResourceAsStream(...) with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.

In short: try using getResourceAsStream and some constructor of ImageIcon that uses an InputStream as an argument.

Classloaders

Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon was capable of finding it.

Edit: classpath

getResource is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.

How does Java resolve a relative path in new File()?

The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.

Relative paths are ones that start without a drive specifier. So in linux they don't start with a /, in windows they don't start with a C:\, etc. These always start from your working directory.

Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.

Gradient text color

The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.

For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):

  • The gradient starts at color #f22 at 0% (that is the left edge of the element). First color is always assumed to start at 0% even though the percentage is not mentioned explicitly.
  • Between 0% to 14.25%, the color changes from #f22 to #f2f gradually. The percenatge is set at 14.25 because there are seven color changes and we are looking for equal splits.
  • At 14.25% (of the container's size), the color will exactly be #f2f as per the gradient specified.
  • Similarly the colors change from one to another depending on the bands specified by color stop percentages. Each band should be a step of 14.25%.

So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
  color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
_x000D_
_x000D_

Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text.

(Note that the background-clip: text is an experimental property and is not supported widely.)


Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:

  • First parameter is the direction of the gradient. If the color should be red at left side and brown at the right side then use the direction as to right. If it should be red at right and brown at left then give the direction as to left.
  • Next step is to define the colors of the gradient. Since our gradient should start as red on the left side, just specify red as the first color (percentage is assumed to be 0%).
  • Now, since we have two color changes (red - orange and orange - brown), the percentages must be set as 100 / 2 for equal splits. If equal splits are not required, we can assign the percentages as we wish.
  • So at 50% the color should be orange and then the final color would be brown. The position of the final color is always assumed to be at 100%.

Thus the gradient's specification should read as follows:

background-image: linear-gradient(to right, red, orange 50%, brown).

If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.

_x000D_
_x000D_
.red-orange-brown {_x000D_
  background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
  background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
_x000D_
_x000D_

How to grep Git commit diffs or contents for a certain word?

If you want to find all commits where commit message contains given word, use

$ git log --grep=word

If you want to find all commits where "word" was added or removed in the file contents (to be more exact: where number of occurences of "word" changed), i.e. search the commit contents, use so called 'pickaxe' search with

$ git log -Sword

In modern git there is also

$ git log -Gword

to look for differences whose added or removed line matches "word" (also commit contents).

Note that -G by default accepts a regex, while -S accepts a string, but can be modified to accept regexes using the --pickaxe-regex.

To illustrate the difference between -S<regex> --pickaxe-regex and -G<regex>, consider a commit with the following diff in the same file:

+    return !regexec(regexp, two->ptr, 1, &regmatch, 0);
...
-    hit = !regexec(regexp, mf2.ptr, 1, &regmatch, 0);

While git log -G"regexec\(regexp" will show this commit, git log -S"regexec\(regexp" --pickaxe-regex will not (because the number of occurrences of that string did not change).


With Git 2.25.1 (Feb. 2020), the documentation is clarified around those regexes.

See commit 9299f84 (06 Feb 2020) by Martin Ågren (``).
(Merged by Junio C Hamano -- gitster -- in commit 0d11410, 12 Feb 2020)

diff-options.txt: avoid "regex" overload in example

Reported-by: Adam Dinwoodie
Signed-off-by: Martin Ågren
Reviewed-by: Taylor Blau

When we exemplify the difference between -G and -S (using --pickaxe-regex), we do so using an example diff and git diff invocation involving "regexec", "regexp", "regmatch", ...

The example is correct, but we can make it easier to untangle by avoiding writing "regex.*" unless it's really needed to make our point.

Use some made-up, non-regexy words instead.

The git diff documentation now includes:

To illustrate the difference between -S<regex> --pickaxe-regex and -G<regex>, consider a commit with the following diff in the same file:

+    return frotz(nitfol, two->ptr, 1, 0);
...
-    hit = frotz(nitfol, mf2.ptr, 1, 0);

While git log -G"frotz\(nitfol" will show this commit, git log -S"frotz\(nitfol" --pickaxe-regex will not (because the number of occurrences of that string did not change).

Can inner classes access private variables?

An inner class is a friend of the class it is defined within.
So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer.

Unlike Java though, there is no correlation between an object of type Outer::Inner and an object of the parent class. You have to make the parent child relationship manually.

#include <string>
#include <iostream>

class Outer
{
    class Inner
    {
        public:
            Inner(Outer& x): parent(x) {}
            void func()
            {
                std::string a = "myconst1";
                std::cout << parent.var << std::endl;

                if (a == MYCONST)
                {   std::cout << "string same" << std::endl;
                }
                else
                {   std::cout << "string not same" << std::endl;
                }
            }
        private:
            Outer&  parent;
    };

    public:
        Outer()
            :i(*this)
            ,var(4)
        {}
        Outer(Outer& other)
            :i(other)
            ,var(22)
        {}
        void func()
        {
            i.func();
        }
    private:
        static const char* const MYCONST;
        Inner i;
        int var;
};

const char* const Outer::MYCONST = "myconst";

int main()
{

    Outer           o1;
    Outer           o2(o1);
    o1.func();
    o2.func();
}

How to validate an OAuth 2.0 access token for a resource server?

OAuth 2.0 spec doesn't define the part. But there could be couple of options:

  1. When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.

  2. Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.

FORCE INDEX in MySQL - where do I put it?

The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html

FORCE INDEX goes right after the table reference:

SELECT * FROM (
    SELECT owner_id,
           product_id,
           start_time,
           price,
           currency,
           name,
           closed,
           active,
           approved,
           deleted,
           creation_in_progress
    FROM db_products FORCE INDEX (products_start_time)
    ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
      AND resultstable.active = 1
      AND resultstable.approved = 1
      AND resultstable.deleted = 0
      AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC

WARNING:

If you're using ORDER BY before GROUP BY to get the latest entry per owner_id, you're using a nonstandard and undocumented behavior of MySQL to do that.

There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.

Search the tag for many explanations of better solutions for this type of query.

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}

Max parallel http connections in a browser?

  1. Yes, wildcard domain will work for you.
  2. Not aware of any limits on connections. Limits if any will be browser specific.

Powershell v3 Invoke-WebRequest HTTPS error

  1. Run this command

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}

in powershell using admin rights, This will generate all certificates in Personal directory

  1. To get rid of Privacy error, select these certificates, right click ? Copy. And paste in Trusted Root Certification Authority/Certificates.
  2. Last step is to select correct bindings in IIS. Go to IIS website, select Bindings, Select SNI checkbox and set the individual certificates for each website.

Make sure website hostname and certificate dns-name should exactly match

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

Adding POST parameters before submit

you can do this without jQuery:

    var form=document.getElementById('form-id');//retrieve the form as a DOM element

    var input = document.createElement('input');//prepare a new input DOM element
    input.setAttribute('name', inputName);//set the param name
    input.setAttribute('value', inputValue);//set the value
    input.setAttribute('type', inputType)//set the type, like "hidden" or other

    form.appendChild(input);//append the input to the form

    form.submit();//send with added input

how to get right offset of an element? - jQuery

Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).

var offset = $('#whatever').offset();

offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));

Read lines from a file into a Bash array

#!/bin/bash
IFS=$'\n' read  -d'' -r -a inlines  < testinput
IFS=$'\n' read  -d'' -r -a  outlines < testoutput
counter=0
cat testinput | while read line; 
do
    echo "$((${inlines[$counter]}-${outlines[$counter]}))"
    counter=$(($counter+1))
done
# OR Do like this
counter=0
readarray a < testinput
readarray b < testoutput
cat testinput | while read myline; 
do
    echo value is: $((${a[$counter]}-${b[$counter]}))
    counter=$(($counter+1))
done

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I experienced this issue when calling my web api endpoint and solved it.

In my case it was an issue in the way the client was encoding the body content. I was not specifying the encoding or media type. Specifying them solved it.

Not specifying encoding type, caused 415 error:

var content = new StringContent(postData);
httpClient.PostAsync(uri, content);

Specifying the encoding and media type, success:

var content = new StringContent(postData, Encoding.UTF8, "application/json");
httpClient.PostAsync(uri, content);

Powershell: How can I stop errors from being displayed in a script?

If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"

Verify a certificate chain using openssl verify

I've had to do a verification of a letsencrypt certificate and I did it like this:

  1. Download the root-cert and the intermediate-cert from the letsencrypt chain of trust.
  2. Issue this command:

    $ openssl verify -CAfile letsencrypt-root-cert/isrgrootx1.pem.txt -untrusted letsencrypt-intermediate-cert/letsencryptauthorityx3.pem.txt /etc/letsencrypt/live/sitename.tld/cert.pem 
    /etc/letsencrypt/live/sitename.tld/cert.pem: OK
    

Android Studio - How to Change Android SDK Path

EUREKA I found it!

With the current Studio 1.3 each project has a local.properties file where you can edit the SDK!