Programs & Examples On #Xsd2code

Xsd2Code is a CSharp or Visual Basic Business Entity class Generator from XSD schema.

Zoom in on a point (using scale and translate)

I want to put here some information for those, who do separately drawing of picture and moving -zooming it.

This may be useful when you want to store zooms and position of viewport.

Here is drawer:

function redraw_ctx(){
   self.ctx.clearRect(0,0,canvas_width, canvas_height)
   self.ctx.save()
   self.ctx.scale(self.data.zoom, self.data.zoom) // 
   self.ctx.translate(self.data.position.left, self.data.position.top) // position second
   // Here We draw useful scene My task - image:
   self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
   self.ctx.restore(); // Restore!!!
}

Notice scale MUST be first.

And here is zoomer:

function zoom(zf, px, py){
    // zf - is a zoom factor, which in my case was one of (0.1, -0.1)
    // px, py coordinates - is point within canvas 
    // eg. px = evt.clientX - canvas.offset().left
    // py = evt.clientY - canvas.offset().top
    var z = self.data.zoom;
    var x = self.data.position.left;
    var y = self.data.position.top;

    var nz = z + zf; // getting new zoom
    var K = (z*z + z*zf) // putting some magic

    var nx = x - ( (px*zf) / K ); 
    var ny = y - ( (py*zf) / K);

    self.data.position.left = nx; // renew positions
    self.data.position.top = ny;   
    self.data.zoom = nz; // ... and zoom
    self.redraw_ctx(); // redraw context
    }

and, of course, we would need a dragger:

this.my_cont.mousemove(function(evt){
    if (is_drag){
        var cur_pos = {x: evt.clientX - off.left,
                       y: evt.clientY - off.top}
        var diff = {x: cur_pos.x - old_pos.x,
                    y: cur_pos.y - old_pos.y}

        self.data.position.left += (diff.x / self.data.zoom);  // we want to move the point of cursor strictly
        self.data.position.top += (diff.y / self.data.zoom);

        old_pos = cur_pos;
        self.redraw_ctx();

    }


})

Ignoring upper case and lower case in Java

use toUpperCase() or toLowerCase() method of String class.

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

how to get the first and last days of a given month

You might want to look at the strtotime and date functions.

<?php

$query_date = '2010-02-04';

// First day of the month.
echo date('Y-m-01', strtotime($query_date));

// Last day of the month.
echo date('Y-m-t', strtotime($query_date));

How do I do pagination in ASP.NET MVC?

Controller

 [HttpGet]
    public async Task<ActionResult> Index(int page =1)
    {
        if (page < 0 || page ==0 )
        {
            page = 1;
        }
        int pageSize = 5;
        int totalPage = 0;
        int totalRecord = 0;
        BusinessLayer bll = new BusinessLayer();
        MatchModel matchmodel = new MatchModel();
        matchmodel.GetMatchList = bll.GetMatchCore(page, pageSize, out totalRecord, out totalPage);
        ViewBag.dbCount = totalPage;
        return View(matchmodel);
    }

BusinessLogic

  public List<Match> GetMatchCore(int page, int pageSize, out int totalRecord, out int totalPage)
    {
        SignalRDataContext db = new SignalRDataContext();
        var query = new List<Match>();
        totalRecord = db.Matches.Count();
        totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
        query = db.Matches.OrderBy(a => a.QuestionID).Skip(((page - 1) * pageSize)).Take(pageSize).ToList();
        return query;
    }

View for displaying total page count

 if (ViewBag.dbCount != null)
    {
        for (int i = 1; i <= ViewBag.dbCount; i++)
        {
            <ul class="pagination">
                <li>@Html.ActionLink(@i.ToString(), "Index", "Grid", new { page = @i },null)</li> 
            </ul>
        }
    }

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

HTML5 Email input pattern attribute

<input name="email" type="email" pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$" class="form-control" placeholder="Email*" id="email" required="">

This is modified version of above solution which accept capital letter as well.

How can I delete a newline if it is the last character in a file?

head -n -1 abc > newfile
tail -n 1 abc | tr -d '\n' >> newfile

Edit 2:

Here is an awk version (corrected) that doesn't accumulate a potentially huge array:

awk '{if (line) print line; line=$0} END {printf $0}' abc

Google Chrome redirecting localhost to https

A lazy and fast solution for lazy people like me (working in Chrome 67).

Just launch another Chrome window in Stealth Mode, with the "Incognito Window" option (CTRL + SHIFT + N). No need to delete cache, no need to dive into deep Chrome settings, etc.

Should I use JSLint or JSHint JavaScript validation?

Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.

Declare all the global var in that file like:

/*global require,dojo,dojoConfig,alert */

Declare all the lint settings like:

/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */

Hope this will help you :)

How to iterate over a std::map full of strings in C++

Your main problem is that you are calling a method called first() in the iterator. What you are meant to do is use the property called first:

...append(iter->first) rather than ...append(iter->first())

As a matter of style, you shouldn't be using new to create that string.

std::string something::toString() 
{
        std::map<std::string, std::string>::iterator iter;
        std::string strToReturn; //This is no longer on the heap

        for (iter = table.begin(); iter != table.end(); ++iter) {
           strToReturn.append(iter->first); //Not a method call
           strToReturn.append("=");
           strToReturn.append(iter->second);
           //....
           // Make sure you don't modify table here or the iterators will not work as you expect
        }
        //...
        return strToReturn;
}

edit: facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop

for (auto& item: table) {
    ...
}

How to use global variables in React Native?

You can consider leveraging React's Context feature.

class NavigationContainer extends React.Component {
    constructor(props) {
        super(props);
        this.goTo = this.goTo.bind(this);
    }
    goTo(location) {
        ...
    }
    getChildContext() {
        // returns the context to pass to children
        return {
            goTo: this.goTo
        }
    }
    ...
}

// defines the context available to children
NavigationContainer.childContextTypes = {
    goTo: PropTypes.func
}

class SomeViewContainer extends React.Component {
    render() {
        // grab the context provided by ancestors
        const {goTo} = this.context;
        return <button onClick={evt => goTo('somewhere')}>
            Hello
        </button>
    }
}

// Define the context we want from ancestors
SomeViewContainer.contextTypes = {
    goTo: PropTypes.func
}

With context, you can pass data through the component tree without having to pass the props down manually at every level. There is a big warning on this being an experimental feature and may break in the future, but I would imagine this feature to be around given the majority of the popular frameworks like Redux use context extensively.

The main advantage of using context v.s. a global variable is context is "scoped" to a subtree (this means you can define different scopes for different subtrees).

Do note that you should not pass your model data via context, as changes in context will not trigger React's component render cycle. However, I do find it useful in some use case, especially when implementing your own custom framework or workflow.

how to convert long date value to mm/dd/yyyy format

Try this example

 String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html

Switch in Laravel 5 - Blade

To overcome the space in 'switch ()', you can use code :

Blade::extend(function($value, $compiler){
    $value = preg_replace('/(\s*)@switch[ ]*\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
    $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
    $value = preg_replace('/(\s*)@case[ ]*\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
    $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
    $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
    return $value;
  });

How can I select rows by range?

You can use rownum :

SELECT * FROM table WHERE rownum > 10 and rownum <= 20

Git mergetool generates unwanted .orig files

git config --global mergetool.keepBackup false

This should work for Beyond Compare (as mergetool) too

Customize the Authorization HTTP header

You can create your own custom auth schemas that use the Authorization: header - for example, this is how OAuth works.

As a general rule, if servers or proxies don't understand the values of standard headers, they will leave them alone and ignore them. It is creating your own header keys that can often produce unexpected results - many proxies will strip headers with names they don't recognise.

Having said that, it is possibly a better idea to use cookies to transmit the token, rather than the Authorization: header, for the simple reason that cookies were explicitly designed to carry custom values, whereas the specification for HTTP's built in auth methods does not really say either way - if you want to see exactly what it does say, have a look here.

The other point about this is that many HTTP client libraries have built-in support for Digest and Basic auth but may make life more difficult when trying to set a raw value in the header field, whereas they will all provide easy support for cookies and will allow more or less any value within them.

How to convert String into Hashmap in java

This is one solution. If you want to make it more generic, you can use the StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

Generating sql insert into for Oracle

You might execute something like this in the database:

select "insert into targettable(field1, field2, ...) values(" || field1 || ", " || field2 || ... || ");"
from targettable;

Something more sophisticated is here.

Assign null to a SqlParameter

A simple extension method for this would be:

    public static void AddParameter(this SqlCommand sqlCommand, string parameterName, 
        SqlDbType sqlDbType, object item)
    {
        sqlCommand.Parameters.Add(parameterName, sqlDbType).Value = item ?? DBNull.Value;
    }

Using regular expressions to do mass replace in Notepad++ and Vim

It may help if you're less specific. Your expression there is "greedy", which may be interpreted different ways by different programs. Try this in vim:

%s/^<[^>]+>//

How to close <img> tag properly?

This one is valid HTML5 and it is absolutely fine without closing it. It is a so-called void element:

<img src='stackoverflow.png'>

The following are valid XHTML tags. They have to be closed. The later one is also fine in HTML 5:

<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

I've tried all examples, posted here, but they do not work without extra CSS. Try this:

<a href="http://www.google.com"><button type="button" class="btn btn-success">Google</button></a>

Works perfectly without any extra CSS.

Clear back stack using fragments

I posted something similar here

From Joachim's answer, from Dianne Hackborn:

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

I ended up just using:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

But could equally have used something like:

((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one. You can then just replace the fragment with what you want

C++: How to round a double to an int?

Casting is not a mathematical operation and doesn't behave as such. Try

int y = (int)round(x);

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Do this:

date('Y-m-d', strtotime('dd/mm/yyyy'));

But make sure 'dd/mm/yyyy' is the actual date.

Split function equivalent in T-SQL?

Using tally table here is one split string function(best possible approach) by Jeff Moden

CREATE FUNCTION [dbo].[DelimitedSplit8K]
        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover NVARCHAR(4000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;

Referred from Tally OH! An Improved SQL 8K “CSV Splitter” Function

iterating and filtering two lists using java 8

// produce the filter set by streaming the items from list 2
// assume list2 has elements of type MyClass where getStr gets the
// string that might appear in list1
Set<String> unavailableItems = list2.stream()
    .map(MyClass::getStr)
    .collect(Collectors.toSet());

// stream the list and use the set to filter it
List<String> unavailable = list1.stream()
            .filter(e -> unavailableItems.contains(e))
            .collect(Collectors.toList());

How to find specified name and its value in JSON-string from Java?

I agree that Google's Gson is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple:

// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;

@Test
public void json2Object() {
    // given
    String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
            + "\"address\" : \"some address\","
            + "\"someobject\" : {\"field\" : \"value\"}}";

    // when
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);

    // then
    @SuppressWarnings("unchecked")
    Set<String> keySet = object.keySet();
    for (String key : keySet) {
        Object value = object.get(key);
        System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
                .getSimpleName());
    }

    assertThat(object.get("age").toString(), is("20"));
}

Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. The object you define is clear for all fields (name and type), but less flexible than Map.

HTML.ActionLink method

Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item") 

Objective-C: Reading a file line by line

I found response by @lukaswelte and code from Dave DeLong very helpful. I was looking for a solution to this problem but needed to parse large files by \r\n not just \n.

The code as written contains a bug if parsing by more than one character. I've changed the code as below.

.h file:

#import <Foundation/Foundation.h>

@interface FileChunkReader : NSObject {
    NSString * filePath;

    NSFileHandle * fileHandle;
    unsigned long long currentOffset;
    unsigned long long totalFileLength;

    NSString * lineDelimiter;
    NSUInteger chunkSize;
}

@property (nonatomic, copy) NSString * lineDelimiter;
@property (nonatomic) NSUInteger chunkSize;

- (id) initWithFilePath:(NSString *)aPath;

- (NSString *) readLine;
- (NSString *) readTrimmedLine;

#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL *))block;
#endif

@end

.m file:

#import "FileChunkReader.h"

@interface NSData (DDAdditions)

- (NSRange) rangeOfData_dd:(NSData *)dataToFind;

@end

@implementation NSData (DDAdditions)

- (NSRange) rangeOfData_dd:(NSData *)dataToFind {

    const void * bytes = [self bytes];
    NSUInteger length = [self length];

    const void * searchBytes = [dataToFind bytes];
    NSUInteger searchLength = [dataToFind length];
    NSUInteger searchIndex = 0;

    NSRange foundRange = {NSNotFound, searchLength};
    for (NSUInteger index = 0; index < length; index++) {
        if (((char *)bytes)[index] == ((char *)searchBytes)[searchIndex]) {
            //the current character matches
            if (foundRange.location == NSNotFound) {
                foundRange.location = index;
            }
            searchIndex++;
            if (searchIndex >= searchLength)
            {
                return foundRange;
            }
        } else {
            searchIndex = 0;
            foundRange.location = NSNotFound;
        }
    }

    if (foundRange.location != NSNotFound
        && length < foundRange.location + foundRange.length )
    {
        // if the dataToFind is partially found at the end of [self bytes],
        // then the loop above would end, and indicate the dataToFind is found
        // when it only partially was.
        foundRange.location = NSNotFound;
    }

    return foundRange;
}

@end

@implementation FileChunkReader

@synthesize lineDelimiter, chunkSize;

- (id) initWithFilePath:(NSString *)aPath {
    if (self = [super init]) {
        fileHandle = [NSFileHandle fileHandleForReadingAtPath:aPath];
        if (fileHandle == nil) {
            return nil;
        }

        lineDelimiter = @"\n";
        currentOffset = 0ULL; // ???
        chunkSize = 128;
        [fileHandle seekToEndOfFile];
        totalFileLength = [fileHandle offsetInFile];
        //we don't need to seek back, since readLine will do that.
    }
    return self;
}

- (void) dealloc {
    [fileHandle closeFile];
    currentOffset = 0ULL;

}

- (NSString *) readLine {
    if (currentOffset >= totalFileLength)
    {
        return nil;
    }

    @autoreleasepool {

        NSData * newLineData = [lineDelimiter dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandle seekToFileOffset:currentOffset];
        unsigned long long originalOffset = currentOffset;
        NSMutableData *currentData = [[NSMutableData alloc] init];
        NSData *currentLine = [[NSData alloc] init];
        BOOL shouldReadMore = YES;


        while (shouldReadMore) {
            if (currentOffset >= totalFileLength)
            {
                break;
            }

            NSData * chunk = [fileHandle readDataOfLength:chunkSize];
            [currentData appendData:chunk];

            NSRange newLineRange = [currentData rangeOfData_dd:newLineData];

            if (newLineRange.location != NSNotFound) {

                currentOffset = originalOffset + newLineRange.location + newLineData.length;
                currentLine = [currentData subdataWithRange:NSMakeRange(0, newLineRange.location)];

                shouldReadMore = NO;
            }else{
                currentOffset += [chunk length];
            }
        }

        if (currentLine.length == 0 && currentData.length > 0)
        {
            currentLine = currentData;
        }

        return [[NSString alloc] initWithData:currentLine encoding:NSUTF8StringEncoding];
    }
}

- (NSString *) readTrimmedLine {
    return [[self readLine] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

#if NS_BLOCKS_AVAILABLE
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL*))block {
    NSString * line = nil;
    BOOL stop = NO;
    while (stop == NO && (line = [self readLine])) {
        block(line, &stop);
    }
}
#endif

@end

Load a Bootstrap popover content with AJAX. Is this possible?

  $('[data-poload]').popover({
    content: function(){
      var div_id =  "tmp-id-" + $.now();
      return details_in_popup($(this).data('poload'), div_id, $(this));
    },
    delay: 500,

    trigger: 'hover',
    html:true
  });

  function details_in_popup(link, div_id, el){
      $.ajax({
          url: link,
          cache:true,
          success: function(response){
              $('#'+div_id).html(response);
              el.data('bs.popover').options.content = response;
          }
      });
      return '<div id="'+ div_id +'"><i class="fa fa-spinner fa-spin"></i></div>';
  }   

Ajax content is loaded once! see el.data('bs.popover').options.content = response;

Generate signed apk android studio

Read this my answer here

How do I export a project in the Android studio?

This will guide you step by step to generate signed APK and how to create keystore file from Android Studio.

From the link you can do it easily as I added the screenshot of it step by step.

Short answer

If you have Key-store file then you can do same simply.

Go to Build then click on Generate Signed APK

How do I run Visual Studio as an administrator by default?

Try the following steps on Windows 10:

  • Search for Visual Studio on the Start window and select "Open file location":

    enter image description here

  • Select "Troubleshoot compatibility" :

    trouble shoot

  • Select "troubleshoot program":

    tobleshoot

    • Raise permissions:

    raise permissions

  • Select "Yes, save these settings for this program"

  • Select "Close"

Once that is done, Visual Studio should be running as administrator.

Export specific rows from a PostgreSQL table as INSERT SQL script

For my use-case I was able to simply pipe to grep.

pg_dump -U user_name --data-only --column-inserts -t nyummy.cimory | grep "tokyo" > tokyo.sql

How to get the data-id attribute?

Surprised no one mentioned:

<select id="selectVehicle">
     <option value="1" data-year="2011">Mazda</option>
     <option value="2" data-year="2015">Honda</option>
     <option value="3" data-year="2008">Mercedes</option>
     <option value="4" data-year="2005">Toyota</option>
    </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

Converting dictionary to JSON

json.dumps() is used to decode JSON data

  • json.loads take a string as input and returns a dictionary as output.
  • json.dumps take a dictionary as input and returns a string as output.
import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

Python Pandas : pivot table with aggfunc = count unique distinct

For best performance I recommend doing DataFrame.drop_duplicates followed up aggfunc='count'.

Others are correct that aggfunc=pd.Series.nunique will work. This can be slow, however, if the number of index groups you have is large (>1000).

So instead of (to quote @Javier)

df2.pivot_table('X', 'Y', 'Z', aggfunc=pd.Series.nunique)

I suggest

df2.drop_duplicates(['X', 'Y', 'Z']).pivot_table('X', 'Y', 'Z', aggfunc='count')

This works because it guarantees that every subgroup (each combination of ('Y', 'Z')) will have unique (non-duplicate) values of 'X'.

How to change default format at created_at and updated_at value laravel

Use Carbon\Carbon;

$targetDate =  "2014-06-26 04:07:31";
Carbon::parse($targetDate)->format('Y-m-d');

What is your most productive shortcut with Vim?

CTRL + A increments the number you are standing on.

Python Pandas iterate over rows and access column names

How to iterate efficiently

If you really have to iterate a Pandas dataframe, you will probably want to avoid using iterrows(). There are different methods and the usual iterrows() is far from being the best. itertuples() can be 100 times faster.

In short:

  • As a general rule, use df.itertuples(name=None). In particular, when you have a fixed number columns and less than 255 columns. See point (3)
  • Otherwise, use df.itertuples() except if your columns have special characters such as spaces or '-'. See point (2)
  • It is possible to use itertuples() even if your dataframe has strange columns by using the last example. See point (4)
  • Only use iterrows() if you cannot the previous solutions. See point (1)

Different methods to iterate over rows in a Pandas dataframe:

Generate a random dataframe with a million rows and 4 columns:

    df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 4)), columns=list('ABCD'))
    print(df)

1) The usual iterrows() is convenient, but damn slow:

start_time = time.clock()
result = 0
for _, row in df.iterrows():
    result += max(row['B'], row['C'])

total_elapsed_time = round(time.clock() - start_time, 2)
print("1. Iterrows done in {} seconds, result = {}".format(total_elapsed_time, result))

2) The default itertuples() is already much faster, but it doesn't work with column names such as My Col-Name is very Strange (you should avoid this method if your columns are repeated or if a column name cannot be simply converted to a Python variable name).:

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row.B, row.C)

total_elapsed_time = round(time.clock() - start_time, 2)
print("2. Named Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

3) The default itertuples() using name=None is even faster but not really convenient as you have to define a variable per column.

start_time = time.clock()
result = 0
for(_, col1, col2, col3, col4) in df.itertuples(name=None):
    result += max(col2, col3)

total_elapsed_time = round(time.clock() - start_time, 2)
print("3. Itertuples done in {} seconds, result = {}".format(total_elapsed_time, result))

4) Finally, the named itertuples() is slower than the previous point, but you do not have to define a variable per column and it works with column names such as My Col-Name is very Strange.

start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])

total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))

Output:

         A   B   C   D
0       41  63  42  23
1       54   9  24  65
2       15  34  10   9
3       39  94  82  97
4        4  88  79  54
...     ..  ..  ..  ..
999995  48  27   4  25
999996  16  51  34  28
999997   1  39  61  14
999998  66  51  27  70
999999  51  53  47  99

[1000000 rows x 4 columns]

1. Iterrows done in 104.96 seconds, result = 66151519
2. Named Itertuples done in 1.26 seconds, result = 66151519
3. Itertuples done in 0.94 seconds, result = 66151519
4. Polyvalent Itertuples working even with special characters in the column name done in 2.94 seconds, result = 66151519

This article is a very interesting comparison between iterrows and itertuples

Use a JSON array with objects with javascript

_x000D_
_x000D_
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
_x000D_
_x000D_

how to get param in method post spring mvc?

When I want to get all the POST params I am using the code below,

@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
    // Source..
}

I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

Dictionary of dictionaries in Python?

If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:

def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]

Encode html entities in javascript

htmlentities() converts HTML Entities

So we build a constant that will contain our html tags we want to convert.

const htmlEntities = [ 
    {regex:'&',entity:'&amp;'},
    {regex:'>',entity:'&gt;'},
    {regex:'<',entity:'&lt;'} 
  ];

We build a function that will convert all corresponding html characters to string : Html ==> String

 function htmlentities (s){
    var reg; 
    for (v in htmlEntities) {
      reg = new RegExp(htmlEntities[v].regex, 'g');
      s = s.replace(reg, htmlEntities[v].entity);
    }
    return s;
  }

To decode, we build a reverse function that will convert all string to their equivalent html . String ==> html

 function  html_entities_decode (s){
    var reg; 
    for (v in htmlEntities) {
      reg = new RegExp(htmlEntities[v].entity, 'g');
      s = s.replace(reg, htmlEntities[v].regex);
    }
    return s;
  
   }

After, We can encode all others special characters (é è ...) with encodeURIComponent()

Use Case

 var s  = '<div> God bless you guy   </div> '
 var h = encodeURIComponent(htmlentities(s));         /** To encode */
 h =  html_entities_decode(decodeURIComponent(h));     /** To decode */

Regular Expression For Duplicate Words

Try this with below RE

  • \b start of word word boundary
  • \W+ any word character
  • \1 same word matched already
  • \b end of word
  • ()* Repeating again

    public static void main(String[] args) {
    
        String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);
    
        Scanner in = new Scanner(System.in);
    
        int numSentences = Integer.parseInt(in.nextLine());
    
        while (numSentences-- > 0) {
            String input = in.nextLine();
    
            Matcher m = p.matcher(input);
    
            // Check for subsequences of input that match the compiled pattern
            while (m.find()) {
                input = input.replaceAll(m.group(0),m.group(1));
            }
    
            // Prints the modified sentence.
            System.out.println(input);
        }
    
        in.close();
    }
    

How can I start and check my MySQL log?

Enable general query log by the following query in mysql command line

SET GLOBAL general_log = 'ON';

Now open C:/xampp/mysql/data/mysql.log and check query log

If it fails, open your my.cnf file. For windows its my.ini file and enable it there. Just make sure its in the [mysqld] section

[mysqld]
general_log             = 1

Note: In xampp my.ini file can be either found in xampp\mysql or in c:\windows directory

#ifdef replacement in the Swift language

My two cents for Xcode 8:

a) A custom flag using the -D prefix works fine, but...

b) Simpler use:

In Xcode 8 there is a new section: "Active Compilation Conditions", already with two rows, for debug and release.

Simply add your define WITHOUT -D.

What is the difference between `sorted(list)` vs `list.sort()`?

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

enum Values to NSString (iOS)

Here is a plug-and-play solution that you can extend with a simple copy and paste of your EXISTING definitions.

I hope you all find it useful, as I have found useful so many other StackOverflow solutions.

- (NSString*) enumItemNameForPrefix:(NSString*)enumPrefix item:(int)enumItem {
NSString* enumList = nil;
if ([enumPrefix isEqualToString:@"[Add Your Enum Name Here"]) {
    // Instructions:
    // 1) leave all code as is (it's good reference and won't conflict)
    // 2) add your own enums below as follows:
    //    2.1) duplicate the LAST else block below and add as many enums as you like
    //    2.2) Copy then Paste your list, including carraige returns
    //    2.3) add a back slash at the end of each line to concatenate the broken string
    // 3) your are done.
}
else if ([enumPrefix isEqualToString:@"ExampleNonExplicitType"]) {
    enumList = @" \
    ExampleNonExplicitTypeNEItemName1, \
    ExampleNonExplicitTypeNEItemName2, \
    ExampleNonExplicitTypeNEItemName3 \
    ";
}
else if ([enumPrefix isEqualToString:@"ExampleExplicitAssignsType"]) {
    enumList = @" \
    ExampleExplicitAssignsTypeEAItemName1 = 1, \
    ExampleExplicitAssignsTypeEAItemName2 = 2, \
    ExampleExplicitAssignsTypeEAItemName3 = 4 \
    ";
}
else if ([enumPrefix isEqualToString:@"[Duplicate and Add Your Enum Name Here #1"]) {
    // Instructions:
    // 1) duplicate this else block and add as many enums as you like
    // 2) Paste your list, including carraige returns
    // 3) add a back slash at the end of each line to continue/concatenate the broken string
    enumList = @" \
    [Replace only this line: Paste your Enum Definition List Here] \
    ";
}

// parse it
int implicitIndex = 0;
NSString* itemKey = nil;
NSString* itemValue = nil;
NSArray* enumArray = [enumList componentsSeparatedByString:@","];
NSMutableDictionary* enumDict = [[[NSMutableDictionary alloc] initWithCapacity:enumArray.count] autorelease];

for (NSString* itemPair in enumArray) {
    NSArray* itemPairArray = [itemPair componentsSeparatedByString:@"="];
    itemValue = [[itemPairArray objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    itemKey = [NSString stringWithFormat:@"%d", implicitIndex];
    if (itemPairArray.count > 1)
        itemKey = [[itemPairArray lastObject] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [enumDict setValue:itemValue forKey:itemKey];
    implicitIndex++;
}

// return value with or without prefix
NSString* withPrefix = [enumDict valueForKey:[NSString stringWithFormat:@"%d", enumItem]];
NSString* withoutPrefix = [withPrefix stringByReplacingOccurrencesOfString:enumPrefix withString:@""];
NSString* outValue = (0 ? withPrefix : withoutPrefix);
if (0) NSLog(@"enum:%@ item:%d retVal:%@ dict:%@", enumPrefix, enumItem, outValue, enumDict);
return outValue;
}

Here are the example declarations:

typedef enum _type1 {
ExampleNonExplicitTypeNEItemName1, 
ExampleNonExplicitTypeNEItemName2, 
ExampleNonExplicitTypeNEItemName3
} ExampleNonExplicitType;

typedef enum _type2 {
ExampleExplicitAssignsTypeEAItemName1 = 1, 
ExampleExplicitAssignsTypeEAItemName2 = 2, 
ExampleExplicitAssignsTypeEAItemName3 = 4
} ExampleExplicitAssignsType;

Here is an example call:

NSLog(@"EXAMPLE:  type1:%@  type2:%@ ", [self enumItemNameForPrefix:@"ExampleNonExplicitType" item:ExampleNonExplicitTypeNEItemName2], [self enumItemNameForPrefix:@"ExampleExplicitAssignsType" item:ExampleExplicitAssignsTypeEAItemName3]);

Enjoy! ;-)

How can I check if string contains characters & whitespace, not just whitespace?

Instead of checking the entire string to see if there's only whitespace, just check to see if there's at least one character of non whitespace:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

What's the fastest way to read a text file line-by-line?

If the file size is not big, then it is faster to read the entire file and split it afterwards

var filestreams = sr.ReadToEnd().Split(Environment.NewLine, 
                              StringSplitOptions.RemoveEmptyEntries);

Using AJAX to pass variable to PHP and retrieve those using AJAX again

$(document).ready(function() {
    $("#raaagh").click(function() {
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data) {
                console.log(data);
                $.ajax({
                    url:'ajax.php',
                    data: data,
                    dataType:'json',
                    success:function(data1) {
                        var y1=data1;
                        console.log(data1);
                    }
                });
            }
        });
    });
});

Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

EDIT - related to 2.3.0 (2016-12-07)

NOTE: to get solution for previous version, check the history of this post

Similar topic is discussed here Equivalent of $compile in Angular 2. We need to use JitCompiler and NgModule. Read more about NgModule in Angular2 here:

In a Nutshell

There is a working plunker/example (dynamic template, dynamic component type, dynamic module,JitCompiler, ... in action)

The principal is:
1) create Template
2) find ComponentFactory in cache - go to 7)
3) - create Component
4) - create Module
5) - compile Module
6) - return (and cache for later use) ComponentFactory
7) use Target and ComponentFactory to create an Instance of dynamic Component

Here is a code snippet (more of it here) - Our custom Builder is returning just built/cached ComponentFactory and the view Target placeholder consume to create an instance of the DynamicComponent

  // here we get a TEMPLATE with dynamic content === TODO
  var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });

This is it - in nutshell it. To get more details.. read below

.

TL&DR

Observe a plunker and come back to read details in case some snippet requires more explanation

.

Detailed explanation - Angular2 RC6++ & runtime components

Below description of this scenario, we will

  1. create a module PartsModule:NgModule (holder of small pieces)
  2. create another module DynamicModule:NgModule, which will contain our dynamic component (and reference PartsModule dynamically)
  3. create dynamic Template (simple approach)
  4. create new Component type (only if template has changed)
  5. create new RuntimeModule:NgModule. This module will contain the previously created Component type
  6. call JitCompiler.compileModuleAndAllComponentsAsync(runtimeModule) to get ComponentFactory
  7. create an Instance of the DynamicComponent - job of the View Target placeholder and ComponentFactory
  8. assign @Inputs to new instance (switch from INPUT to TEXTAREA editing), consume @Outputs

NgModule

We need an NgModules.

While I would like to show a very simple example, in this case, I would need three modules (in fact 4 - but I do not count the AppModule). Please, take this rather than a simple snippet as a basis for a really solid dynamic component generator.

There will be one module for all small components, e.g. string-editor, text-editor (date-editor, number-editor...)

@NgModule({
  imports:      [ 
      CommonModule,
      FormsModule
  ],
  declarations: [
      DYNAMIC_DIRECTIVES
  ],
  exports: [
      DYNAMIC_DIRECTIVES,
      CommonModule,
      FormsModule
  ]
})
export class PartsModule { }

Where DYNAMIC_DIRECTIVES are extensible and are intended to hold all small parts used for our dynamic Component template/type. Check app/parts/parts.module.ts

The second will be module for our Dynamic stuff handling. It will contain hosting components and some providers.. which will be singletons. Therefor we will publish them standard way - with forRoot()

import { DynamicDetail }          from './detail.view';
import { DynamicTypeBuilder }     from './type.builder';
import { DynamicTemplateBuilder } from './template.builder';

@NgModule({
  imports:      [ PartsModule ],
  declarations: [ DynamicDetail ],
  exports:      [ DynamicDetail],
})

export class DynamicModule {

    static forRoot()
    {
        return {
            ngModule: DynamicModule,
            providers: [ // singletons accross the whole app
              DynamicTemplateBuilder,
              DynamicTypeBuilder
            ], 
        };
    }
}

Check the usage of the forRoot() in the AppModule

Finally, we will need an adhoc, runtime module.. but that will be created later, as a part of DynamicTypeBuilder job.

The forth module, application module, is the one who keeps declares compiler providers:

...
import { COMPILER_PROVIDERS } from '@angular/compiler';    
import { AppComponent }   from './app.component';
import { DynamicModule }    from './dynamic/dynamic.module';

@NgModule({
  imports:      [ 
    BrowserModule,
    DynamicModule.forRoot() // singletons
  ],
  declarations: [ AppComponent],
  providers: [
    COMPILER_PROVIDERS // this is an app singleton declaration
  ],

Read (do read) much more about NgModule there:

A template builder

In our example we will process detail of this kind of entity

entity = { 
    code: "ABC123",
    description: "A description of this Entity" 
};

To create a template, in this plunker we use this simple/naive builder.

The real solution, a real template builder, is the place where your application can do a lot

// plunker - app/dynamic/template.builder.ts
import {Injectable} from "@angular/core";

@Injectable()
export class DynamicTemplateBuilder {

    public prepareTemplate(entity: any, useTextarea: boolean){
      
      let properties = Object.keys(entity);
      let template = "<form >";
      let editorName = useTextarea 
        ? "text-editor"
        : "string-editor";
        
      properties.forEach((propertyName) =>{
        template += `
          <${editorName}
              [propertyName]="'${propertyName}'"
              [entity]="entity"
          ></${editorName}>`;
      });
  
      return template + "</form>";
    }
}

A trick here is - it builds a template which uses some set of known properties, e.g. entity. Such property(-ies) must be part of dynamic component, which we will create next.

To make it a bit more easier, we can use an interface to define properties, which our Template builder can use. This will be implemented by our dynamic Component type.

export interface IHaveDynamicData { 
    public entity: any;
    ...
}

A ComponentFactory builder

Very important thing here is to keep in mind:

our component type, build with our DynamicTypeBuilder, could differ - but only by its template (created above). Components' properties (inputs, outputs or some protected) are still same. If we need different properties, we should define different combination of Template and Type Builder

So, we are touching the core of our solution. The Builder, will 1) create ComponentType 2) create its NgModule 3) compile ComponentFactory 4) cache it for later reuse.

An dependency we need to receive:

// plunker - app/dynamic/type.builder.ts
import { JitCompiler } from '@angular/compiler';
    
@Injectable()
export class DynamicTypeBuilder {

  // wee need Dynamic component builder
  constructor(
    protected compiler: JitCompiler
  ) {}

And here is a snippet how to get a ComponentFactory:

// plunker - app/dynamic/type.builder.ts
// this object is singleton - so we can use this as a cache
private _cacheOfFactories:
     {[templateKey: string]: ComponentFactory<IHaveDynamicData>} = {};
  
public createComponentFactory(template: string)
    : Promise<ComponentFactory<IHaveDynamicData>> {    
    let factory = this._cacheOfFactories[template];

    if (factory) {
        console.log("Module and Type are returned from cache")
       
        return new Promise((resolve) => {
            resolve(factory);
        });
    }
    
    // unknown template ... let's create a Type for it
    let type   = this.createNewComponent(template);
    let module = this.createComponentModule(type);
    
    return new Promise((resolve) => {
        this.compiler
            .compileModuleAndAllComponentsAsync(module)
            .then((moduleWithFactories) =>
            {
                factory = _.find(moduleWithFactories.componentFactories
                                , { componentType: type });

                this._cacheOfFactories[template] = factory;

                resolve(factory);
            });
    });
}

Above we create and cache both Component and Module. Because if the template (in fact the real dynamic part of that all) is the same.. we can reuse

And here are two methods, which represent the really cool way how to create a decorated classes/types in runtime. Not only @Component but also the @NgModule

protected createNewComponent (tmpl:string) {
  @Component({
      selector: 'dynamic-component',
      template: tmpl,
  })
  class CustomDynamicComponent  implements IHaveDynamicData {
      @Input()  public entity: any;
  };
  // a component for this particular template
  return CustomDynamicComponent;
}
protected createComponentModule (componentType: any) {
  @NgModule({
    imports: [
      PartsModule, // there are 'text-editor', 'string-editor'...
    ],
    declarations: [
      componentType
    ],
  })
  class RuntimeComponentModule
  {
  }
  // a module for just this Type
  return RuntimeComponentModule;
}

Important:

our component dynamic types differ, but just by template. So we use that fact to cache them. This is really very important. Angular2 will also cache these.. by the type. And if we would recreate for the same template strings new types... we will start to generate memory leaks.

ComponentFactory used by hosting component

Final piece is a component, which hosts the target for our dynamic component, e.g. <div #dynamicContentPlaceHolder></div>. We get a reference to it and use ComponentFactory to create a component. That is in a nutshell, and here are all the pieces of that component (if needed, open plunker here)

Let's firstly summarize import statements:

import {Component, ComponentRef,ViewChild,ViewContainerRef}   from '@angular/core';
import {AfterViewInit,OnInit,OnDestroy,OnChanges,SimpleChange} from '@angular/core';

import { IHaveDynamicData, DynamicTypeBuilder } from './type.builder';
import { DynamicTemplateBuilder }               from './template.builder';

@Component({
  selector: 'dynamic-detail',
  template: `
<div>
  check/uncheck to use INPUT vs TEXTAREA:
  <input type="checkbox" #val (click)="refreshContent(val.checked)" /><hr />
  <div #dynamicContentPlaceHolder></div>  <hr />
  entity: <pre>{{entity | json}}</pre>
</div>
`,
})
export class DynamicDetail implements AfterViewInit, OnChanges, OnDestroy, OnInit
{ 
    // wee need Dynamic component builder
    constructor(
        protected typeBuilder: DynamicTypeBuilder,
        protected templateBuilder: DynamicTemplateBuilder
    ) {}
    ...

We just receive, template and component builders. Next are properties which are needed for our example (more in comments)

// reference for a <div> with #dynamicContentPlaceHolder
@ViewChild('dynamicContentPlaceHolder', {read: ViewContainerRef}) 
protected dynamicComponentTarget: ViewContainerRef;
// this will be reference to dynamic content - to be able to destroy it
protected componentRef: ComponentRef<IHaveDynamicData>;

// until ngAfterViewInit, we cannot start (firstly) to process dynamic stuff
protected wasViewInitialized = false;

// example entity ... to be recieved from other app parts
// this is kind of candiate for @Input
protected entity = { 
    code: "ABC123",
    description: "A description of this Entity" 
  };

In this simple scenario, our hosting component does not have any @Input. So it does not have to react to changes. But despite of that fact (and to be ready for coming changes) - we need to introduce some flag if the component was already (firstly) initiated. And only then we can start the magic.

Finally we will use our component builder, and its just compiled/cached ComponentFacotry. Our Target placeholder will be asked to instantiate the Component with that factory.

protected refreshContent(useTextarea: boolean = false){
  
  if (this.componentRef) {
      this.componentRef.destroy();
  }
  
  // here we get a TEMPLATE with dynamic content === TODO
  var template = this.templateBuilder.prepareTemplate(this.entity, useTextarea);

  // here we get Factory (just compiled or from cache)
  this.typeBuilder
      .createComponentFactory(template)
      .then((factory: ComponentFactory<IHaveDynamicData>) =>
    {
        // Target will instantiate and inject component (we'll keep reference to it)
        this.componentRef = this
            .dynamicComponentTarget
            .createComponent(factory);

        // let's inject @Inputs to component instance
        let component = this.componentRef.instance;

        component.entity = this.entity;
        //...
    });
}

small extension

Also, we need to keep a reference to compiled template.. to be able properly destroy() it, whenever we will change it.

// this is the best moment where to start to process dynamic stuff
public ngAfterViewInit(): void
{
    this.wasViewInitialized = true;
    this.refreshContent();
}
// wasViewInitialized is an IMPORTANT switch 
// when this component would have its own changing @Input()
// - then we have to wait till view is intialized - first OnChange is too soon
public ngOnChanges(changes: {[key: string]: SimpleChange}): void
{
    if (this.wasViewInitialized) {
        return;
    }
    this.refreshContent();
}

public ngOnDestroy(){
  if (this.componentRef) {
      this.componentRef.destroy();
      this.componentRef = null;
  }
}

done

That is pretty much it. Do not forget to Destroy anything what was built dynamically (ngOnDestroy). Also, be sure to cache dynamic types and modules if the only difference is their template.

Check it all in action here

to see previous versions (e.g. RC5 related) of this post, check the history

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

Visual Studio 2012 Web Publish doesn't copy files

Follow these steps to resolve:

Build > Publish > Profile > New

Create a new profile and configure it with the same settings as your existing profile.

The project will now publish correctly. This often occurs as a result of a source-controlled publish profile from another machine that was created in a newer version of Visual Studio.

PHP Parse error: syntax error, unexpected T_PUBLIC

The public keyword is used only when declaring a class method.

Since you're declaring a simple function and not a class you need to remove public from your code.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Most of the times it should not be used as the primary key for a table because it really hit the performance of the database. useful links regarding GUID impact on performance and as a primary key.

  1. https://www.sqlskills.com/blogs/kimberly/disk-space-is-cheap/
  2. https://www.sqlskills.com/blogs/kimberly/guids-as-primary-keys-andor-the-clustering-key/

How do I change the database name using MySQL?

Follow bellow steps:

shell> mysqldump -hlocalhost -uroot -p  database1  > dump.sql

mysql> CREATE DATABASE database2;

shell> mysql -hlocalhost -uroot -p database2 < dump.sql

If you want to drop database1 otherwise leave it.

mysql> DROP DATABASE database1;

Note : shell> denote command prompt and mysql> denote mysql prompt.

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 to create a floating action button (FAB) in android, using AppCompat v21?

Try this library, it supports shadow, there is minSdkVersion=7 and also supports android:elevation attribute for API-21 implicitly.

Original post is here.

How to display count of notifications in app launcher icon

Android ("vanilla" android without custom launchers and touch interfaces) does not allow changing of the application icon, because it is sealed in the .apk tightly once the program is compiled. There is no way to change it to a 'drawable' programmatically using standard APIs. You may achieve your goal by using a widget instead of an icon. Widgets are customisable. Please read this :http://www.cnet.com/8301-19736_1-10278814-251.html and this http://developer.android.com/guide/topics/appwidgets/index.html. Also look here: https://github.com/jgilfelt/android-viewbadger. It can help you.

As for badge numbers. As I said before - there is no standard way for doing this. But we all know that Android is an open operating system and we can do everything we want with it, so the only way to add a badge number - is either to use some 3-rd party apps or custom launchers, or front-end touch interfaces: Samsung TouchWiz or Sony Xperia's interface. Other answers use this capabilities and you can search for this on stackoverflow, e.g. here. But I will repeat one more time: there is no standard API for this and I want to say it is a bad practice. App's icon notification badge is an iOS pattern and it should not be used in Android apps anyway. In Andrioid there is a status bar notifications for these purposes:http://developer.android.com/guide/topics/ui/notifiers/notifications.html So, if Facebook or someone other use this - it is not a common pattern or trend we should consider. But if you insist anyway and don't want to use home screen widgets then look here, please:

How does Facebook add badge numbers on app icon in Android?

As you see this is not an actual Facebook app it's TouchWiz. In vanilla android this can be achieved with Nova Launcher http://forums.androidcentral.com/android-applications/199709-how-guide-global-badge-notifications.html So if you will see icon badges somewhere, be sure it is either a 3-rd party launcher or touch interface (frontend wrapper). May be sometime Google will add this capability to the standard Android API.

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

CSS rule to apply only if element has BOTH classes

div.abc.xyz {
    /* rules go here */
}

... or simply:

.abc.xyz {
    /* rules go here */
}

Appending a vector to a vector

While saying "the compiler can reserve", why rely on it? And what about automatic detection of move semantics? And what about all that repeating of the container name with the begins and ends?

Wouldn't you want something, you know, simpler?

(Scroll down to main for the punchline)

#include <type_traits>
#include <vector>
#include <iterator>
#include <iostream>

template<typename C,typename=void> struct can_reserve: std::false_type {};

template<typename T, typename A>
struct can_reserve<std::vector<T,A>,void>:
    std::true_type
{};

template<int n> struct secret_enum { enum class type {}; };
template<int n>
using SecretEnum = typename secret_enum<n>::type;

template<bool b, int override_num=1>
using EnableFuncIf = typename std::enable_if< b, SecretEnum<override_num> >::type;
template<bool b, int override_num=1>
using DisableFuncIf = EnableFuncIf< !b, -override_num >;

template<typename C, EnableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t n ) {
  c.reserve(n);
}
template<typename C, DisableFuncIf< can_reserve<C>::value >... >
void try_reserve( C& c, std::size_t ) { } // do nothing

template<typename C,typename=void>
struct has_size_method:std::false_type {};
template<typename C>
struct has_size_method<C, typename std::enable_if<std::is_same<
  decltype( std::declval<C>().size() ),
  decltype( std::declval<C>().size() )
>::value>::type>:std::true_type {};

namespace adl_aux {
  using std::begin; using std::end;
  template<typename C>
  auto adl_begin(C&&c)->decltype( begin(std::forward<C>(c)) );
  template<typename C>
  auto adl_end(C&&c)->decltype( end(std::forward<C>(c)) );
}
template<typename C>
struct iterable_traits {
    typedef decltype( adl_aux::adl_begin(std::declval<C&>()) ) iterator;
    typedef decltype( adl_aux::adl_begin(std::declval<C const&>()) ) const_iterator;
};
template<typename C> using Iterator = typename iterable_traits<C>::iterator;
template<typename C> using ConstIterator = typename iterable_traits<C>::const_iterator;
template<typename I> using IteratorCategory = typename std::iterator_traits<I>::iterator_category;

template<typename C, EnableFuncIf< has_size_method<C>::value, 1>... >
std::size_t size_at_least( C&& c ) {
    return c.size();
}

template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 2>... >
std::size_t size_at_least( C&& c ) {
    using std::begin; using std::end;
  return end(c)-begin(c);
};
template<typename C, EnableFuncIf< !has_size_method<C>::value &&
  !std::is_base_of< std::random_access_iterator_tag, IteratorCategory<Iterator<C>> >::value, 3>... >
std::size_t size_at_least( C&& c ) {
  return 0;
};

template < typename It >
auto try_make_move_iterator(It i, std::true_type)
-> decltype(make_move_iterator(i))
{
    return make_move_iterator(i);
}
template < typename It >
It try_make_move_iterator(It i, ...)
{
    return i;
}


#include <iostream>
template<typename C1, typename C2>
C1&& append_containers( C1&& c1, C2&& c2 )
{
  using std::begin; using std::end;
  try_reserve( c1, size_at_least(c1) + size_at_least(c2) );

  using is_rvref = std::is_rvalue_reference<C2&&>;
  c1.insert( end(c1),
             try_make_move_iterator(begin(c2), is_rvref{}),
             try_make_move_iterator(end(c2), is_rvref{}) );

  return std::forward<C1>(c1);
}

struct append_infix_op {} append;
template<typename LHS>
struct append_on_right_op {
  LHS lhs;
  template<typename RHS>
  LHS&& operator=( RHS&& rhs ) {
    return append_containers( std::forward<LHS>(lhs), std::forward<RHS>(rhs) );
  }
};

template<typename LHS>
append_on_right_op<LHS> operator+( LHS&& lhs, append_infix_op ) {
  return { std::forward<LHS>(lhs) };
}
template<typename LHS,typename RHS>
typename std::remove_reference<LHS>::type operator+( append_on_right_op<LHS>&& lhs, RHS&& rhs ) {
  typename std::decay<LHS>::type retval = std::forward<LHS>(lhs.lhs);
  return append_containers( std::move(retval), std::forward<RHS>(rhs) );
}

template<typename C>
void print_container( C&& c ) {
  for( auto&& x:c )
    std::cout << x << ",";
  std::cout << "\n";
};

int main() {
  std::vector<int> a = {0,1,2};
  std::vector<int> b = {3,4,5};
  print_container(a);
  print_container(b);
  a +append= b;
  const int arr[] = {6,7,8};
  a +append= arr;
  print_container(a);
  print_container(b);
  std::vector<double> d = ( std::vector<double>{-3.14, -2, -1} +append= a );
  print_container(d);
  std::vector<double> c = std::move(d) +append+ a;
  print_container(c);
  print_container(d);
  std::vector<double> e = c +append+ std::move(a);
  print_container(e);
  print_container(a);
}

hehe.

Now with move-data-from-rhs, append-array-to-container, append forward_list-to-container, move-container-from-lhs, thanks to @DyP's help.

Note that the above does not compile in clang thanks to the EnableFunctionIf<>... technique. In clang this workaround works.

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

Capturing a form submit with jquery and .submit

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  var form = $('#login_form')[0];_x000D_
  form.onsubmit = function(e){_x000D_
  var data = $("#login_form :input").serializeArray();_x000D_
  console.log(data);_x000D_
  $.ajax({_x000D_
  url: "the url to post",_x000D_
  data: data,_x000D_
  processData: false,_x000D_
  contentType: false,_x000D_
  type: 'POST',_x000D_
  success: function(data){_x000D_
    alert(data);_x000D_
  },_x000D_
  error: function(xhrRequest, status, error) {_x000D_
    alert(JSON.stringify(xhrRequest));_x000D_
  }_x000D_
});_x000D_
    return false;_x000D_
  }_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="POST" id="login_form">_x000D_
    <label>Username:</label>_x000D_
    <input type="text" name="username" id="username"/>_x000D_
    <label>Password:</label>_x000D_
    <input type="password" name="password" id="password"/>_x000D_
    <input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

jQuery datepicker, onSelect won't work

The function datepicker is case sensitive and all lowercase. The following however works fine for me:

$(document).ready(function() {
  $('.date-pick').datepicker( {
    onSelect: function(date) {
        alert(date);
    },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1
  });
});

How can I add C++11 support to Code::Blocks compiler?

The answer with screenshots (put the checkbox as in the second pic, then press OK):

enter image description here enter image description here

Getting files by creation date in .NET

this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}

How to call a C# function from JavaScript?

Server-side functions are on the server-side, client-side functions reside on the client. What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load handler you can access value of variable and call the server method.

More info can be found here and here

Oracle: SQL query to find all the triggers belonging to the tables?

Use the Oracle documentation and search for keyword "trigger" in your browser.

This approach should work with other metadata type questions.

while EOF in JAVA?

To read a file Scanner class is recommended.

    Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
    try {
      while (scanner.hasNextLine()){
         System.out.println(scanner.nextLine());
      }
    }
    finally{
      scanner.close();
    }

Reading Datetime value From Excel sheet

i had a similar situation and i used the below code for getting this worked..

Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);

Workbook workbook = new Workbook(fstream, loadOptions);

Worksheet worksheet = workbook.Worksheets[0];

dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);

DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();

foreach (DataColumn column in dtCloned.Columns)
{
    if (column.DataType == Type.GetType("System.DateTime"))
    {
        column.DataType = typeof(String);
        myAL.Add(column.ColumnName);
    }
}


foreach (DataRow row in dt.Rows)
{
    dtCloned.ImportRow(row);
}



foreach (string colName in myAL)
{
    dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}


/*******************************/

public static class MyExtension
{
    public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
    {
        foreach (DataRow row in column.Table.Rows)
        {
            row[column] = conversion(row[column]);
        }
    }
}

Hope this helps some1 thx_joxin

Printing a char with printf

%d prints an integer: it will print the ascii representation of your character. What you need is %c:

printf("%c", ch);

printf("%d", '\0'); prints the ascii representation of '\0', which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.

printf("%d", sizeof('\n')); prints 4 because a character literal is an int, in C, and not a char.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

How to get the error message from the error code returned by GetLastError()?

GetLastError returns a numerical error code. To obtain a descriptive error message (e.g., to display to a user), you can call FormatMessage:

// This functions fills a caller-defined character buffer (pBuffer)
// of max length (cchBufferLength) with the human-readable error message
// for a Win32 error code (dwErrorCode).
// 
// Returns TRUE if successful, or FALSE otherwise.
// If successful, pBuffer is guaranteed to be NUL-terminated.
// On failure, the contents of pBuffer are undefined.
BOOL GetErrorMessage(DWORD dwErrorCode, LPTSTR pBuffer, DWORD cchBufferLength)
{
    if (cchBufferLength == 0)
    {
        return FALSE;
    }

    DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL,  /* (not used with FORMAT_MESSAGE_FROM_SYSTEM) */
                                 dwErrorCode,
                                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                 pBuffer,
                                 cchBufferLength,
                                 NULL);
    return (cchMsg > 0);
}

In C++, you can simplify the interface considerably by using the std::string class:

#include <Windows.h>
#include <system_error>
#include <memory>
#include <string>
typedef std::basic_string<TCHAR> String;

String GetErrorMessage(DWORD dwErrorCode)
{
    LPTSTR psz{ nullptr };
    const DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
                                         | FORMAT_MESSAGE_IGNORE_INSERTS
                                         | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                                       NULL, // (not used with FORMAT_MESSAGE_FROM_SYSTEM)
                                       dwErrorCode,
                                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                       reinterpret_cast<LPTSTR>(&psz),
                                       0,
                                       NULL);
    if (cchMsg > 0)
    {
        // Assign buffer to smart pointer with custom deleter so that memory gets released
        // in case String's c'tor throws an exception.
        auto deleter = [](void* p) { ::LocalFree(p); };
        std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer(psz, deleter);
        return String(ptrBuffer.get(), cchMsg);
    }
    else
    {
        auto error_code{ ::GetLastError() };
        throw std::system_error( error_code, std::system_category(),
                                 "Failed to retrieve error message string.");
    }
}

NOTE: These functions also work for HRESULT values. Just change the first parameter from DWORD dwErrorCode to HRESULT hResult. The rest of the code can remain unchanged.


These implementations provide the following improvements over the existing answers:

  • Complete sample code, not just a reference to the API to call.
  • Provides both C and C++ implementations.
  • Works for both Unicode and MBCS project settings.
  • Takes the error code as an input parameter. This is important, as a thread's last error code is only valid at well defined points. An input parameter allows the caller to follow the documented contract.
  • Implements proper exception safety. Unlike all of the other solutions that implicitly use exceptions, this implementation will not leak memory in case an exception is thrown while constructing the return value.
  • Proper use of the FORMAT_MESSAGE_IGNORE_INSERTS flag. See The importance of the FORMAT_MESSAGE_IGNORE_INSERTS flag for more information.
  • Proper error handling/error reporting, unlike some of the other answers, that silently ignore errors.


This answer has been incorporated from Stack Overflow Documentation. The following users have contributed to the example: stackptr, Ajay, Cody Gray?, IInspectable.

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

How to show google.com in an iframe?

The reason for this is, that Google is sending an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page.

See: Mozilla Developer Network - The X-Frame-Options response header

How to generate classes from wsdl using Maven and wsimport?

I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure

the version management system (svn/etc.) would always notice changed sources

With git it is not true. So you can just configure jaxws-maven-plugin to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxws-maven-plugin</artifactId>
        <version>2.6</version>

    <dependencies>
      <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-fluent-api</artifactId>
        <version>3.0</version>
      </dependency>
      <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-tools</artifactId>
        <version>2.3.0</version>
      </dependency>
    </dependencies>

    <executions>
      <execution>
        <goals>
          <goal>wsimport</goal>
        </goals>
        <configuration>
          <packageName>som.path.generated</packageName>
          <xjcArgs>
            <xjcArg>-Xfluent-api</xjcArg>
          </xjcArgs>
          <verbose>true</verbose>
          <keep>true</keep> <!--used by default-->
          <sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
          <wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
          <wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
        </configuration>
      </execution>
    </executions>
  </plugin>

Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:

A a = new A()
  .withField1(value1)
  .withField2(value2);

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

How to generate random positive and negative numbers in Java

This is an old question I know but um....

n=n-(n*2)

Gradle version 2.2 is required. Current version is 2.10

Use ./gradlew instead of gradle to resolve this issue.

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

Accessing elements of Python dictionary by index

You can't rely on order of dictionaries, but you may try this:

mydict['Apple'].items()[0][0]

If you want the order to be preserved you may want to use this: http://www.python.org/dev/peps/pep-0372/#ordered-dict-api

Why is using a wild card with a Java import statement bad?

The most important one is that importing java.awt.* can make your program incompatible with a future Java version:

Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.

You won't have that problem when you import only those classes explicitly from java.awt that you actually use.

Resources:

Java Imports

Abort Ajax requests using jQuery

I had the problem of polling and once the page was closed the poll continued so in my cause a user would miss an update as a mysql value was being set for the next 50 seconds after page closing, even though I killed the ajax request, I figured away around, using $_SESSION to set a var won't update in the poll its self until its ended and a new one has started, so what I did was set a value in my database as 0 = offpage , while I'm polling I query that row and return false; when it's 0 as querying in polling will get you current values obviously...

I hope this helped

How to fix 'android.os.NetworkOnMainThreadException'?

How to fix android.os.NetworkOnMainThreadException

What is NetworkOnMainThreadException:

In Android all the UI operations we have to do on the UI thread (main thread). If we perform background operations or some network operation on the main thread then we risk this exception will occur and the app will not respond.

How to fix it:

To avoid this problem, you have to use another thread for background operations or network operations, like using asyncTask and use some library for network operations like Volley, AsyncHttp, etc.

Get TimeZone offset value from TimeZone without TimeZone name

I know this is old, but I figured I'd give my input. I had to do this for a project at work and this was my solution.

I have a Building object that includes the Timezone using the TimeZone class and wanted to create zoneId and offset fields in a new class.

So what I did was create:

private String timeZoneId;
private String timeZoneOffset;

Then in the constructor I passed in the Building object and set these fields like so:

this.timeZoneId = building.getTimeZone().getID();
this.timeZoneOffset = building.getTimeZone().toZoneId().getId();

So timeZoneId might equal something like "EST" And timeZoneOffset might equal something like "-05:00"

I would like to not that you might not

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

I had this problem when I delegated my compilation task to the Google Compute Engine via SSH. The nature of this issue is a memory error, as indicated by the crash log; specifically it is thrown when Java runs out of virtual memory to work with during the build.

Important: When gradle crashes due to this memory error, the gradle daemons remain running long after your compilation task has failed. Any re-attempt to build using gradle again will allocate a new gradle daemon. You must ensure that you properly dispose of any crashed instances using gradlew --stop.

The hs_error_pid crash logs indicates the following workarounds:

# There is insufficient memory for the Java Runtime Environment to continue.
# Possible reasons:
#   The system is out of physical RAM or swap space
#   In 32 bit mode, the process size limit was hit
# Possible solutions:
#   Reduce memory load on the system
#   Increase physical memory or swap space
#   Check if swap backing store is full
#   Use 64 bit Java on a 64 bit OS
#   Decrease Java heap size (-Xmx/-Xms)
#   Decrease number of Java threads
#   Decrease Java thread stack sizes (-Xss)
#   Set larger code cache with -XX:ReservedCodeCacheSize=

I found that after increasing the runtime resources of the virtual machine, this issue was resolved.

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

Detecting installed programs via registry

On 64-bit systems the x64 key is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

Most programs are listed there. Look at the keys: DisplayName DisplayVersion

Note that the last is not always set!

On 64-bit systems the x86 key (usually with more entries) is:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

How do I add space between items in an ASP.NET RadioButtonList

Even easier...

ASP.NET

<asp:RadioButtonList runat="server" ID="MyRadioButtonList" RepeatDirection="Horizontal" CssClass="FormatRadioButtonList"> ...

CSS

.FormatRadioButtonList label
{
  margin-right: 15px;
}

Request UAC elevation from within a Python script?

It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)

Putting an if-elif-else statement on one line?

The ternary operator is the best way to a concise expression. The syntax is variable = value_1 if condition else value_2. So, for your example, you must apply the ternary operator twice:

i = 23 # set any value for i
x = 2 if i > 100 else 1 if i < 100 else 0

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

You don't have to do it this complicated way. If you are using XCode 5 (which I am sure most of us are) then create your icons call them whatever you like i.e.

  • myIcon-58.png
  • myIcon-57.png
  • myIcon-72.png
  • myIcon-80.png
  • myIcon-100.png ....

And drag and drop them on to the correct boxes under AppIcon. See screenshots. You don't have to manually edit plist file.

enter image description here enter image description here enter image description here

How to insert a file in MySQL database?

The other answers will give you a good idea how to accomplish what you have asked for....

However

There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.

That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ImportError: cannot import name NUMPY_MKL

Reinstall numpy-1.11.0_XXX.whl (for your Python) from www.lfd.uci.edu/~gohlke/pythonlibs. This file has the same name and version if compare with the variant downloaded by me earlier 29.03.2016, but its size and content differ from old variant. After re-installation error disappeared.

Second option - return back to scipy 0.17.0 from 0.17.1

P.S. I use Windows 64-bit version of Python 3.5.1, so can't guarantee that numpy for Python 2.7 is already corrected.

add new row in gridview after binding C#, ASP.net

you can try the following code

protected void Button1_Click(object sender, EventArgs e)
   {
       DataTable dt = new DataTable();

       if (dt.Columns.Count == 0)
       {
           dt.Columns.Add("PayScale", typeof(string));
           dt.Columns.Add("IncrementAmt", typeof(string));
           dt.Columns.Add("Period", typeof(string));
       }

       DataRow NewRow = dt.NewRow();
       NewRow[0] = TextBox1.Text;
       NewRow[1] = TextBox2.Text;
       dt.Rows.Add(NewRow); 
       GridView1.DataSource = dt;
       GridViewl.DataBind();
   }

here payscale,incrementamt and period are database field name.

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

Swift 3

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let editAction = UITableViewRowAction(style: .normal, title: "Edit") { (rowAction, indexPath) in
        //TODO: edit the row at indexPath here
    }
    editAction.backgroundColor = .blue

    let deleteAction = UITableViewRowAction(style: .normal, title: "Delete") { (rowAction, indexPath) in
        //TODO: Delete the row at indexPath here
    }
    deleteAction.backgroundColor = .red

    return [editAction,deleteAction]
}

Swift 2.1

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    let editAction = UITableViewRowAction(style: .Normal, title: "Edit") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
        //TODO: edit the row at indexPath here
    }
    editAction.backgroundColor = UIColor.blueColor()

    let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
        //TODO: Delete the row at indexPath here
    }
    deleteAction.backgroundColor = UIColor.redColor()

    return [editAction,deleteAction]
}

Note: for iOS 8 onwards

How to set up Android emulator proxy settings

In case if you are under proxy environment and internet is not running in your emulator, then please don't change any setting in emulator. Go to your eclipse project, right click , click on "Run as" then click on "Run Configuration". In pop up window choose "Target" and scroll down a little, you will find "Additional Emulator Command Line Options" Enter your proxy setting here in "Additional Emulator Command Line Options" as i entered

-http-proxy http://ee11s040:[email protected]:3128

enter image description here

Then start a new Emulator.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Another awk variant:

#!/usr/bin/awk -f
# usage:
# awk -f randomize_lines.awk lines.txt
# usage after "chmod +x randomize_lines.awk":
# randomize_lines.awk lines.txt

BEGIN {
  FS = "\n";
  srand();
}

{
  lines[ rand()] = $0;
}

END {
  for( k in lines ){
    print lines[k];
  }
}

How to define constants in Visual C# like #define in C?

Check How to: Define Constants in C# on MSDN:

In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.

How to send HTML-formatted email?

This works for me

msg.BodyFormat = MailFormat.Html;

and then you can use html in your body

msg.Body = "<em>It's great to use HTML in mail!!</em>"

Using the HTML5 "required" attribute for a group of checkboxes?

we can do this easily with html5 also, just need to add some jquery code

Demo

HTML

<form>
 <div class="form-group options">
   <input type="checkbox" name="type[]" value="A" required /> A
   <input type="checkbox" name="type[]" value="B" required /> B
   <input type="checkbox" name="type[]" value="C" required /> C
   <input type="submit">
 </div>
</form>

Jquery

$(function(){
    var requiredCheckboxes = $('.options :checkbox[required]');
    requiredCheckboxes.change(function(){
        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        } else {
            requiredCheckboxes.attr('required', 'required');
        }
    });
});

How to Deep clone in javascript

There should be no real world need for such a function anymore. This is mere academic interest.

As purely an exercise, this is a more functional way of doing it. It's an extension of @tfmontague's answer as I'd suggested adding a guard block there. But seeing as I feel compelled to ES6 and functionalise all the things, here's my pimped version. It complicates the logic as you have to map over the array and reduce over the object, but it avoids any mutations.

_x000D_
_x000D_
const cloner = (x) => {
    const recurseObj = x => (typeof x === 'object') ? cloner(x) : x
    const cloneObj = (y, k) => {
        y[k] = recurseObj(x[k])
        return y
    }
    // Guard blocks
    // Add extra for Date / RegExp if you want
    if (!x) {
        return x
    }
    if (Array.isArray(x)) {
        return x.map(recurseObj)
    }
    return Object.keys(x).reduce(cloneObj, {})
}
const tests = [
    null,
    [],
    {},
    [1,2,3],
    [1,2,3, null],
    [1,2,3, null, {}],
    [new Date('2001-01-01')], // FAIL doesn't work with Date
    {x:'', y: {yx: 'zz', yy: null}, z: [1,2,3,null]},
    {
        obj : new function() {
            this.name = "Object test";
        }
    } // FAIL doesn't handle functions
]
tests.map((x,i) => console.log(i, cloner(x)))
_x000D_
_x000D_
_x000D_

How should a model be structured in MVC?

Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.

You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.

It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):

class Database {
   protected $_conn;

   public function __construct($connection) {
       $this->_conn = $connection;
   }

   public function ExecuteObject($sql, $data) {
       // stuff
   }
}

abstract class Model {
   protected $_db;

   public function __construct(Database $db) {
       $this->_db = $db;
   }
}

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');

Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.

How to Convert datetime value to yyyymmddhhmmss in SQL server?

Another option I have googled, but contains several replace ...

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

Any way to exit bash script, but not quitting the terminal

It's correct that sourced vs. executed scripts use return vs. exit to keep the same session open, as others have noted.

Here's a related tip, if you ever want a script that should keep the session open, regardless of whether or not it's sourced.

The following example can be run directly like foo.sh or sourced like . foo.sh/source foo.sh. Either way it will keep the session open after "exiting". The $@ string is passed so that the function has access to the outer script's arguments.

#!/bin/sh
foo(){
    read -p "Would you like to XYZ? (Y/N): " response;
    [ $response != 'y' ] && return 1;
    echo "XYZ complete (args $@).";
    return 0;
    echo "This line will never execute.";
}
foo "$@";

Terminal result:

$ foo.sh
$ Would you like to XYZ? (Y/N): n
$ . foo.sh
$ Would you like to XYZ? (Y/N): n
$ |
(terminal window stays open and accepts additional input)

This can be useful for quickly testing script changes in a single terminal while keeping a bunch of scrap code underneath the main exit/return while you work. It could also make code more portable in a sense (if you have tons of scripts that may or may not be called in different ways), though it's much less clunky to just use return and exit where appropriate.

How to create an installer for a .net Windows Service using Visual Studio

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.

Here is my brief steps how to create service with installer:

  1. Run Visual Studio, Go to File->New->Project
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service'
  3. Select 'Windows Service'. Type Name and Location. Press OK.
  4. Double click Service1.cs, right click in designer and select 'Add Installer'
  5. Double click ProjectInstaller.cs. For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'.
  6. Double click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall event. Write code:

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (System.ServiceProcess.ServiceController sc = new 
        System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
    
  7. Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.

  8. Create install.bat with below script:

    :::::::::::::::::::::::::::::::::::::::::
    :: Automatically check & get admin rights
    :::::::::::::::::::::::::::::::::::::::::
    @echo off
    CLS 
    ECHO.
    ECHO =============================
    ECHO Running Admin shell
    ECHO =============================
    
    :checkPrivileges 
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) 
    
    :getPrivileges 
    if '%1'=='ELEV' (shift & goto gotPrivileges)  
    ECHO. 
    ECHO **************************************
    ECHO Invoking UAC for Privilege Escalation 
    ECHO **************************************
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs" 
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" 
    "%temp%\OEgetPrivileges.vbs" 
    exit /B 
    
    :gotPrivileges 
    ::::::::::::::::::::::::::::
    :START
    ::::::::::::::::::::::::::::
    setlocal & pushd .
    
    cd /d %~dp0
    %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
    pause
    
  9. Create uninstall.bat file (change in pen-ult line /i to /u)
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat

Tomcat manager/html is not available?

I had the situatuion when tomcat manager did not start. I had this exception in my logs/manager.DDD-MM-YY.log:

org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter CSRF
java.lang.ClassNotFoundException: org.apache.catalina.filters.CsrfPreventionFilter
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        ...

This exception was raised because I used a version of tomcat that hadn't CSRF prevention filter. Tomcat 6.0.24 doesn't have the CSRF prevention filter in it. The first version that has it is the 6.0.30 version (at least. according to the changelog). As a result, Tomcat Manager was uncompatible with version of Tomcat that I used. I've digged description of this issue here: http://blog.techstacks.com/.m/2009/05/tomcat-management-setting-up-tomcat/comments/

Steps to fix it:

  1. Check version of tomcat installed by running "sh version.sh" from your tomcat/bin directory
  2. Download corresponding version of tomcat
  3. Stop tomcat
  4. Remove your webapps/manager directory and copy manager application from distributive that you've downloaded.
  5. Start tomcat

Now you should be able to access tomcat manager.

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

Example of SOAP request authenticated with WS-UsernameToken

May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "

JavaScript OOP in NodeJS: how?

As Node.js community ensure new features from the JavaScript ECMA-262 specification are brought to Node.js developers in a timely manner.

You can take a look at JavaScript classes. MDN link to JS classes In the ECMAScript 6 JavaScript classes are introduced, this method provide easier way to model OOP concepts in Javascript.

Note : JS classes will work in only strict mode.

Below is some skeleton of class,inheritance written in Node.js ( Used Node.js Version v5.0.0 )

Class declarations :

'use strict'; 
class Animal{

 constructor(name){
    this.name = name ;
 }

 print(){
    console.log('Name is :'+ this.name);
 }
}

var a1 = new Animal('Dog');

Inheritance :

'use strict';
class Base{

 constructor(){
 }
 // methods definitions go here
}

class Child extends Base{
 // methods definitions go here
 print(){ 
 }
}

var childObj = new Child();

Simple WPF RadioButton Binding?

Actually, using the converter like that breaks two-way binding, plus as I said above, you can't use that with enumerations either. The better way to do this is with a simple style against a ListBox, like this:

Note: Contrary to what DrWPF.com stated in their example, do not put the ContentPresenter inside the RadioButton or else if you add an item with content such as a button or something else, you will not be able to set focus or interact with it. This technique solves that. Also, you need to handle the graying of the text as well as removing of margins on labels or else it will not render correctly. This style handles both for you as well.

<Style x:Key="RadioButtonListItem" TargetType="{x:Type ListBoxItem}" >

    <Setter Property="Template">
        <Setter.Value>

            <ControlTemplate TargetType="ListBoxItem">

                <DockPanel LastChildFill="True" Background="{TemplateBinding Background}" HorizontalAlignment="Stretch" VerticalAlignment="Center" >

                    <RadioButton IsChecked="{TemplateBinding IsSelected}" Focusable="False" IsHitTestVisible="False" VerticalAlignment="Center" Margin="0,0,4,0" />

                    <ContentPresenter
                        Content             = "{TemplateBinding ContentControl.Content}"
                        ContentTemplate     = "{TemplateBinding ContentControl.ContentTemplate}"
                        ContentStringFormat = "{TemplateBinding ContentControl.ContentStringFormat}"
                        HorizontalAlignment = "{TemplateBinding Control.HorizontalContentAlignment}"
                        VerticalAlignment   = "{TemplateBinding Control.VerticalContentAlignment}"
                        SnapsToDevicePixels = "{TemplateBinding UIElement.SnapsToDevicePixels}" />

                </DockPanel>

            </ControlTemplate>

        </Setter.Value>

    </Setter>

</Style>

<Style x:Key="RadioButtonList" TargetType="ListBox">

    <Style.Resources>
        <Style TargetType="Label">
            <Setter Property="Padding" Value="0" />
        </Style>
    </Style.Resources>

    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Background"      Value="Transparent" />

    <Setter Property="ItemContainerStyle" Value="{StaticResource RadioButtonListItem}" />

    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="TextBlock.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
        </Trigger>
    </Style.Triggers>

</Style>

<Style x:Key="HorizontalRadioButtonList" BasedOn="{StaticResource RadioButtonList}" TargetType="ListBox">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel Background="Transparent" Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

You now have the look and feel of radio buttons, but you can do two-way binding, and you can use an enumeration. Here's how...

<ListBox Style="{StaticResource RadioButtonList}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Yet another option</ListBoxItem>

</ListBox>

Also, since we explicitly separated out the style that tragets the ListBoxItem rather than putting it inline, again as the other examples have shown, you can now create a new style off of it to customize things on a per-item basis such as spacing. (This will not work if you simply try to target ListBoxItem as the keyed style overrides generic control targets.)

Here's an example of putting a margin of 6 above and below each item. (Note how you have to explicitly apply the style via the ItemContainerStyle property and not simply targeting ListBoxItem in the ListBox's resource section for the reason stated above.)

<Window.Resources>
    <Style x:Key="SpacedRadioButtonListItem" TargetType="ListBoxItem" BasedOn="{StaticResource RadioButtonListItem}">
        <Setter Property="Margin" Value="0,6" />
    </Style>
</Window.Resources>

<ListBox Style="{StaticResource RadioButtonList}"
    ItemContainerStyle="{StaticResource SpacedRadioButtonListItem}"
    SelectedValue="{Binding SomeVal}"
    SelectedValuePath="Tag">

    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOption}"     >Some option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.SomeOtherOption}">Some other option</ListBoxItem>
    <ListBoxItem Tag="{x:Static l:MyEnum.YetAnother}"     >Ter another option</ListBoxItem>

</ListBox>

How do I show the schema of a table in a MySQL database?

SHOW CREATE TABLE yourTable;

or

SHOW COLUMNS FROM yourTable;

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

Rotating and spacing axis labels in ggplot2

Change the last line to

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:

alt text

The image above is from this blog post.

Session 'app': Error Installing APK

In my case with Android 8.0(Oreo), no one of this solutions worked! If you have more than 1 user, then you should go to Settings->Applications->All Applications->Find the application and uninstall for all users! After this steps, it worked!

How can I run multiple curl requests processed sequentially?

Another crucial method not mentioned here is using the same TCP connection for multiple HTTP requests, and exactly one curl command for this.

This is very useful to save network bandwidth, client and server resources, and overall the need of using multiple curl commands, as curl by default closes the connection when end of command is reached.

Keeping the connection open and reusing it is very common for standard clients running a web-app.

Starting curl version 7.36.0, the --next or -: command-line option allows to chain multiple requests, and usable both in command-line and scripting.

For example:

  • Sending multiple requests on the same TCP connection:

curl http://example.com/?update_=1 -: http://example.com/foo

  • Sending multiple different HTTP requests on the same connection:

curl http://example.com/?update_=1 -: -d "I am posting this string" http://example.com/?update_=2

  • Sending multiple HTTP requests with different curl options for each request:

curl -o 'my_output_file' http://example.com/?update_=1 -: -d "my_data" -s -m 10 http://example.com/foo -: -o /dev/null http://example.com/random

From the curl manpage:

-:, --next

Tells curl to use a separate operation for the following URL and associated options. This allows you to send several URL requests, each with their own specific options, for example, such as different user names or custom requests for each.

-:, --next will reset all local options and only global ones will have their values survive over to the operation following the -:, --next instruction. Global options include -v, --verbose, --trace, --trace-ascii and --fail-early.

For example, you can do both a GET and a POST in a single command line:

curl www1.example.com --next -d postthis www2.example.com

Added in 7.36.0.

Differences between C++ string == and compare()?

compare() is equivalent to strcmp(). == is simple equality checking. compare() therefore returns an int, == is a boolean.

How do I get which JRadioButton is selected from a ButtonGroup

jRadioOne = new javax.swing.JRadioButton();
jRadioTwo = new javax.swing.JRadioButton();
jRadioThree = new javax.swing.JRadioButton();

... then for every button:

buttonGroup1.add(jRadioOne);
jRadioOne.setText("One");
jRadioOne.setActionCommand(ONE);
jRadioOne.addActionListener(radioButtonActionListener);

...listener

ActionListener radioButtonActionListener = new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioButtonActionPerformed(evt);
            }
        };

...do whatever you need as response to event

protected void radioButtonActionPerformed(ActionEvent evt) {            
       System.out.println(evt.getActionCommand());
    }

pgadmin4 : postgresql application server could not be contacted.

We got the same issue. so no any change in the file. but start pgAdmin 4 using administrator.

The following step. 1. right click pgAdmin 4 icon 2. select "Run As Administrator"

How can I set the default value for an HTML <select> element?

This is how I did it...

<form action="../<SamePage>/" method="post">

<?php
    if ( $_POST['drop_down'] == "")
    {
    $selected = "";
    }
    else
    {
    $selected = "selected";
    }
?>

<select name="select" size="1">

  <option value="1" <?php $selected ?>>One</option>
     ////////  OR  ////////
  <option value="2" $selected>Two</option>

</select>
</form>

Read/write to file using jQuery

both HTML5 and Google Gears add local storage capabilities, mainly by an embedded SQLite API.

How to use source: function()... and AJAX in JQuery UI autocomplete

Set the auto complete:

$("#searchBox").autocomplete({
    source: queryDB
});

The source function that gets the data:

function queryDB(request, response) {
    var query = request.term;
    var data = getDataFromDB(query);
    response(data); //puts the results on the UI
}

How to call a shell script from python code?

I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.

The new way to execute external scripts is with the run function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.

import subprocess

subprocess.run(['./test.sh'])

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

global variable for all controller and views

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return Setting::all();
    });

    // If you use this line of code then it'll be available in any view
    // as $site_settings but you may also use app('site_settings') as well
    View::share('site_settings', app('site_settings'));
});

To get the same data in any controller you may use:

$site_settings = app('site_settings');

There are many ways, just use one or another, which one you prefer but I'm using the Container.

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

How can I clear the input text after clicking

To remove the default text, on clicking the element:

$('input:text').click(
    function(){
        $(this).val('');
    });

I would, though, suggest using focus() instead:

$('input:text').focus(
    function(){
        $(this).val('');
    });

Which responds to keyboard events too (the tab key, for example). Also, you could use the placeholder attribute in the element:

<input type="text" placeholder="default text" />

Which will clear on focus of the element, and reappear if the element remains empty/user doesn't input anything.

how to execute php code within javascript

May be this way:

    <?php 
     if($_SERVER['REQUEST_METHOD']=="POST") {
       echo 'asdasda';
     }
    ?>

    <form method="post">
    <button type="submit" id="okButton">Order now</button>
</form>

How can I remove all files in my git repo and update/push from my local git repo?

I have tried like this

git rm --cached -r * -f

And it is working for me.

Show percent % instead of counts in charts of categorical variables

Since version 3.3 of ggplot2, we have access to the convenient after_stat() function.

We can do something similar to @Andrew's answer, but without using the .. syntax:

# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

You can find all the "computed variables" available to use in the documentation of the geom_ and stat_ functions. For example, for geom_bar(), you can access the count and prop variables. (See the documentation for computed variables.)

One comment about your NULL values: they are ignored when you create the vector (i.e. you end up with a vector of length 9, not 11). If you really want to keep track of missing data, you will have to use NA instead (ggplot2 will put NAs at the right end of the plot):

# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

Created on 2021-02-09 by the reprex package (v1.0.0)

(Note that using chr or fct data will not make a difference for your example.)

How do I run a node.js app as a background service?

If you are using pm2, you can use it with autorestart set to false:

$ pm2 ecosystem

This will generate a sample ecosystem.config.js:

module.exports = {
  apps: [
    {
      script: './scripts/companies.js',
      autorestart: false,
    },
    {
      script: './scripts/domains.js',
      autorestart: false,
    },
    {
      script: './scripts/technologies.js',
      autorestart: false,
    },
  ],
}

$ pm2 start ecosystem.config.js

Android ImageView setImageResource in code

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);

How to reverse a 'rails generate'

Removed scaffolding for selected model:

bin/rails d scaffold <AccessControl> //model name

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

I want to show all tables that have specified column name

SELECT      T.TABLE_NAME, C.COLUMN_NAME
FROM        INFORMATION_SCHEMA.COLUMNS C
            INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE       TABLE_TYPE = 'BASE TABLE'
            AND COLUMN_NAME = 'ColName'

This returns tables only and ignores views for anyone who is interested!

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.

For asp core 2.2:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace Project
{
    sealed class Program
    {
        #region Variables
        /// <summary>
        /// Last loaded configuration
        /// </summary>
        private static IConfiguration _Configuration;
        #endregion

        #region Properties
        /// <summary>
        /// Default application configuration
        /// </summary>
        internal static IConfiguration Configuration
        {
            get
            {
                // None configuration yet?
                if (Program._Configuration == null)
                {
                    // Create the builder using a callback class
                    IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();

                    // Build everything but do not initialize it
                    builder.Build();
                }

                // Current configuration
                return Program._Configuration;
            }

            // Update configuration
            set => Program._Configuration = value;
        }
        #endregion

        #region Public
        /// <summary>
        /// Start the webapp
        /// </summary>
        public static void Main(string[] args)
        {
            // Create the builder using the default Startup class
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            // Build everything and run it
            using (IWebHost host = builder.Build())
                host.Run();
        }
        #endregion


        #region CallBackConfiguration
        /// <summary>
        /// Aux class to callback configuration
        /// </summary>
        private class CallBackConfiguration
        {
            /// <summary>
            /// Callback with configuration
            /// </summary>
            public CallBackConfiguration(IConfiguration configuration)
            {
                // Update the last configuration
                Program.Configuration = configuration;
            }

            /// <summary>
            /// Do nothing, just for compatibility
            /// </summary>
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //
            }
        }
        #endregion
    }
}

So now on you just use the static Program.Configuration at any other class you need it.

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/

How to get error information when HttpWebRequest.GetResponse() fails

I faced a similar situation:

I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.

However, when reading the response using GetResponseStream(), got the error:

Stream not readable

So, this code worked for me:

try
{
    response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
    var webException = exception.InnerException as WebException;
    var rawResponse = string.Empty;

    var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
    using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
    using (var reader = new StreamReader(brandNewStream))
        rawResponse = reader.ReadToEnd();
}

How to split page into 4 equal parts?

try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.

 <html>
   <head>
   <title>CSS devide window by 25% horizontally</title>
   <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
   <style type="text/css" media="screen"> 
     body {
     margin:0;
     padding:0;
     height:100%;
     }
     #top_div
     {
       height:25%;
       width:100%;
       background-color:#009900;
       margin:auto;
       text-align:center;
     }
     #mid1_div
     {
       height:25%;
       width:100%;
       background-color:#990000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
     #mid2_div
     {
       height:25%;
       width:100%;
       background-color:#000000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
     #bottom_div
     {
       height:25%;
       width:100%;
       background-color:#990000;
       margin:auto;
       text-align:center;
       color:#FFFFFF;
     }
   </style>
   </head>
   <body>
     <div id="top_div">Top- height is 25% of window height</div>
     <div id="mid1_div">Middle 1 - height is 25% of window height</div>
     <div id="mid2_div">Middle 2 - height is 25% of window height</div>
     <div id="bottom_div">Bottom - height is 25% of window height</div>
   </body>
 </html>

Tested and works fine, copy the code above into a HTML file, and open with your browser.

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

'too many values to unpack', iterating over a dict. key=>string, value=>list

In Python3 iteritems() is no longer supported

Use .items

for field, possible_values in fields.items():
    print(field, possible_values)

php.ini: which one?

Generally speaking, the cli/php.ini file is used when the PHP binary is called from the command-line.
You can check that running php --ini from the command-line.

fpm/php.ini will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo() from a php page served by your webserver.

cgi/php.ini, in your situation, will most likely not be used.


Using two distinct php.ini files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.

Typically, in the php.ini file that's used by the web-server, you'll specify a rather short max_execution_time : web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini file that will be used is the one in cli/. For those scripts, you'll specify a much longer max_execution_time in cli/php.ini than you did in fpm/php.ini.

max_execution_time is a common example ; you could do the same with several other configuration directives, of course.

Setting default values for columns in JPA

If you're using a double, you can use the following:

@Column(columnDefinition="double precision default '96'")

private Double grolsh;

Yes it's db specific.

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

I also had the same issue when I tried to install a Windows service, in my case I managed to resolved the issue by removing blank spaces in the folder path to the service .exe, below is the command worked for me in a command prompt

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

Press ENTER to change working directory

InstallUtil.exe C:\MyService\Release\ReminderService.exe

Press ENTER

How to execute the start script with Nodemon

In package json:

{
  "name": "abc",
  "version": "0.0.1",
  "description": "my server",
  "scripts": {
    "start": "nodemon my_file.js"
  },
  "devDependencies": {
    "nodemon": "~1.3.8",
  },
  "dependencies": {

  }
}

Then from the terminal you can use npm start

Nodemon installation: https://www.npmjs.com/package/nodemon

add Shadow on UIView using swift 3

If you need rounded shadow. Works for swift 4.2

extension UIView {

        func dropShadow() {

            var shadowLayer: CAShapeLayer!
            let cornerRadius: CGFloat = 16.0
            let fillColor: UIColor = .white

            if shadowLayer == nil {
                shadowLayer = CAShapeLayer()

                shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
                shadowLayer.fillColor = fillColor.cgColor

                shadowLayer.shadowColor = UIColor.black.cgColor
                shadowLayer.shadowPath = shadowLayer.path
                shadowLayer.shadowOffset = CGSize(width: -2.0, height: 2.0)
                shadowLayer.shadowOpacity = 0.8
                shadowLayer.shadowRadius = 2

                layer.insertSublayer(shadowLayer, at: 0)
            }
        }
    }

Swift 4 rounded UIView with shadow

javac error: Class names are only accepted if annotation processing is explicitly requested

i think this is also because of incorrect compilation..

so for linux (ubuntu).....

javac file.java

java file

What does the "yield" keyword do?

From a programming viewpoint, the iterators are implemented as thunks.

To implement iterators, generators, and thread pools for concurrent execution, etc. as thunks, one uses messages sent to a closure object, which has a dispatcher, and the dispatcher answers to "messages".

"next" is a message sent to a closure, created by the "iter" call.

There are lots of ways to implement this computation. I used mutation, but it is possible to do this kind of computation without mutation, by returning the current value and the next yielder (making it referential transparent). Racket uses a sequence of transformations of the initial program in some intermediary languages, one of such rewriting making the yield operator to be transformed in some language with simpler operators.

Here is a demonstration of how yield could be rewritten, which uses the structure of R6RS, but the semantics is identical to Python's. It's the same model of computation, and only a change in syntax is required to rewrite it using yield of Python.

Welcome to Racket v6.5.0.3.

-> (define gen
     (lambda (l)
       (define yield
         (lambda ()
           (if (null? l)
               'END
               (let ((v (car l)))
                 (set! l (cdr l))
                 v))))
       (lambda(m)
         (case m
           ('yield (yield))
           ('init  (lambda (data)
                     (set! l data)
                     'OK))))))
-> (define stream (gen '(1 2 3)))
-> (stream 'yield)
1
-> (stream 'yield)
2
-> (stream 'yield)
3
-> (stream 'yield)
'END
-> ((stream 'init) '(a b))
'OK
-> (stream 'yield)
'a
-> (stream 'yield)
'b
-> (stream 'yield)
'END
-> (stream 'yield)
'END
->

JQuery: How to get selected radio button value?

jQuery("input:radio[name=myradiobutton]:checked").val();

Convert NSNumber to int in Objective-C

A tested one-liner:

int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;

How do you use variables in a simple PostgreSQL script?

Here's an example of using a variable in plpgsql:

create table test (id int);
insert into test values (1);
insert into test values (2);
insert into test values (3);

create function test_fn() returns int as $$
    declare val int := 2;
    begin
        return (SELECT id FROM test WHERE id = val);
    end;
$$ LANGUAGE plpgsql;

SELECT * FROM test_fn();
 test_fn 
---------
       2

Have a look at the plpgsql docs for more information.

Fastest way of finding differences between two files in unix?

This will work fast:

Case 1 - File2 = File1 + extra text appended.

grep -Fxvf File2.txt File1.txt >> File3.txt

File 1: 80 Lines File 2: 100 Lines File 3: 20 Lines

How to remove carriage return and newline from a variable in shell script

Because the file you source ends lines with carriage returns, the contents of $testVar are likely to look like this:

$ printf '%q\n' "$testVar"
$'value123\r'

(The first line's $ is the shell prompt; the second line's $ is from the %q formatting string, indicating $'' quoting.)

To get rid of the carriage return, you can use shell parameter expansion and ANSI-C quoting (requires Bash):

testVar=${testVar//$'\r'}

Which should result in

$ printf '%q\n' "$testVar"
value123

Can Android Studio be used to run standard Java projects?

I found a somewhat hacky, annoying and not-completely-sure-it-always-works solution to this. I wanted to share in case someone else finds it useful.

In Android Studio, you can right-click a class with a main method and select "Run .main()". This will create a new Run configuration for YourClass, although it won't quite work: it will be missing some classpath entries.

In order to fix the missing classpath entries, go into the Project Structure and manually add the output folder location for your module and any other module dependencies that you need, like so:

  • File -> Project Structure ...
  • Select "Modules" in the Project Settings panel on the left-column panel
  • Select your module on the list of modules in the middle-column panel
  • Select the "Dependencies" tab on the right-column panel

And then for the module where you have your Java application as well as for each of the module dependencies you need: - Click "+" -> "Jars or directories" on the far right of the right-column panel - Navigate to the output folder of the module (e.g.: my_module/build/classes/main/java) and click "OK" - On the new entry to the Dependencies list, on the far right, change the select box from "Compile" to "Runtime"

After this, you should be able to execute the Run configuration you just created to run the simple Java application.

One thing to note is that, for my particular [quite involved] Android Studio project set-up, I have to manually build the project with gradle, from outside Android Studio in order to get my simple Java Application classes to build, before I run the application - I think this is because the Run configuration of type "Application" is not triggering the corresponding Gradle build.

Finally, this was done on Android Studio 0.4.0.

I hope others find it useful. I also hope Google comes around to supporting this functionality soon.

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

How to add 10 days to current time in Rails

Try this on Ruby. It will return a new date/time the specified number of days in the future

DateTime.now.days_since(10)

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

Please do the following checks:

1- No wires in the TX and RX of your arduino while uploading the code.
2- No soldered pins in each others.
3- If 1 and 2 are okey than you must reinstall the bootloader into your arduino using another arduino, you can search how to do that in youtube there plenty of videos talking about it.

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

For the specific case where you know the data will not have nulls (always a good idea for strings) and the data is really large, you are still doing three comparisons before actually comparing the values, if you know for sure this is your case, you can optimize a tad bit. YMMV as readable code trumps minor optimization:

        if(o1.name != null && o2.name != null){
            return o1.name.compareToIgnoreCase(o2.name);
        }
        // at least one is null
        return (o1.name == o2.name) ? 0 : (o1.name != null ? 1 : -1);

What are some reasons for jquery .focus() not working?

Try something like this when you are applying focus that way if the element is hidden, it won't throw an error:

$("#elementid").filter(':visible').focus();

It may make more sense to make the element visible, though that will require code specific to your layout.

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

Double precision - decimal places

It is because it's being converted from a binary representation. Just because it has printed all those decimal digits doesn't mean it can represent all decimal values to that precision. Take, for example, this in Python:

>>> 0.14285714285714285
0.14285714285714285
>>> 0.14285714285714286
0.14285714285714285

Notice how I changed the last digit, but it printed out the same number anyway.

Writing String to Stream and reading it back does not work

I think it would be a lot more productive to use a TextWriter, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;.

stringAsStream = new MemoryStream();

// create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
{
  sWriter.Write("Lorem ipsum.");
}
stringAsStream.Position = 0L; // rewind

Note that:

StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)

Also, you don't have to create a new UnicodeEncoding() usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.

And then, finally (as others have said) you're trying to convert the bytes directly to chars, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.

Removing padding gutter from grid columns in Bootstrap 4

Need an edge-to-edge design? Drop the parent .container or .container-fluid.

Still if you need to remove padding from .row and immediate child columns you have to add the class .no-gutters with the code from @Brian above to your own CSS file, actually it's Not 'right out of the box', check here for official details on the final Bootstrap 4 release: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters

What is lazy loading in Hibernate?

Bydefault lazy loading is true.Lazy loading means when the select query is executed it will not hit the database. It will wait for getter function i.e when we required then ,it will fetch from the datbase. for example: You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time. So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.

Animate text change in UILabel

Swift 4.2 solution (taking 4.0 answer and updating for new enums to compile)

extension UIView {
    func fadeTransition(_ duration:CFTimeInterval) {
        let animation = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name:
            CAMediaTimingFunctionName.easeInEaseOut)
        animation.type = CATransitionType.fade
        animation.duration = duration
        layer.add(animation, forKey: CATransitionType.fade.rawValue)
    }
}

func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}

Determining if Swift dictionary contains key and obtaining any of its values

My solution for a cache implementation that stores optional NSAttributedString:

public static var attributedMessageTextCache    = [String: NSAttributedString?]()

    if attributedMessageTextCache.index(forKey: "key") != nil
    {
        if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
        {
            return attributedMessageText
        }
        return nil
    }

    TextChatCache.attributedMessageTextCache["key"] = .some(.none)
    return nil

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

C#: Assign same value to multiple variables in single statement

Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;

php - insert a variable in an echo string

You can try this

$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i; 

In OS X Lion, LANG is not set to UTF-8, how to fix it?

This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

Parse HTML in Android

Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.

http://developer.android.com/reference/android/webkit/WebView.html

I think that you can enable javascript if you need it.

What is "android:allowBackup"?

This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).

http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html

Microsoft.Office.Core Reference Missing

You can use this NuGet package which includes the interop assemblies in addition to the office assembly.

https://www.nuget.org/packages/Bundle.Microsoft.Office.Interop/

NPM clean modules

In a word no.

In two, not yet.

There is, however, an open issue for a --no-build flag to npm install to perform an installation without building, which could be used to do what you're asking.

See this open issue.

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

Best way to define error codes/strings in Java?

There are many ways to solve this. My preferred approach is to have interfaces:

public interface ICode {
     /*your preferred code type here, can be int or string or whatever*/ id();
}

public interface IMessage {
    ICode code();
}

Now you can define any number of enums which provide messages:

public enum DatabaseMessage implements IMessage {
     CONNECTION_FAILURE(DatabaseCode.CONNECTION_FAILURE, ...);
}

Now you have several options to turn those into Strings. You can compile the strings into your code (using annotations or enum constructor parameters) or you can read them from a config/property file or from a database table or a mixture. The latter is my preferred approach because you will always need some messages that you can turn into text very early (ie. while you connect to the database or read the config).

I'm using unit tests and reflection frameworks to find all types that implement my interfaces to make sure each code is used somewhere and that the config files contain all expected messages, etc.

Using frameworks that can parse Java like https://github.com/javaparser/javaparser or the one from Eclipse, you can even check where the enums are used and find unused ones.

Java - Check if JTextField is empty or not

The following will return true if the JTextField "name" does not contain text:

name.getText().isEmpty

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Yes, on Arrays.asList, returning a fixed-size list.

Other than using a linked list, simply use addAll method list.

Example:

String idList = "123,222,333,444";

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

parentRecepeIdList.addAll(Arrays.asList(idList.split(","))); 

parentRecepeIdList.add("555");

How to autoplay HTML5 mp4 video on Android?

Chrome has disabled it. https://bugs.chromium.org/p/chromium/issues/detail?id=159336 Even the jQuery play() is blocked. They want user to initiate it so bandwidth can be saved.

Can I specify multiple users for myself in .gitconfig?

GIT_AUTHOR_EMAIL + local .bashrc

.bashrc_local: don't track this file, put it only on your work computer:

export GIT_AUTHOR_EMAIL='[email protected]'
export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"

.bashrc: track this file, make it the same on both work and home computers:

F="$HOME/.bashrc_local"
if [ -r "$F" ]; then
    . "$F"
fi

I'm using https://github.com/technicalpickles/homesick to sync my dotfiles.

If only gitconfig would accept environment variables: Shell variable expansion in git config

Bash or KornShell (ksh)?

For scripts, I always use ksh because it smooths over gotchas.

But I find bash more comfortable for interactive use. For me the emacs key bindings and tab completion are the main benefits. But that's mostly force of habit, not any technical issue with ksh.

SQL: Select columns with NULL values only

An updated version of 'user2466387' version, with an additional small test which can improve performance, because it's useless to test non nullable columns:

AND IS_NULLABLE = 'YES'

The full code:

SET NOCOUNT ON;

DECLARE
 @ColumnName sysname
,@DataType nvarchar(128)
,@cmd nvarchar(max)
,@TableSchema nvarchar(128) = 'dbo'
,@TableName sysname = 'TableName';

DECLARE getinfo CURSOR FOR
SELECT
     c.COLUMN_NAME
    ,c.DATA_TYPE
FROM
    INFORMATION_SCHEMA.COLUMNS AS c
WHERE
    c.TABLE_SCHEMA = @TableSchema
    AND c.TABLE_NAME = @TableName
    AND IS_NULLABLE = 'YES';

OPEN getinfo;

FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName + N' WHERE [' + @ColumnName + N'] IS NOT NULL) RAISERROR(''' + @ColumnName + N' (' + @DataType + N')'', 0, 0) WITH NOWAIT;';
    EXECUTE (@cmd);

    FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;
END;

CLOSE getinfo;
DEALLOCATE getinfo;

Reading RFID with Android phones

I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.

More devices are from Motorola & other vendors as well!

We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).

The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!

This is the sample app:

We get all the device paired to our Android/iOS phones :

get device list

connect

connected

Scan