Programs & Examples On #Pii

PII stands for Personally Identifiable Information -- that information which can uniquely identify an individual.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Override
public void configure(WebSecurity web) throws Exception {
    if (enableSwagger)  
        web.ignoring().antMatchers("/v2/api-docs",
                               "/configuration/ui",
                               "/swagger-resources/**",
                               "/configuration/security",
                               "/swagger-ui.html",
                               "/webjars/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}

No connection could be made because the target machine actively refused it 127.0.0.1

If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)

How to add DOM element script to head section?

For modern browsers, the best solution is to use Promises.

Go to https://stackoverflow.com/a/63936671/13720928 to find out more!

conversion from string to json object android

its work

    String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";

    try {

        JSONObject obj = new JSONObject(json);

        Log.d("My App", obj.toString());
        Log.d("phonetype value ", obj.getString("phonetype"));

    } catch (Throwable tx) {
        Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
    }

Jenkins returned status code 128 with github

In my case I had to add the public key to my repo (at Bitbucket) AND use git clone once via ssh to answer yes to the "known host" question the first time.

Display Images Inline via CSS

Place this css in your page:

<style>
   #client_logos {
    display: inline-block;
    width:100%;
    }
  </style>

Replace

<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>

To

<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>

Store an array in HashMap

Yes, the Map interface will allow you to store Arrays as values. Here's a very simple example:

int[] val = {1, 2, 3};
Map<String, int[]> map = new HashMap<String, int[]>();
map.put("KEY1", val);

Also, depending on your use case you may want to look at the Multimap support offered by guava.

Web Reference vs. Service Reference

Adding a service reference allows you to create a WCF client, which can be used to talk to a regular web service provided you use the appropriate binding. Adding a web reference will allow you to create only a web service (i.e., SOAP) reference.

If you are absolutely certain you are not ready for WCF (really don't know why) then you should create a regular web service reference.

How to add Python to Windows registry

When installing Python 3.4 the "Add python.exe to Path" came up unselected. Re-installed with this selected and problem resolved.

Parsing JSON using Json.net

Edit: Thanks Marc, read up on the struct vs class issue and you're right, thank you!

I tend to use the following method for doing what you describe, using a static method of JSon.Net:

MyObject deserializedObject = JsonConvert.DeserializeObject<MyObject>(json);

Link: Serializing and Deserializing JSON with Json.NET

For the Objects list, may I suggest using generic lists out made out of your own small class containing attributes and position class. You can use the Point struct in System.Drawing (System.Drawing.Point or System.Drawing.PointF for floating point numbers) for you X and Y.

After object creation it's much easier to get the data you're after vs. the text parsing you're otherwise looking at.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

For me it was a Firewall issue.

First you have to add the port (such as 1444 and maybe 1434) but also

C:\Program Files (x86)\Microsoft SQL Server\90\Shared\sqlbrowser.exe

and

%ProgramFiles%\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\Binn\SQLAGENT.EXE

The second time I got this issue is when I came back to the firewall, the paths were not correct and I needed to update form 12 to 13! Simply clicking on browse in the Programs and Services tab helped to realise this.

Finally, try running the command

EXEC xp_readerrorlog 0,1,"could not register the Service Principal Name",Null

For me, it returned the error reason

How to pass value from <option><select> to form action

You don't have to use jQuery or Javascript.

Use the name tag of the select and let the form do it's job.

<select name="agent_id" id="agent_id">

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

a:hover{text-decoration: underline !important}
a{text-decoration: none !important}

Check if a value exists in ArrayList

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

How to unit test abstract classes: extend with stubs?

If your abstract class contains concrete functionality that has business value, then I will usually test it directly by creating a test double that stubs out the abstract data, or by using a mocking framework to do this for me. Which one I choose depends a lot on whether I need to write test-specific implementations of the abstract methods or not.

The most common scenario in which I need to do this is when I'm using the Template Method pattern, such as when I'm building some sort of extensible framework that will be used by a 3rd party. In this case, the abstract class is what defines the algorithm that I want to test, so it makes more sense to test the abstract base than a specific implementation.

However, I think it's important that these tests should focus on the concrete implementations of real business logic only; you shouldn't unit test implementation details of the abstract class because you'll end up with brittle tests.

How to convert int[] to Integer[] in Java?

Not sure why you need a Double in your map. In terms of what you're trying to do, you have an int[] and you just want counts of how many times each sequence occurs? Why would this required a Double anyway?

What I would do is to create a wrapper for the int array with a proper .equals and .hashCode methods to account for the fact that int[] object itself doesn't consider the data in it's version of these methods.

public class IntArrayWrapper {
    private int values[];

    public IntArrayWrapper(int[] values) {
        super();
        this.values = values;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(values);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        IntArrayWrapper other = (IntArrayWrapper) obj;
        if (!Arrays.equals(values, other.values))
            return false;
        return true;
    }

}

And then use google guava's multiset, which is meant exactly for the purpose of counting occurances, as long as the element type you put in it has proper .equals and .hashCode methods.

List<int[]> list = ...;
HashMultiset<IntArrayWrapper> multiset = HashMultiset.create();
for (int values[] : list) {
    multiset.add(new IntArrayWrapper(values));
}

Then, to get the count for any particular combination:

int cnt = multiset.count(new IntArrayWrapper(new int[] { 0, 1, 2, 3 }));

sqlalchemy filter multiple columns

You can simply call filter multiple times:

query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
                                 filter(User.lastname.like(searchVar2))

Determine if $.ajax error is a timeout

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

Per the jQuery documentation:

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

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

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

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

Hope this helps!

python-pandas and databases like mysql

This should work just fine.

import MySQLdb as mdb
import pandas as pd
con = mdb.connect(‘127.0.0.1’, ‘root’, ‘password’, ‘database_name’);
with con:
 cur = con.cursor()
 cur.execute(“select random_number_one, random_number_two, random_number_three from randomness.a_random_table”)
 rows = cur.fetchall()
 df = pd.DataFrame( [[ij for ij in i] for i in rows] )
 df.rename(columns={0: ‘Random Number One’, 1: ‘Random Number Two’, 2: ‘Random Number Three’}, inplace=True);
 print(df.head(20))

Add days to JavaScript Date

Correct Answer:

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

Incorrect Answer:

This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.

// Don't do it this way!
function addDaysWRONG(date, days) {
  var result = new Date();
  result.setDate(date.getDate() + days);
  return result;
}

Proof / Example

Check this JsFiddle

_x000D_
_x000D_
// Correct_x000D_
function addDays(date, days) {_x000D_
    var result = new Date(date);_x000D_
    result.setDate(result.getDate() + days);_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Bad Year/Month_x000D_
function addDaysWRONG(date, days) {_x000D_
    var result = new Date();_x000D_
    result.setDate(date.getDate() + days);_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Bad during DST_x000D_
function addDaysDstFail(date, days) {_x000D_
    var dayms = (days * 24 * 60 * 60 * 1000);_x000D_
    return new Date(date.getTime() + dayms);    _x000D_
}_x000D_
_x000D_
// TEST_x000D_
function formatDate(date) {_x000D_
    return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();_x000D_
}_x000D_
_x000D_
$('tbody tr td:first-child').each(function () {_x000D_
    var $in = $(this);_x000D_
    var $out = $('<td/>').insertAfter($in).addClass("answer");_x000D_
    var $outFail = $('<td/>').insertAfter($out);_x000D_
    var $outDstFail = $('<td/>').insertAfter($outFail);_x000D_
    var date = new Date($in.text());_x000D_
    var correctDate = formatDate(addDays(date, 1));_x000D_
    var failDate = formatDate(addDaysWRONG(date, 1));_x000D_
    var failDstDate = formatDate(addDaysDstFail(date, 1));_x000D_
_x000D_
    $out.text(correctDate);_x000D_
    $outFail.text(failDate);_x000D_
    $outDstFail.text(failDstDate);_x000D_
    $outFail.addClass(correctDate == failDate ? "right" : "wrong");_x000D_
    $outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");_x000D_
});
_x000D_
body {_x000D_
    font-size: 14px;_x000D_
}_x000D_
_x000D_
table {_x000D_
    border-collapse:collapse;_x000D_
}_x000D_
table, td, th {_x000D_
    border:1px solid black;_x000D_
}_x000D_
td {_x000D_
    padding: 2px;_x000D_
}_x000D_
_x000D_
.wrong {_x000D_
    color: red;_x000D_
}_x000D_
.right {_x000D_
    color: green;_x000D_
}_x000D_
.answer {_x000D_
    font-weight: bold;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th colspan="4">DST Dates</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>03/10/2013</td></tr>_x000D_
        <tr><td>11/03/2013</td></tr>_x000D_
        <tr><td>03/09/2014</td></tr>_x000D_
        <tr><td>11/02/2014</td></tr>_x000D_
        <tr><td>03/08/2015</td></tr>_x000D_
        <tr><td>11/01/2015</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2013</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2013</td></tr>_x000D_
        <tr><td>02/01/2013</td></tr>_x000D_
        <tr><td>03/01/2013</td></tr>_x000D_
        <tr><td>04/01/2013</td></tr>_x000D_
        <tr><td>05/01/2013</td></tr>_x000D_
        <tr><td>06/01/2013</td></tr>_x000D_
        <tr><td>07/01/2013</td></tr>_x000D_
        <tr><td>08/01/2013</td></tr>_x000D_
        <tr><td>09/01/2013</td></tr>_x000D_
        <tr><td>10/01/2013</td></tr>_x000D_
        <tr><td>11/01/2013</td></tr>_x000D_
        <tr><td>12/01/2013</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2014</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2014</td></tr>_x000D_
        <tr><td>02/01/2014</td></tr>_x000D_
        <tr><td>03/01/2014</td></tr>_x000D_
        <tr><td>04/01/2014</td></tr>_x000D_
        <tr><td>05/01/2014</td></tr>_x000D_
        <tr><td>06/01/2014</td></tr>_x000D_
        <tr><td>07/01/2014</td></tr>_x000D_
        <tr><td>08/01/2014</td></tr>_x000D_
        <tr><td>09/01/2014</td></tr>_x000D_
        <tr><td>10/01/2014</td></tr>_x000D_
        <tr><td>11/01/2014</td></tr>_x000D_
        <tr><td>12/01/2014</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2015</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2015</td></tr>_x000D_
        <tr><td>02/01/2015</td></tr>_x000D_
        <tr><td>03/01/2015</td></tr>_x000D_
        <tr><td>04/01/2015</td></tr>_x000D_
        <tr><td>05/01/2015</td></tr>_x000D_
        <tr><td>06/01/2015</td></tr>_x000D_
        <tr><td>07/01/2015</td></tr>_x000D_
        <tr><td>08/01/2015</td></tr>_x000D_
        <tr><td>09/01/2015</td></tr>_x000D_
        <tr><td>10/01/2015</td></tr>_x000D_
        <tr><td>11/01/2015</td></tr>_x000D_
        <tr><td>12/01/2015</td></tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Javascript: The prettiest way to compare one value against multiple values

Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:

if (foobar === foo || foobar === bar) {
     //do something
}

And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:

// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);

// test the Set at runtime
if (tSet.has(foobar)) {
    // do something
}

For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.

Is right click a Javascript event?

Yes, its a javascript mousedown event. There is a jQuery plugin too to do it

Div with horizontal scrolling only

For horizontal scroll, keep these two properties in mind:

overflow-x:scroll;
white-space: nowrap;

See working link : click me

HTML

<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better   control of the layout. The default value is visible.You can use the overflow property when you want     to have better control of the layout. The default value is visible.</div>

CSS

div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}

What is the easiest way to remove the first character from a string?

class String
  def bye_felicia()
    felicia = self.strip[0] #first char, not first space.
    self.sub(felicia, '')
  end
end

Replace all non-alphanumeric characters in a string

Try:

s = filter(str.isalnum, s)

in Python3:

s = ''.join(filter(str.isalnum, s))

Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit

How to push JSON object in to array using javascript

can you try something like this. You have to put each json in the data not json[i], because in the way you are doing it you are getting and putting only the properties of each json. Put the whole json instead in the data

 var my_json;
    $.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
    console.log(json1);
        var data = [];
    json1.feeds.forEach(function(feed,i){
        console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
        my_json = feed;
        console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
        data.push(my_json);
    }); 

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

How do I create a slug in Django?

If you're using the admin interface to add new items of your model, you can set up a ModelAdmin in your admin.py and utilize prepopulated_fields to automate entering of a slug:

class ClientAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Client, ClientAdmin)

Here, when the user enters a value in the admin form for the name field, the slug will be automatically populated with the correct slugified name.

Angular 2 - innerHTML styling

If you're trying to style dynamically added HTML elements inside an Angular component, this might be helpful:

// inside component class...
    
constructor(private hostRef: ElementRef) { }
    
getContentAttr(): string {
  const attrs = this.hostRef.nativeElement.attributes
  for (let i = 0, l = attrs.length; i < l; i++) {
    if (attrs[i].name.startsWith('_nghost-c')) {
      return `_ngcontent-c${attrs[i].name.substring(9)}`
    }
  }
}
    
ngAfterViewInit() {
  // dynamically add HTML element
  dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}

My guess is that the convention for this attribute is not guaranteed to be stable between versions of Angular, so that one might run into problems with this solution when upgrading to a new version of Angular (although, updating this solution would likely be trivial in that case).

jQuery.ajax handling continue responses: "success:" vs ".done"?

From JQuery Documentation

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Comparing HTTP and FTP for transferring files

Both of them uses TCP as a transport protocol, but HTTP uses a persistent connection, which makes the performance of the TCP better.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.

SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';

How do I find out which DOM element has the focus?

If you want to get a object that is instance of Element, you must use document.activeElement, but if you want to get a object that is instance of Text, you must to use document.getSelection().focusNode.

I hope helps.

Good PHP ORM Library?

I really like Propel, here you can get an overview, the documentation is pretty good, and you can get it through PEAR or SVN.

You only need a working PHP5 install, and Phing to start generating classes.

Get most recent file in a directory on Linux

With only Bash builtins, closely following BashFAQ/003:

shopt -s nullglob

for f in * .*; do
    [[ -d $f ]] && continue
    [[ $f -nt $latest ]] && latest=$f
done

printf '%s\n' "$latest"

How to insert newline in string literal?

Here, Environment.NewLine doesn't worked.

I put a "<br/>" in a string and worked.

Ex:

ltrYourLiteral.Text = "First line.<br/>Second Line.";

git rebase fatal: Needed a single revision

The issue is that you branched off a branch off of.... where you are trying to rebase to. You can't rebase to a branch that does not contain the commit your current branch was originally created on.

I got this when I first rebased a local branch X to a pushed one Y, then tried to rebase a branch (first created on X) to the pushed one Y.

Solved for me by rebasing to X.

I have no problem rebasing to remote branches (potentially not even checked out), provided my current branch stems from an ancestor of that branch.

How can I calculate the number of years between two dates?

let currentTime = new Date().getTime();
let birthDateTime= new Date(birthDate).getTime();
let difference = (currentTime - birthDateTime)
var ageInYears=difference/(1000*60*60*24*365)

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

Your sample code won't work as shown because you forgot to include a Console.ReadLine() before the serviceHost.Close() line. That means the host is opened and then immediately closed.

Other than that, it seems you have a permission problem on your machine. Ensure you are logged-in as an administrator account on your machine. If you are an administrator then it may be that you don't have the World Wide Web Publishing Service (W3SVC) running to handle HTTP requests.

Regular Expression - 2 letters and 2 numbers in C#

This should get you for starting with two letters and ending with two numbers.

[A-Za-z]{2}(.*)[0-9]{2}

If you know it will always be just two and two you can

[A-Za-z]{2}[0-9]{2}

Importing csv file into R - numeric values read as characters

version for data.table based on code from dmanuge :

convNumValues<-function(ds){
  ds<-data.table(ds)
  dsnum<-data.table(data.matrix(ds))
  num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
  nds <- data.table(  dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
                        ,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}

View HTTP headers in Google Chrome?

For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:

  1. While the browser is open, press F12 to access Web Developer tools

  2. When opened, click the "Network" option

  3. Initially, it is possible the page data is not present/up to date. Refresh the page if necessary

  4. Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)

see screenshot

Catch checked change event of a checkbox

<input type="checkbox" id="something" />

$("#something").click( function(){
   if( $(this).is(':checked') ) alert("checked");
});

Edit: Doing this will not catch when the checkbox changes for other reasons than a click, like using the keyboard. To avoid this problem, listen to changeinstead of click.

For checking/unchecking programmatically, take a look at Why isn't my checkbox change event triggered?

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

Showing the same file in both columns of a Sublime Text window

Yes, you can. When a file is open, click on File -> New View Into File. You can then drag the new tab to the other pane and view the file twice.

There are several ways to create a new pane. As described in other answers, on Linux and Windows, you can use AltShift2 (Option ?Command ?2 on OS X), which corresponds to View ? Layout ? Columns: 2 in the menu. If you have the excellent Origami plugin installed, you can use View ? Origami ? Pane ? Create ? Right, or the CtrlK, Ctrl? chord on Windows/Linux (replace Ctrl with ? on OS X).

reading from app.config file

Also add the key "StartingMonthColumn" in App.config that you run application from, for example in the App.config of the test project.

c++ Read from .csv file

That because your csv file is in invalid format, maybe the line break in your text file is not the \n or \r

and, using c/c++ to parse text is not a good idea. try awk:

 $awk -F"," '{print "ID="$1"\tName="$2"\tAge="$3"\tGender="$4}' 1.csv
 ID=0   Name=Filipe Age=19  Gender=M
 ID=1   Name=Maria  Age=20  Gender=F
 ID=2   Name=Walter Age=60  Gender=M

How to write a Unit Test?

This is a very generic question and there is a lot of ways it can be answered.

If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single "production" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.

In your specific example, you could for example test the following:

  1. A simple addition between two positive numbers. Add them, then verify the result is what you would expect.
  2. An addition between a positive and a negative number (which returns a result with the sign of the first argument).
  3. An addition between a positive and a negative number (which returns a result with the sign of the second argument).
  4. An addition between two negative numbers.
  5. An addition that results in an overflow.

To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).

Example testcase class in your case (without the methods contents defined):

import static org.junit.Assert.*;

public class AdditionTests {
    @Test
    public void testSimpleAddition() { ... }


    @Test
    public void testPositiveNegativeAddition() { ... }


    @Test
    public void testNegativePositiveAddition() { ... }


    @Test
    public void testNegativeAddition() { ... }


    @Test
    public void testOverflow() { ... }
}

If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate "visually" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

How to get first character of a string in SQL?

LEFT(colName, 1) will also do this, also. It's equivalent to SUBSTRING(colName, 1, 1).

I like LEFT, since I find it a bit cleaner, but really, there's no difference either way.

Vue - Deep watching an array of objects and calculating the change?

It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal and oldVal refer to the same object. Vue will not keep an old copy of an object that you mutated.

Had you replaced the object with another one, Vue would have provided you with correct references.

Read the Note section in the docs. (vm.$watch)

More on this here and here.

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

GIF has 8 bit (256 color) palette where PNG as upto 24 bit color palette. So, PNG can support more color and of course the algorithm support compression

How to show only next line after the matched one?

grep /Pattern/ | tail -n 2 | head -n 1

Tail first 2 and then head last one to get exactly first line after match.

Bash script to calculate time elapsed

start=$(date +%Y%m%d%H%M%S);
for x in {1..5};
do echo $x;
sleep 1; done;
end=$(date +%Y%m%d%H%M%S);
elapsed=$(($end-$start));
ftime=$(for((i=1;i<=$((${#end}-${#elapsed}));i++));
        do echo -n "-";
        done;
        echo ${elapsed});
echo -e "Start  : ${start}\nStop   : ${end}\nElapsed: ${ftime}"

Start  : 20171108005304
Stop   : 20171108005310
Elapsed: -------------6

Floating point inaccuracy examples

Here is my simple understanding.

Problem: The value 0.45 cannot be accurately be represented by a float and is rounded up to 0.450000018. Why is that?

Answer: An int value of 45 is represented by the binary value 101101. In order to make the value 0.45 it would be accurate if it you could take 45 x 10^-2 (= 45 / 10^2.) But that’s impossible because you must use the base 2 instead of 10.

So the closest to 10^2 = 100 would be 128 = 2^7. The total number of bits you need is 9 : 6 for the value 45 (101101) + 3 bits for the value 7 (111). Then the value 45 x 2^-7 = 0.3515625. Now you have a serious inaccuracy problem. 0.3515625 is not nearly close to 0.45.

How do we improve this inaccuracy? Well we could change the value 45 and 7 to something else.

How about 460 x 2^-10 = 0.44921875. You are now using 9 bits for 460 and 4 bits for 10. Then it’s a bit closer but still not that close. However if your initial desired value was 0.44921875 then you would get an exact match with no approximation.

So the formula for your value would be X = A x 2^B. Where A and B are integer values positive or negative. Obviously the higher the numbers can be the higher would your accuracy become however as you know the number of bits to represent the values A and B are limited. For float you have a total number of 32. Double has 64 and Decimal has 128.

Accessing nested JavaScript objects and arrays by string path

Inspired by @webjay's answer: https://stackoverflow.com/a/46008856/4110122

I made this function which can you use it to Get/ Set/ Unset any value in object

function Object_Manager(obj, Path, value, Action) 
{
    try
    {
        if(Array.isArray(Path) == false)
        {
            Path = [Path];
        }

        let level = 0;
        var Return_Value;
        Path.reduce((a, b)=>{
            level++;
            if (level === Path.length)
            {
                if(Action === 'Set')
                {
                    a[b] = value;
                    return value;
                }
                else if(Action === 'Get')
                {
                    Return_Value = a[b];
                }
                else if(Action === 'Unset')
                {
                    delete a[b];
                }
            } 
            else 
            {
                return a[b];
            }
        }, obj);
        return Return_Value;
    }

    catch(err)
    {
        console.error(err);
        return obj;
    }
}

To use it:

 // Set
 Object_Manager(Obj,[Level1,Level2,Level3],New_Value, 'Set');

 // Get
 Object_Manager(Obj,[Level1,Level2,Level3],'', 'Get');

 // Unset
 Object_Manager(Obj,[Level1,Level2,Level3],'', 'Unset');

How to use Visual Studio Code as Default Editor for Git

Another useful option is to set EDITOR environment variable. This environment variable is used by many utilities to know what editor to use. Git also uses it if no core.editor is set.

You can set it for current session using:

export EDITOR="code --wait"

This way not only git, but many other applications will use VS Code as an editor.

To make this change permanent, add this to your ~/.profile for example. See this question for more options.


Another advantage of this approach is that you can set different editors for different cases:

  1. When you working from local terminal.
  2. When you are connected through SSH session.

This is useful especially with VS Code (or any other GUI editor) because it just doesn't work without GUI.

On Linux OS, put this into your ~/.profile:

# Preferred editor for local and remote sessions
if [[ -n $SSH_CONNECTION ]]; then # SSH mode
  export EDITOR='vim'
else # Local terminal mode
  export EDITOR='code -w'
fi

This way when you use a local terminal, the $SSH_CONNECTION environment variable will be empty, so the code -w editor will be used, but when you are connected through SSH, then $SSH_CONNECTION environment variable will be a non-empty string, so the vim editor will be used. It is console editor, so it will work even when you are connected through SSH.

Java: how do I get a class literal from a generic type?

You could use a helper method to get rid of @SuppressWarnings("unchecked") all over a class.

@SuppressWarnings("unchecked")
private static <T> Class<T> generify(Class<?> cls) {
    return (Class<T>)cls;
}

Then you could write

Class<List<Foo>> cls = generify(List.class);

Other usage examples are

  Class<Map<String, Integer>> cls;

  cls = generify(Map.class);

  cls = TheClass.<Map<String, Integer>>generify(Map.class);

  funWithTypeParam(generify(Map.class));

public void funWithTypeParam(Class<Map<String, Integer>> cls) {
}

However, since it is rarely really useful, and the usage of the method defeats the compiler's type checking, I would not recommend to implement it in a place where it is publicly accessible.

How to import the class within the same directory or sub directory?

To make it more simple to understand:

Step 1: lets go to one directory, where all will be included

$ cd /var/tmp

Step 2: now lets make a class1.py file which has a class name Class1 with some code

$ cat > class1.py <<\EOF
class Class1:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class1 OK]: " + ENDC
EOF

Step 3: now lets make a class2.py file which has a class name Class2 with some code

$ cat > class2.py <<\EOF
class Class2:
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'
    OK = OKBLUE + "[Class2 OK]: " + ENDC
EOF

Step 4: now lets make one main.py which will be execute once to use Class1 and Class2 from 2 different files

$ cat > main.py <<\EOF
"""this is how we are actually calling class1.py and  from that file loading Class1"""
from class1 import Class1 
"""this is how we are actually calling class2.py and  from that file loading Class2"""
from class2 import Class2

print Class1.OK
print Class2.OK
EOF

Step 5: Run the program

$ python main.py

The output would be

[Class1 OK]: 
[Class2 OK]:

git checkout tag, git pull fails in branch

In order to just download updates:

git fetch origin master

However, this just updates a reference called origin/master. The best way to update your local master would be the checkout/merge mentioned in another comment. If you can guarantee that your local master has not diverged from the main trunk that origin/master is on, you could use git update-ref to map your current master to the new point, but that's probably not the best solution to be using on a regular basis...

Assign a synthesizable initial value to a reg in Verilog

The other answers are all good. For Xilinx FPGA designs, it is best not to use global reset lines, and use initial blocks for reset conditions for most logic. Here is the white paper from Ken Chapman (Xilinx FPGA guru)

http://japan.xilinx.com/support/documentation/white_papers/wp272.pdf

SQL Server convert select a column and convert it to a string

The current accepted answer doesn't work for multiple groupings.
Try this when you need to operate on categories of column row-values.

Suppose I have the following data:

+---------+-----------+
| column1 |  column2  |
+---------+-----------+
| cat     | Felon     |
| cat     | Purz      |
| dog     | Fido      |
| dog     | Beethoven |
| dog     | Buddy     |
| bird    | Tweety    |
+---------+-----------+

And I want this as my output:

+------+----------------------+
| type |        names         |
+------+----------------------+
| cat  | Felon,Purz           |
| dog  | Fido,Beethoven,Buddy |
| bird | Tweety               |
+------+----------------------+

(If you're following along:

create table #column_to_list (column1 varchar(30), column2 varchar(30))
insert into #column_to_list
values 
('cat','Felon'),
('cat','Purz'),
('dog','Fido'),
('dog','Beethoven'),
('dog','Buddy'),
('bird','Tweety')

)

Now – I don’t want to go into all the syntax, but as you can see, this does the initial trick for us:

select ',' + cast(column2 as varchar(255)) as [text()]  
from #column_to_list sub
where column1 = 'dog'
for xml path('')
--Using "as [text()]" here is specific to the “for XML” line after our where clause and we can’t give a name to our selection, hence the weird column_name

output:

+------------------------------------------+
| XML_F52E2B61-18A1-11d1-B105-00805F49916B |
+------------------------------------------+
| ,Fido,Beethoven,Buddy                    |
+------------------------------------------+

You can see it’s limited in that it was for just one grouping (where column1 = ‘dog’) and it left a comma in the front, and additionally it’s named weird.

So, first let's handle the leading comma using the 'stuff' function and name our column stuff_list:

select stuff([list],1,1,'') as stuff_list
from (select ',' + cast(column2 as varchar(255)) as [text()]
         from #column_to_list sub
         where column1 = 'dog'
         for xml path('')
         ) sub_query([list]) 
--"sub_query([list])" just names our column as '[list]' so we can refer to it in the stuff function.  

Output:

+----------------------+
|      stuff_list      |
+----------------------+
| Fido,Beethoven,Buddy |
+----------------------+

Finally let’s just mush this into a select statement, noting the reference to the top_query alias defining which column1 we want (on the 5th line here):

select top_query.column1, 
          (select stuff([list],1,1,'') as stuff_list
         from (select ',' + cast(column2 as varchar(255)) as [text()]
                  from #column_to_list sub
                  where sub.column1 = top_query.column1
                  for xml path('')
                  ) sub_query([list])
              ) as pet_list
from  #column_to_list top_query
group by column1
order by column1

output:

+---------+----------------------+
| column1 |       pet_list       |
+---------+----------------------+
| bird    | Tweety               |
| cat     | Felon,Purz           |
| dog     | Fido,Beethoven,Buddy |
+---------+----------------------+

And we’re done.

You can read more here:

ggplot with 2 y axes on each side and different scales

Here are my two cents on how to do the transformations for secondary axis. First, you want to couple the the ranges of the primary and secondary data. This is usually messy in terms of polluting your global environment with variables you don't want.

To make this easier, we'll make a function factory that produces two functions, wherein scales::rescale() does all the heavy lifting. Because these are closures, they are aware of the environment in which they were created, so they 'have a memory' of the to and from parameters generated before creation.

  • One functions does the forward transformation: transforms the secondary data to the primary scale.
  • The second function does the reverse transformation: transforms data in primary units to secondary units.
library(ggplot2)
library(scales)

# Function factory for secondary axis transforms
train_sec <- function(primary, secondary) {
  from <- range(secondary)
  to   <- range(primary)
  # Forward transform for the data
  forward <- function(x) {
    rescale(x, from = from, to = to)
  }
  # Reverse transform for the secondary axis
  reverse <- function(x) {
    rescale(x, from = to, to = from)
  }
  list(fwd = forward, rev = reverse)
}

This seems all rather complicated, but making the function factory makes all the rest easier. Now, before we make a plot, we'll produce the relevant functions by showing the factory the primary and secondary data. We'll use the economics dataset which has very different ranges for the unemploy and psavert columns.

sec <- with(economics, train_sec(unemploy, psavert))

Then we use y = sec$fwd(psavert) to rescale the secondary data to primary axis, and specify ~ sec$rev(.) as the transformation argument to the secondary axis. This gives us a plot where the primary and secondary ranges occupy the same space on the plot.

ggplot(economics, aes(date)) +
  geom_line(aes(y = unemploy), colour = "blue") +
  geom_line(aes(y = sec$fwd(psavert)), colour = "red") +
  scale_y_continuous(sec.axis = sec_axis(~sec$rev(.), name = "psavert"))

The factory is slightly more flexible than that, because if you simply want to rescale the maximum, you can pass in data that has the lower limit at 0.

# Rescaling the maximum
sec <- with(economics, train_sec(c(0, max(unemploy)),
                                 c(0, max(psavert))))

ggplot(economics, aes(date)) +
  geom_line(aes(y = unemploy), colour = "blue") +
  geom_line(aes(y = sec$fwd(psavert)), colour = "red") +
  scale_y_continuous(sec.axis = sec_axis(~sec$rev(.), name = "psavert"))

Created on 2021-02-05 by the reprex package (v0.3.0)

I admit the difference in this example is not that very obvious, but if you look closely you can see that the maxima are the same and the red line goes lower than the blue one.

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

Exploring Docker container's file system

The docker exec command to run a command in a running container can help in multiple cases.


Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a
                             container
  -e, --env list             Set environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format:
                             [:])
  -w, --workdir string       Working directory inside the container

For example :

1) Accessing in bash to the running container filesystem :

docker exec -it containerId bash 

2) Accessing in bash to the running container filesystem as root to be able to have required rights :

docker exec -it -u root containerId bash  

This is particularly useful to be able to do some processing as root in a container.

3) Accessing in bash to the running container filesystem with a specific working directory :

docker exec -it -w /var/lib containerId bash 

Easiest way to read from and write to files

Or, if you are really about lines:

System.IO.File also contains a static method WriteAllLines, so you could do:

IList<string> myLines = new List<string>()
{
    "line1",
    "line2",
    "line3",
};

File.WriteAllLines("./foo", myLines);

Escaping quotation marks in PHP

Save your text not in a PHP file, but in an ordinary text file called, say, "text.txt"

Then with one simple $text1 = file_get_contents('text.txt'); command have your text with not a single problem.

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Try this:

$('select[name="' + name + '"] option:selected').val();

This will get the selected value of your menu.

CSS to keep element at "fixed" position on screen

position: fixed;

Will make this happen.

It handles like position:absolute; with the exception that it will scroll with the window as the user scrolls down the content.

Ctrl+click doesn't work in Eclipse Juno

I faced this issue several times. As described by Ashutosh Jindal, if the Hyperlinking is already enabled and still the ctrl+click doesn't work then you need to:

  1. Navigate to Java -> Editor -> Mark Occurrences in Preferences
  2. Uncheck "Mark occurrences of the selected element in the current file" if its already checked.
  3. Now, check on the above mentioned option and then check on all the items under it. Click Apply.

This should now enabled the ctrl+click functionality.

FirstOrDefault returns NullReferenceException if no match is found

FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null. Thats the reason for the exception.

So you just have to check for null first:

string displayName = null;
var keyValue = Dictionary
    .FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue  != null)
{
    displayName = keyValue.Value.DisplayName;
} 

But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue> is used to find a value by the key. Maybe you should refactor it.

Another option is to provide a default value with DefaultIfEmpty:

string displayName = Dictionary
    .Where(kv => kv.Value.ID == long.Parse(options.ID))
    .Select(kv => kv.Value.DisplayName)   // not a problem even if no item matches
    .DefaultIfEmpty("--Option unknown--") // or no argument -> null
    .First();                             // cannot cause an exception

Rounding up to next power of 2

Despite the question is tagged as c here my five cents. Lucky us, C++ 20 would include std::ceil2 and std::floor2 (see here). It is consexpr template functions, current GCC implementation uses bitshifting and works with any integral unsigned type.

Delete empty rows

To delete rows empty in table

syntax:

DELETE FROM table_name 
WHERE column_name IS NULL;

example:

Table name: data ---> column name: pkdno

DELETE FROM data 
WHERE pkdno IS NULL;

Answer: 5 rows deleted. (sayso)

Generate SQL Create Scripts for existing tables with Query

Lone time lurker, first time poster...

Expanding on @Devart and @ildanny solutions...

I had the need to run this for ALL tables in a db and also to execute the code against Linked Servers.

All tables...

/*
Ex. 
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'All', 0, NULL;
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'dbo', 0, NULL;
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'All', 1, '{linkedservername}';
*/
CREATE PROCEDURE etl.GetTableDefinitions
(
  @SystemName NVARCHAR(128)
, @DatabaseName NVARCHAR(128)
, @SchemaName NVARCHAR(128)
, @linkedserver BIT
, @linkedservername NVARCHAR(128)
)

AS

DECLARE @sql NVARCHAR(MAX) = N'';
DECLARE @sql1 NVARCHAR(MAX) = N'';
DECLARE @inSchemaName NVARCHAR(MAX) = N'';

SELECT @inSchemaName = CASE WHEN @SchemaName = N'All' THEN N's.[name]' ELSE '''' + @SchemaName + '''' END;

IF @linkedserver = 0
BEGIN

SELECT @sql = N'
SET NOCOUNT ON;

--- options ---
DECLARE @UseTransaction BIT = 0; 
DECLARE @GenerateUseDatabase BIT = 0;
DECLARE @GenerateFKs BIT = 0;
DECLARE @GenerateIdentity BIT = 1;
DECLARE @GenerateCollation BIT = 0;
DECLARE @GenerateCreateTable BIT = 1;
DECLARE @GenerateIndexes BIT = 0;
DECLARE @GenerateConstraints BIT = 1;
DECLARE @GenerateKeyConstraints BIT = 1;
DECLARE @GenerateConstraintNameOfDefaults BIT = 1;
DECLARE @GenerateDropIfItExists BIT = 0;
DECLARE @GenerateDropFKIfItExists BIT = 0;
DECLARE @GenerateDelete BIT = 0;
DECLARE @GenerateInsertInto BIT = 0;
DECLARE @GenerateIdentityInsert INT = 0; --0 ignore set,but add column; 1 generate; 2 ignore set AND column
DECLARE @GenerateSetNoCount INT = 0; --0 ignore set,1=set on, 2=set off 
DECLARE @GenerateMessages BIT = 0; --print with no wait
DECLARE @GenerateDataCompressionOptions BIT = 0; --TODO: generates the compression option only of the TABLE, not the indexes
                                                    --NB: the compression options reflects the design VALUE.
                                                    --The actual compression of a the page is saved here
--- variables ---
DECLARE @DataTypeSpacer INT = 1; --this is just to improve the formatting of the script ...
DECLARE @name SYSNAME;
DECLARE @sql NVARCHAR(MAX) = N'''';
DECLARE @int INT = 1;
DECLARE @maxint INT;
DECLARE @SourceDatabase NVARCHAR(MAX) = N''' + @DatabaseName + '''; --this is used by the INSERT 
DECLARE @TargetDatabase NVARCHAR(MAX) = N''' + @DatabaseName + '''; --this is used by the INSERT AND USE <DBName>
DECLARE @cr NVARCHAR(20) = NCHAR(13);
DECLARE @tab NVARCHAR(20) = NCHAR(9);

DECLARE @Tables TABLE
(
      id INT IDENTITY(1,1)
    , [name] SYSNAME
    , [object_id] INT 
    , [database_id] SMALLINT
);

BEGIN 

    INSERT INTO @Tables([name], [object_id], [database_id])
    SELECT s.[name] + N''.'' + t.[name] AS [name]
        , t.[object_id]
        , DB_ID(''' + @DatabaseName + ''') AS [database_id]
    FROM [' + @DatabaseName + '].sys.tables t
        JOIN [' + @DatabaseName + '].sys.schemas s ON t.[schema_id] = s.[schema_id]
    WHERE t.[name] NOT IN (''Tally'',''LOC_AND_SEG_CAP1'',''LOC_AND_SEG_CAP2'',''LOC_AND_SEG_CAP3'',''LOC_AND_SEG_CAP4'',''TableNames'')
        AND s.[name] = ' + @inSchemaName + '
    ORDER BY s.[name], t.[name];

    SELECT @maxint = COUNT(0) 
    FROM @Tables;

    WHILE @int <= @maxint
    BEGIN

        ;WITH 
        index_column AS 
        (
            SELECT ic.[object_id]
                , OBJECT_NAME(ic.[object_id], DB_ID(N''' + @DatabaseName + ''')) AS ObjectName
                , ic.index_id
                , ic.is_descending_key
                , ic.is_included_column
                , c.[name] 
            FROM [' + @DatabaseName + '].sys.index_columns ic WITH (NOLOCK)
                JOIN [' + @DatabaseName + '].sys.columns c WITH (NOLOCK) ON ic.[object_id] = c.[object_id] 
                    AND ic.column_id = c.column_id
                JOIN [' + @DatabaseName + '].sys.tables t ON c.[object_id] = t.[object_id]
        ) 
        , fk_columns AS 
        (
            SELECT k.constraint_object_id
                , cname = c.[name]
                , rcname = rc.[name]
            FROM [' + @DatabaseName + '].sys.foreign_key_columns k WITH (NOWAIT)
                JOIN [' + @DatabaseName + '].sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id 
                    AND rc.column_id = k.referenced_column_id 
                JOIN [' + @DatabaseName + '].sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id 
                    AND c.column_id = k.parent_column_id
                JOIN [' + @DatabaseName + '].sys.tables t ON c.[object_id] = t.[object_id]
            WHERE @GenerateFKs = 1
        )
        SELECT @sql = @sql +

            --------------------  USE DATABASE   --------------------------------------------------------------------------------------------------
                CAST(
                    CASE WHEN @GenerateUseDatabase = 1
                    THEN N''USE '' + @TargetDatabase + N'';'' + @cr
                    ELSE N'''' END 
                AS NVARCHAR(200))
                +
            --------------------  SET NOCOUNT   --------------------------------------------------------------------------------------------------
                CAST(
                    CASE @GenerateSetNoCount 
                    WHEN 1 THEN N''SET NOCOUNT ON;'' + @cr
                    WHEN 2 THEN N''SET NOCOUNT OFF;'' + @cr
                    ELSE N'''' END 
                AS NVARCHAR(MAX))
                +
            --------------------  USE TRANSACTION  --------------------------------------------------------------------------------------------------
                CAST(
                    CASE WHEN @UseTransaction = 1
                    THEN 
                        N''SET XACT_ABORT ON'' + @cr
                        + N''BEGIN TRY'' + @cr
                        + N''BEGIN TRAN'' + @cr
                    ELSE N'''' END 
                AS NVARCHAR(MAX))
                +
            --------------------  DROP SYNONYM   --------------------------------------------------------------------------------------------------
                CASE WHEN @GenerateDropIfItExists = 1
                THEN CAST(N''IF OBJECT_ID('''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''',''''SN'''') IS NOT NULL DROP SYNONYM '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr AS NVARCHAR(MAX))
                ELSE CAST(N'''' AS NVARCHAR(MAX))   END 
                +
            --------------------  DROP TABLE IF EXISTS --------------------------------------------------------------------------------------------------
                CASE WHEN @GenerateDropIfItExists = 1
                THEN 
                    --Drop TABLE if EXISTS
                    CAST(N''IF OBJECT_ID('''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''',''''U'''') IS NOT NULL DROP TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr AS NVARCHAR(MAX))
                    + @cr
                ELSE N'''' END 
                +
            --------------------  DROP CONSTRAINT IF EXISTS --------------------------------------------------------------------------------------------------
                CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDropFKIfItExists = 1 THEN 
                    N''RAISERROR(''''DROP CONSTRAINTS OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr            
                ELSE N'''' END) AS NVARCHAR(MAX)) 
                +
                CASE WHEN @GenerateDropFKIfItExists = 1
                THEN 
                    --Drop foreign keys
                    ISNULL(((
                        SELECT 
                            CAST(
                                N''ALTER TABLE '' + QUOTENAME(s.[name]) + N''.'' + QUOTENAME(t.[name]) + N'' DROP CONSTRAINT '' + RTRIM(f.[name]) + N'';'' + @cr
                            AS NVARCHAR(MAX))
                        FROM [' + @DatabaseName + '].sys.tables t
                            INNER JOIN [' + @DatabaseName + '].sys.foreign_keys f ON f.parent_object_id = t.[object_id]
                            INNER JOIN [' + @DatabaseName + '].sys.schemas s ON s.[schema_id] = f.[schema_id]
                        WHERE f.referenced_object_id = t.[object_id]
                        FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''))
                    , N'''') + @cr
                ELSE N'''' END 
            +
            --------------------- CREATE TABLE -----------------------------------------------------------------------------------------------------------------
            CAST((CASE WHEN @GenerateMessages = 1 THEN 
                N''RAISERROR(''''CREATE TABLE %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr           
            ELSE CAST(N'''' AS NVARCHAR(MAX)) END) AS NVARCHAR(MAX)) 
            +
            CASE WHEN @GenerateCreateTable = 1 THEN 
                CAST(
                    N''CREATE TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + @cr + N''('' + @cr + STUFF((
                    SELECT 
                        CAST(
                            @tab + N'','' + QUOTENAME(c.[name]) + N'' '' + ISNULL(REPLICATE('' '',@DataTypeSpacer - LEN(QUOTENAME(c.[name]))),'''') 
                            +  
                            CASE WHEN c.is_computed = 1
                                THEN N'' AS '' + cc.[definition] 
                                ELSE UPPER(tp.[name]) + 
                                    CASE WHEN tp.[name] IN (N''varchar'', N''char'', N''varbinary'', N''binary'', N''text'')
                                            THEN N''('' + CASE WHEN c.max_length = -1 THEN N''MAX'' ELSE CAST(c.max_length AS NVARCHAR(5)) END + N'')''
                                            WHEN tp.[name] IN (N''NVARCHAR'', N''nchar'', N''ntext'')
                                            THEN N''('' + CASE WHEN c.max_length = -1 THEN N''MAX'' ELSE CAST(c.max_length / 2 AS NVARCHAR(5)) END + N'')''
                                            WHEN tp.[name] IN (N''datetime2'', N''time2'', N''datetimeoffset'') 
                                            THEN N''('' + CAST(c.scale AS NVARCHAR(5)) + N'')''
                                            WHEN tp.[name] = N''decimal'' 
                                            THEN N''('' + CAST(c.[precision] AS NVARCHAR(5)) + N'','' + CAST(c.scale AS NVARCHAR(5)) + N'')''
                                        ELSE N''''
                                    END +
                                    CASE WHEN c.collation_name IS NOT NULL AND @GenerateCollation = 1 THEN N'' COLLATE '' + c.collation_name ELSE N'''' END +
                                    CASE WHEN c.is_nullable = 1 THEN N'' NULL'' ELSE N'' NOT NULL'' END +
                                    CASE WHEN dc.[definition] IS NOT NULL THEN CASE WHEN @GenerateConstraintNameOfDefaults = 1 THEN N'' CONSTRAINT '' + QUOTENAME(dc.[name]) ELSE N'''' END + N'' DEFAULT'' + dc.[definition] ELSE N'''' END + 
                                    CASE WHEN ic.is_identity = 1 AND @GenerateIdentity = 1 THEN N'' IDENTITY('' + CAST(ISNULL(ic.seed_value, N''0'') AS NCHAR(1)) + N'','' + CAST(ISNULL(ic.increment_value, N''1'') AS NCHAR(1)) + N'')'' ELSE N'''' END 
                            END + @cr
                        AS NVARCHAR(MAX)) 
                    FROM [' + @DatabaseName + '].sys.columns c WITH (NOWAIT)
                        INNER JOIN [' + @DatabaseName + '].sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
                        LEFT JOIN [' + @DatabaseName + '].sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] 
                            AND c.column_id = cc.column_id
                        LEFT JOIN [' + @DatabaseName + '].sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 
                            AND c.[object_id] = dc.parent_object_id 
                            AND c.column_id = dc.parent_column_id
                        LEFT JOIN [' + @DatabaseName + '].sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 
                            AND c.[object_id] = ic.[object_id] 
                            AND c.column_id = ic.column_id
                    WHERE c.[object_id] = t.[object_id]
                    ORDER BY c.column_id
                    FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, @tab + N'' '') AS NVARCHAR(MAX))
            ELSE CAST(N'''' AS NVARCHAR(MAX)) END 
            + 
            ---------------------- Key Constraints ----------------------------------------------------------------
            CAST(
                CASE WHEN @GenerateKeyConstraints <> 1 THEN N'''' 
                ELSE 
                    ISNULL((SELECT @tab + N'', CONSTRAINT '' + QUOTENAME(k.[name]) + N'' PRIMARY KEY '' + ISNULL(kidx.[type_desc], N'''') + N''('' + 
                                (SELECT STUFF((
                                    SELECT N'', '' + QUOTENAME(c.[name]) + N'' '' + CASE WHEN ic.is_descending_key = 1 THEN N''DESC'' ELSE N''ASC'' END
                                    FROM [' + @DatabaseName + '].sys.index_columns ic WITH (NOWAIT)
                                        JOIN [' + @DatabaseName + '].sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] 
                                            AND c.column_id = ic.column_id
                                    WHERE ic.is_included_column = 0
                                        AND ic.[object_id] = k.parent_object_id 
                                        AND ic.index_id = k.unique_index_id     
                                    FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N''''))
                        + N'')'' + @cr
                        FROM [' + @DatabaseName + '].sys.key_constraints k WITH (NOWAIT) 
                            LEFT JOIN [' + @DatabaseName + '].sys.indexes kidx ON k.parent_object_id = kidx.[object_id] 
                                AND k.unique_index_id = kidx.index_id
                        WHERE k.parent_object_id = t.[object_id] 
                            AND k.[type] = N''PK''), N'''') + N'')''  + @cr
                END 
            AS NVARCHAR(MAX))
            +
            CAST(
            CASE 
                WHEN @GenerateDataCompressionOptions = 1 AND (SELECT TOP 1 data_compression_desc FROM [' + @DatabaseName + '].sys.partitions WHERE OBJECT_ID = t.[object_id] AND index_id = 1) <> N''NONE''
                THEN N''WITH (DATA_COMPRESSION='' + (SELECT TOP 1 data_compression_desc FROM [' + @DatabaseName + '].sys.partitions WHERE OBJECT_ID = t.[object_id] AND index_id = 1) + N'')'' + @cr
                ELSE N'''' + @cr
            END AS NVARCHAR(MAX))
            + 
            --------------------- FOREIGN KEYS -----------------------------------------------------------------------------------------------------------------
            CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDropFKIfItExists = 1 THEN 
                N''RAISERROR(''''CREATING FK OF  %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr            
            ELSE N'''' END) AS NVARCHAR(MAX)) 
            +
            CAST(
                ISNULL((SELECT (
                    SELECT @cr +
                    N''ALTER TABLE '' +  QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) +  N'' WITH'' 
                    + CASE WHEN fk.is_not_trusted = 1 
                        THEN N'' NOCHECK'' 
                        ELSE N'' CHECK'' 
                    END + 
                    N'' ADD CONSTRAINT '' + QUOTENAME(fk.[name])  + N'' FOREIGN KEY('' 
                    + STUFF((
                        SELECT N'', '' + QUOTENAME(k.cname) + N''''
                        FROM fk_columns k
                        WHERE k.constraint_object_id = fk.[object_id]
                            AND fk.[object_id] = t.[object_id]
                        FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''')
                    + N'')'' +
                    N'' REFERENCES '' + QUOTENAME(SCHEMA_NAME(ro.[schema_id])) + N''.'' + QUOTENAME(ro.[name]) + N'' (''
                    + STUFF((
                        SELECT N'', '' + QUOTENAME(k.rcname) + N''''
                        FROM fk_columns k
                        WHERE k.constraint_object_id = fk.[object_id]
                            AND fk.[object_id] = t.[object_id]
                        FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''')
                    + N'')''
                    + CASE 
                        WHEN fk.delete_referential_action = 1 THEN N'' ON DELETE CASCADE'' 
                        WHEN fk.delete_referential_action = 2 THEN N'' ON DELETE SET NULL''
                        WHEN fk.delete_referential_action = 3 THEN N'' ON DELETE SET DEFAULT'' 
                        ELSE N'''' 
                    END
                    + CASE 
                        WHEN fk.update_referential_action = 1 THEN N'' ON UPDATE CASCADE''
                        WHEN fk.update_referential_action = 2 THEN N'' ON UPDATE SET NULL''
                        WHEN fk.update_referential_action = 3 THEN N'' ON UPDATE SET DEFAULT''  
                        ELSE N'''' 
                    END 
                    + @cr + N''ALTER TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' CHECK CONSTRAINT '' + QUOTENAME(fk.[name])  + N'''' + @cr
                FROM [' + @DatabaseName + '].sys.foreign_keys fk WITH (NOWAIT)
                    JOIN [' + @DatabaseName + '].sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
                WHERE fk.parent_object_id = t.[object_id]
                FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')), N'''')
            AS NVARCHAR(MAX))
            + 
            --------------------- INDEXES ----------------------------------------------------------------------------------------------------------
            CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateIndexes = 1 THEN 
                N''RAISERROR(''''CREATING INDEXES OF  %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr           
            ELSE N'''' END) AS NVARCHAR(MAX)) 
            +
            CASE WHEN @GenerateIndexes = 1 THEN 
                CAST(
                    ISNULL(((SELECT
                        @cr + N''CREATE'' + CASE WHEN i.is_unique = 1 THEN N'' UNIQUE '' ELSE N'' '' END 
                                + i.[type_desc] + N'' INDEX '' + QUOTENAME(i.[name]) + N'' ON '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' ('' +
                                STUFF((
                                SELECT N'', '' + QUOTENAME(c.[name]) + N'''' + CASE WHEN c.is_descending_key = 1 THEN N'' DESC'' ELSE N'' ASC'' END
                                FROM index_column c
                                WHERE c.is_included_column = 0
                                    AND c.[object_id] = t.[object_id]
                                    AND c.index_id = i.index_id
                                FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''') + N'')''  
                                + ISNULL(@cr + N''INCLUDE ('' + 
                                    STUFF((
                                    SELECT N'', '' + QUOTENAME(c.[name]) + N''''
                                    FROM index_column c
                                    WHERE c.is_included_column = 1
                                        AND c.[object_id] = t.[object_id]
                                        AND c.index_id = i.index_id
                                    FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''') + N'')'', N'''')  + @cr
                        FROM [' + @DatabaseName + '].sys.indexes i WITH (NOWAIT)
                        WHERE i.[object_id] = t.[object_id]
                            AND i.is_primary_key = 0
                            AND i.[type] in (1,2)
                            AND @GenerateIndexes = 1
                        FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
                    ), N'''')
                AS NVARCHAR(MAX))
            ELSE N'''' END 
            +
            ------------------------  @GenerateDelete     ----------------------------------------------------------
            CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDelete = 1 THEN 
                N''RAISERROR(''''TRUNCATING  %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr            
            ELSE N'''' END) AS NVARCHAR(MAX)) 
            +
            CASE WHEN @GenerateDelete = 1 THEN
                CAST(
                    (CASE WHEN EXISTS (SELECT TOP 1 [name] FROM [' + @DatabaseName + '].sys.foreign_keys WHERE referenced_object_id = t.[object_id]) THEN 
                        N''DELETE FROM '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr
                    ELSE
                        N''TRUNCATE TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + @cr
                    END)
                AS NVARCHAR(MAX))
            ELSE N'''' END 
            +
            ------------------------- @GenerateInsertInto ----------------------------------------------------------
            CAST((CASE WHEN @GenerateMessages = 1 AND @GenerateDropFKIfItExists = 1 THEN 
                N''RAISERROR(''''INSERTING INTO  %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + @cr            
            ELSE N'''' END) AS NVARCHAR(MAX)) 
            +
            CASE WHEN @GenerateInsertInto = 1
            THEN 
                CAST(
                        CASE WHEN EXISTS (SELECT TOP 1 c.[name] FROM [' + @DatabaseName + '].sys.columns c WHERE c.[object_id] = t.[object_id] AND c.is_identity = 1) AND @GenerateIdentityInsert = 1 THEN 
                            N''SET IDENTITY_INSERT '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' ON;'' + @cr
                        ELSE N'''' END 
                        +
                        N''INSERT INTO '' + QUOTENAME(@TargetDatabase) + N''.'' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N''('' 
                        + @cr
                        +
                        (
                            @tab + N'' '' + SUBSTRING(
                                (
                                SELECT @tab + '',''+ QUOTENAME(c.[name]) + @cr 
                                FROM [' + @DatabaseName + '].sys.columns c 
                                WHERE c.[object_id] = t.[object_id] 
                                    AND c.system_type_ID <> 189 /*timestamp*/ 
                                    AND c.is_computed = 0
                                    AND (c.is_identity = 0 or @GenerateIdentityInsert in (0,1))
                                FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
                            ,3,99999)

                        )
                        + N'')'' + @cr + N''SELECT '' 
                        + @cr
                        +
                        (
                            @tab + N'' '' + SUBSTRING(
                                (
                                SELECT @tab + '',''+ QUOTENAME(c.[name]) + @cr 
                                FROM [' + @DatabaseName + '].sys.columns c 
                                WHERE c.[object_id] = t.[object_id] 
                                    AND c.system_type_ID <> 189 /*timestamp*/ 
                                    AND c.is_computed = 0                     
                                    AND (c.is_identity = 0 or @GenerateIdentityInsert  in (0,1))
                                FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
                            ,3,99999)
                        )
                        + N''FROM '' + @SourceDatabase +  N''.'' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id]))            
                        + N'';'' + @cr
                        + CASE WHEN EXISTS (SELECT TOP 1 c.[name] FROM [' + @DatabaseName + '].sys.columns c WHERE c.[object_id] = t.[object_id] AND c.is_identity = 1) AND @GenerateIdentityInsert = 1 THEN 
                            N''SET IDENTITY_INSERT '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' OFF;''+ @cr
                        ELSE N'''' END              
                AS NVARCHAR(MAX))
            ELSE N'''' END 
            +
            --------------------  USE TRANSACTION  --------------------------------------------------------------------------------------------------
            CAST(
                CASE WHEN @UseTransaction = 1
                THEN 
                    @cr + N''COMMIT TRAN; ''
                    + @cr + N''END TRY''
                    + @cr + N''BEGIN CATCH''
                    + @cr + N''  IF XACT_STATE() IN (-1,1)''
                    + @cr + N''      ROLLBACK TRAN;''
                    + @cr + N''''
                    + @cr + N''  SELECT   ERROR_NUMBER() AS ErrorNumber  ''
                    + @cr + N''          ,ERROR_SEVERITY() AS ErrorSeverity  ''
                    + @cr + N''          ,ERROR_STATE() AS ErrorState  ''
                    + @cr + N''          ,ERROR_PROCEDURE() AS ErrorProcedure  ''
                    + @cr + N''          ,ERROR_LINE() AS ErrorLine  ''
                    + @cr + N''          ,ERROR_MESSAGE() AS ErrorMessage; ''
                    + @cr + N''END CATCH''
                ELSE N'''' END 
            AS NVARCHAR(700))
        FROM @Tables t
        WHERE ID = @int
        ORDER BY [name]; 
    
        SET @int = @int + 1;
    
    END

    EXEC [master].dbo.PrintMax @sql;
/* see below for PrintMax code*/

END'

EXEC (@sql);

END
ELSE

And the Linked Server bit...

BEGIN

SELECT @sql = N'EXECUTE (''
SET NOCOUNT ON;
BEGIN

... Same code but be sure to double up on your single quotes

END

... code for the printmax proc (not mine, @Ben B) because it may not exist at destination server

    DECLARE @CurrentEnd BIGINT; /* track the length of the next substring */
    DECLARE @offset TINYINT; /*tracks the amount of offset needed */
    DECLARE @String NVARCHAR(MAX);
    SET @String = REPLACE(REPLACE(@sql, CHAR(13) + CHAR(10), CHAR(10)), CHAR(13), CHAR(10))

    WHILE LEN(@String) > 1
    BEGIN
        IF CHARINDEX(CHAR(10), @String) BETWEEN 1 AND 4000
        BEGIN
            SET @CurrentEnd = CHARINDEX(CHAR(10), @String) -1
            SET @offset = 2
        END
        ELSE
        BEGIN
            SET @CurrentEnd = 4000
            SET @offset = 1
        END   
        PRINT SUBSTRING(@String, 1, @CurrentEnd) 
        SET @String = SUBSTRING(@String, @CurrentEnd + @offset, LEN(@String))   
    END

END'') AT [' + @linkedservername + ']';

EXEC (@sql);

END

Ben B solution

How to convert string to double with proper cultureinfo

You need to define a single locale that you will use for the data stored in the database, the invariant culture is there for exactly this purpose.

When you display convert to the native type and then format for the user's culture.

E.g. to display:

string fromDb = "123.56";
string display = double.Parse(fromDb, CultureInfo.InvariantCulture).ToString(userCulture);

to store:

string fromUser = "132,56";
double value;
// Probably want to use a more specific NumberStyles selection here.
if (!double.TryParse(fromUser, NumberStyles.Any, userCulture, out value)) {
  // Error...
}
string forDB = value.ToString(CultureInfo.InvariantCulture);

PS. It, almost, goes without saying that using a column with a datatype that matches the data would be even better (but sometimes legacy applies).

How do I remove the title bar from my app?

Go to styles.xml and change .DarkActionBar for .NoActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
</style>

becomes

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
</style>

if colors are irrelevant to your app, you can actually go for

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

How to get option text value using AngularJS?

<div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
      <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
    </select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>

AngularJS:

angular.module('ngrepeatSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    model: null,
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ]
   };
}]);

taken from AngularJS docs

How to make an empty div take space

  works but that is not right way I think the w min-height: 1px;

How to add a progress bar to a shell script?

I would also like to contribute my own progress bar

It achieves sub-character precision by using Half unicode blocks

enter image description here

Code is included

How to fix warning from date() in PHP"

You need to set the default timezone smth like this :

date_default_timezone_set('Europe/Bucharest');

More info about this in http://php.net/manual/en/function.date-default-timezone-set.php

Or you could use @ in front of date to suppress the warning however as the warning states it's not safe to rely on the servers default timezone

ng-if check if array is empty

Verify the length property of the array to be greater than 0:

<p ng-if="post.capabilities.items.length > 0">
   <strong>Topics</strong>: 
   <span ng-repeat="topic in post.capabilities.items">
     {{topic.name}}
   </span>
</p>

Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items"> evaluates always to true, even if the array is empty.

Spring MVC: How to perform validation?

Find complete example of Spring Mvc Validation

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.technicalkeeda.bean.Login;

public class LoginValidator implements Validator {
    public boolean supports(Class aClass) {
        return Login.class.equals(aClass);
    }

    public void validate(Object obj, Errors errors) {
        Login login = (Login) obj;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
                "username.required", "Required field");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPassword",
                "userpassword.required", "Required field");
    }
}


public class LoginController extends SimpleFormController {
    private LoginService loginService;

    public LoginController() {
        setCommandClass(Login.class);
        setCommandName("login");
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Override
    protected ModelAndView onSubmit(Object command) throws Exception {
        Login login = (Login) command;
        loginService.add(login);
        return new ModelAndView("loginsucess", "login", login);
    }
}

How can I create a progress bar in Excel VBA?

I liked the Status Bar from this page:

https://wellsr.com/vba/2017/excel/vba-application-statusbar-to-mark-progress/

I updated it so it could be used as a called procedure. No credit to me.


showStatus Current, Total, "  Process Running: "

Private Sub showStatus(Current As Integer, lastrow As Integer, Topic As String)
Dim NumberOfBars As Integer
Dim pctDone As Integer

NumberOfBars = 50
'Application.StatusBar = "[" & Space(NumberOfBars) & "]"


' Display and update Status Bar
    CurrentStatus = Int((Current / lastrow) * NumberOfBars)
    pctDone = Round(CurrentStatus / NumberOfBars * 100, 0)
    Application.StatusBar = Topic & " [" & String(CurrentStatus, "|") & _
                            Space(NumberOfBars - CurrentStatus) & "]" & _
                            " " & pctDone & "% Complete"

' Clear the Status Bar when you're done
'    If Current = Total Then Application.StatusBar = ""

End Sub

enter image description here

Ansible date variable

I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.

For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.

Below is the variable I set in my playbook:

  vars:
    cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"

That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.

'ng' is not recognized as an internal or external command, operable program or batch file

No need to uninstall angular/cli.

  1. You just need to make sure the PATH to npm is in your environment PATH and at the top.

C:\Users\yourusername\AppData\Roaming\npm

  1. Then close whatever git or command client your using and run ng-v again and should work

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

How to pass boolean parameter value in pipeline to downstream jobs?

Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Swift 4

let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
collectionViewLayout?.sectionInset = UIEdgeInsetsMake(0, 20, 0, 40) 
collectionViewLayout?.invalidateLayout()

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Integrated Security = False : User ID and Password are specified in the connection. Integrated Security = true : the current Windows account credentials are used for authentication.

Integrated Security = SSPI : this is equivalant to true.

We can avoid the username and password attributes from the connection string and use the Integrated Security

C# string does not contain possible?

This should do the trick for you.

For one word:

if (!string.Contains("One"))

For two words:

if (!(string.Contains("One") && string.Contains("Two")))

change PATH permanently on Ubuntu

Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/play.sh (and possibly play.csh, etc):

PATH=$PATH:/home/me/play
export PATH

Why is pydot unable to find GraphViz's executables in Windows 8?

For me: (Win10, Anaconda3) Make sure you have done "conda install graphviz"

I have to add to the PATH: C:\Users\username\Anaconda3\Library\bin\graphviz

To modify PATH go to Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit > New

MAKE SURE TO RESTART YOUR IDE AFTER THIS. It should work

JavaScript: Object Rename Key

I would like just using the ES6(ES2015) way!

we need keeping up with the times!

_x000D_
_x000D_
const old_obj = {_x000D_
    k1: `111`,_x000D_
    k2: `222`,_x000D_
    k3: `333`_x000D_
};_x000D_
console.log(`old_obj =\n`, old_obj);_x000D_
// {k1: "111", k2: "222", k3: "333"}_x000D_
_x000D_
_x000D_
/**_x000D_
 * @author xgqfrms_x000D_
 * @description ES6 ...spread & Destructuring Assignment_x000D_
 */_x000D_
_x000D_
const {_x000D_
    k1: kA, _x000D_
    k2: kB, _x000D_
    k3: kC,_x000D_
} = {...old_obj}_x000D_
_x000D_
console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`);_x000D_
// kA = 111, kB = 222, kC = 333_x000D_
_x000D_
const new_obj = Object.assign(_x000D_
    {},_x000D_
    {_x000D_
        kA,_x000D_
        kB,_x000D_
        kC_x000D_
    }_x000D_
);_x000D_
_x000D_
console.log(`new_obj =\n`, new_obj);_x000D_
// {kA: "111", kB: "222", kC: "333"}
_x000D_
_x000D_
_x000D_

demo screen shortcut

How to change indentation mode in Atom?

When Atom auto-indent-detection got it hopelessly wrong and refused to let me type a literal Tab character, I eventually found the 'Force-Tab' extension - which gave me back control. I wanted to keep shift-tab for outdenting, so set ctrl-tab to insert a hard tab. In my keymap I added:

'atom-text-editor': 'ctrl-tab': 'force-tab:insert-actual-tab'

Creating a zero-filled pandas data frame

If you would like the new data frame to have the same index and columns as an existing data frame, you can just multiply the existing data frame by zero:

df_zeros = df * 0

How to see indexes for a database or table in MySQL?

This works in my case for getting table name and column name in the corresponding table for indexed fields.

SELECT TABLE_NAME , COLUMN_NAME, COMMENT 
FROM information_schema.statistics
WHERE table_schema = 'database_name';

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How to initialize an array in one step using Ruby?

You can simply do this with %w notation in ruby arrays.

array = %w(1 2 3)

It will add the array values 1,2,3 to the arrayand print out the output as ["1", "2", "3"]

What is the correct way to declare a boolean variable in Java?

You don't have to, but some people like to explicitly initialize all variables (I do too). Especially those who program in a variety of languages, it's just easier to have the rule of always initializing your variables rather than deciding case-by-case/language-by-language.

For instance Java has default values for Boolean, int etc .. C on the other hand doesn't automatically give initial values, whatever happens to be in memory is what you end up with unless you assign a value explicitly yourself.

In your case above, as you discovered, the code works just as well without the initialization, esp since the variable is set in the next line which makes it appear particularly redundant. Sometimes you can combine both of those lines (declaration and initialization - as shown in some of the other posts) and get the best of both approaches, i.e., initialize the your variable with the result of the email1.equals (email2); operation.

How to set time to a date object in java

I should like to contribute the modern answer. This involves using java.time, the modern Java date and time API, and not the old Date nor Calendar except where there’s no way to avoid it.

Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
    System.out.println(utcDateDime);

This prints

2018-02-27T00:00Z

Z means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date object for that, convert just before handing the Date on:

    Date oldfashionedDate = Date.from(utcDateDime.toInstant());
    System.out.println(oldfashionedDate);

On my computer this prints

Tue Feb 27 01:00:00 CET 2018

Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString() grabbing the JVMs time zone and using it for producing the string.

How can I set it to something like 5:30 pm?

To answer your direct question directly, if you have a ZonedDateTime, OffsetDateTime or LocalDateTime, in all of these cases the following will accomplish what you asked for:

    yourDateTime = yourDateTime.with(LocalTime.of(17, 30));

If yourDateTime was a LocalDateTime of 2018-02-27T00:00, it will now be 2018-02-27T17:30. Similarly for the other types, only they include offset and time zone too as appropriate.

If you only had a date, as in the first snippet above, you can also add time-of-day information to it:

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));

For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example

    ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
            .atZone(ZoneId.of("Asia/Kolkata"));

This yields 2018-02-27T17:30+05:30[Asia/Kolkata].

Date and Calendar vs java.time

The Date class that you use as well as Calendar and SimpleDateFormat used in the other answers are long outdated, and SimpleDateFormat in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.

Link: Oracle Tutorial Date Time, explaining how to use java.time.

Where's the DateTime 'Z' format specifier?

When you use DateTime you are able to store a date and a time inside a variable.

The date can be a local time or a UTC time, it depend on you.

For example, I'm in Italy (+2 UTC)

var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00
var dt2 = dt1.ToUniversalTime()  // store 2011-06-27 10:00:00

So, what happen when I print dt1 and dt2 including the timezone?

dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 12:00:00 +2

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 10:00:00 +2

dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset.

So where the "+2" come from if it's not contained in the dt1 and dt2 variable?

It come from your machine clock setting.

The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + "TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type) and it will use the offset of the server machine that it's executing the code.

The compiler tell you "Warning: the output of your code is dependent on the machine clock offset"

If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "+2" it will write "+1"

...
dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 12:00:00 +1

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 10:00:00 +1

The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version

symbol(s) not found for architecture i386

I've been stumped by this one before only to realize I added a data-only @interface and forgot to add the empty @implementation block.

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = str_replace(' ', '_', $journalName);

to remove white space

Create a remote branch on GitHub

Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.

 1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
 2. $ git branch <new_branch> (creates new branch)
 3. $ git checkout new_branch
 4. $ git add . (After making changes in the current branch)
 5. $ git commit -m "type commit msg here"
 6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
 7. $ git merge new_branch (starts merging)
 8. $ git push origin master (push to the remote server)

I referred this blog and I found it to be a cleaner approach.

How can I set multiple CSS styles in JavaScript?

Make a function to take care of it, and pass it parameters with the styles you want changed..

function setStyle( objId, propertyObject )
{
 var elem = document.getElementById(objId);
 for (var property in propertyObject)
    elem.style[property] = propertyObject[property];
}

and call it like this

setStyle('myElement', {'fontsize':'12px', 'left':'200px'});

for the values of the properties inside the propertyObject you can use variables..

SQL Server: Database stuck in "Restoring" state

I had the same issue... although I do not know why my database experienced this problem as my drive was not full... It's like it got corrupted or something. I tried all of the above none of them fully worked, I especially thought the suggestion to stop the service and deleting the mdf and ldf files would work... but it still froze up on restore?

I ended up resolving this by deleting the files as mentioned but instead of trying to restore the DB again I copied over fresh .mdf and .ldf files and Attached these using the Front End Attachment wizard. Relief, it worked!!

It took FOREVER to copy over the new files as I am using a Virtual Machine... so copying and pasting using the clipboard took like an hour itself so I would only recommend this as a last attempt.

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

How to apply slide animation between two activities in Android?

Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.

Slide animations can be slid right, slide left, slide up and slide down.

Slide up

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:toXScale="1.0"
        android:toYScale="0.0" />
</set>

Slide down

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:duration="800"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />
</set>

overridePendingTransition(R.anim.slide_down, R.anim.slide_up);

See activity transition animation examples for more activity transition examples.

How to get a tab character?

Tab is [HT], or character number 9, in the unicode library.

What is the difference between an expression and a statement in Python?

Statements before could change the state of our Python program: create or update variables, define function, etc.

And expressions just return some value can't change the global state or local state in a function.

But now we got :=, it's an alien!

How to check if a process is in hang state (Linux)

Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.

Composer: The requested PHP extension ext-intl * is missing from your system

I have solved this problem by adding --ignore-platform-reqs command with composer install in ubuntu.

composer install --ignore-platform-reqs

Single quotes vs. double quotes in C or C++

In C & C++ single quotes is known as a character ('a') whereas double quotes is know as a string ("Hello"). The difference is that a character can store anything but only one alphabet/number etc. A string can store anything. But also remember that there is a difference between '1' and 1. If you type cout<<'1'<<endl<<1; The output would be the same, but not in this case:

cout<<int('1')<<endl<<int(1);

This time the first line would be 48. As when you convert a character to an int it converts to its ascii and the ascii for '1' is 48. Same, if you do:

string s="Hi";
s+=48; //This will add "1" to the string
s+="1"; This will also add "1" to the string

How do you count the number of occurrences of a certain substring in a SQL varchar?

Perhaps you should not store data that way. It is a bad practice to ever store a comma delimited list in a field. IT is very inefficient for querying. This should be a related table.

jQuery Set Cursor Position in Text Area

Here's a jQuery solution:

$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

With this, you can do

$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

Solution -

1) Upgrade your Selenium Server i.e. selenium jar "selenium-server-standalone-2.xx.x.JAR" TO "selenium-server-standalone-2.45.0.JAR"

2) Upgrade your Selenium Client Driver i.e. selenium libs folder "selenium-java-2.xx.x" TO "selenium-java-2.45.0"

3) Check and Install compatible Firefox version

Refer - Download updated selenium libs & jar i.e. Version 2.45.0

This will RESOLVE your problem.. Cheers !!

PostgreSQL query to list all table names?

select 
 relname as table 
from 
 pg_stat_user_tables 
where schemaname = 'public'

select 
  tablename as table 
from 
  pg_tables  
where schemaname = 'public'

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

Jquery button click() function is not working

The click event is not bound to your new element, use a jQuery.on to handle the click.

EditorFor() and html properties

This is the cleanest and most elegant/simple way to get a solution here.

Brilliant blog post and no messy overkill in writing custom extension/helper methods like a mad professor.

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

try to do the following:

  1. Make sure Office interop assemblies are installed.
  2. Check the version of the assemblies on development and production.
  3. Create Desktop folder under systemprofile.
  4. set the DCOM security explicitly for the service user.

you can find more details here

No templates in Visual Studio 2017

In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.

When running the Team Explorer version, only the Blank Solution option was available.

The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"

Once I launched the correct EXE, Visual Studio started working as expected.

The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

If you have installed WAMP on your machine, please make sure that it is running. Do not EXIT the WAMP from tray menu since it will stop the MySQL Server.

Finding first blank row, then writing to it

ActiveSheet.Range("A10000").End(xlup).offset(1,0).Select

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

Dictionary returning a default value if the key does not exist

TryGetValue will already assign the default value for the type to the dictionary, so you can just use:

dictionary.TryGetValue(key, out value);

and just ignore the return value. However, that really will just return default(TValue), not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, 
     TKey key,
     TValue defaultValue)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     Func<TValue> defaultValueProvider)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value
         : defaultValueProvider();
}

(You may want to put argument checking in, of course :)

Remove trailing spaces automatically or with a shortcut

<Ctr>-<Shift>-<F> 

Format, does it as well.

This removes trailing whitespace and formats/indents your code.

Get names of all keys in the collection

You could do this with MapReduce:

mr = db.runCommand({
  "mapreduce" : "my_collection",
  "map" : function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce" : function(key, stuff) { return null; }, 
  "out": "my_collection" + "_keys"
})

Then run distinct on the resulting collection so as to find all the keys:

db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]

Browser detection in JavaScript?

Instead of hardcoding web browsers, you can scan the user agent to find the browser name:

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+/g)[0]

I've tested this on Safari, Chrome, and Firefox. Let me know if you found this doesn't work on a browser.

  • Safari: "Safari"
  • Chrome: "Chrome"
  • Firefox: "Firefox"

You can even modify this to get the browser version if you want. Do note there are better ways to get the browser version

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+\/[\d.]+/g)[0].split('/')

Sample output:

Firefox/39.0    

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Can pandas automatically recognize dates?

pandas read_csv method is great for parsing dates. Complete documentation at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html

you can even have the different date parts in different columns and pass the parameter:

parse_dates : boolean, list of ints or names, list of lists, or dict
If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a
separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date
column. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

The default sensing of dates works great, but it seems to be biased towards north american Date formats. If you live elsewhere you might occasionally be caught by the results. As far as I can remember 1/6/2000 means 6 January in the USA as opposed to 1 Jun where I live. It is smart enough to swing them around if dates like 23/6/2000 are used. Probably safer to stay with YYYYMMDD variations of date though. Apologies to pandas developers,here but i have not tested it with local dates recently.

you can use the date_parser parameter to pass a function to convert your format.

date_parser : function
Function to use for converting a sequence of string columns to an array of datetime
instances. The default uses dateutil.parser.parser to do the conversion.

Hive External Table Skip First Row

While you have your answer from Daniel, here are some customizations possible using OpenCSVSerde:

CREATE EXTERNAL TABLE `mydb`.`mytable`(
    `product_name` string,
    `brand_id` string,
    `brand` string,
    `color` string,
    `description` string,
    `sale_price` string)
PARTITIONED BY (
    `seller_id` string)
ROW FORMAT SERDE
    'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
    'separatorChar' = '\t',
    'quoteChar' = '"',
    'escapeChar' = '\\')
STORED AS INPUTFORMAT
    'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
    'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
    'hdfs://namenode.com:port/data/mydb/mytable'
TBLPROPERTIES (
    'serialization.null.format' = '',
    'skip.header.line.count' = '1')

With this, you have total control over the separator, quote character, escape character, null handling and header handling.

Look here and here.

selecting rows with id from another table

Try this (subquery):

SELECT * FROM terms WHERE id IN 
   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

When is JavaScript synchronous?

JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.

Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.

I would recommend you to give a look to the following article:

That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.

async

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

When considering what the computer actually does...

++x: load x from memory, increment, use, store back to memory.

x++: load x from memory, use, increment, store back to memory.

Consider: a = 0 x = f(a++) y = f(++a)

where function f(p) returns p + 1

x will be 1 (or 2)

y will be 2 (or 1)

And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.

Generally, just use x = x + 1. It's way simpler.

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Have you tried adding the semicolon to onclick="googleMapsQuery(422111);". I don't have enough of your code to test if the missing semicolon would cause the error, but ie is more picky about syntax.

Error renaming a column in MySQL

There is a syntax problem, because the right syntax to alter command is ALTER TABLE tablename CHANGE OldColumnName NewColunmName DATATYPE;

Deploy a project using Git push

In essence all you need to do are the following:

server = $1
branch = $2
git push $server $branch
ssh <username>@$server "cd /path/to/www; git pull"

I have those lines in my application as an executable called deploy.

so when I want to do a deploy I type ./deploy myserver mybranch.

Is there a way to get a list of column names in sqlite?

I like the answer by @thebeancounter, but prefer to parameterize the unknowns, the only problem being a vulnerability to exploits on the table name. If you're sure it's okay, then this works:

def get_col_names(cursor, tablename):
    """Get column names of a table, given its name and a cursor
       (or connection) to the database.
    """
    reader=cursor.execute("SELECT * FROM {}".format(tablename))
    return [x[0] for x in reader.description] 

If it's a problem, you could add code to sanitize the tablename.

How to get pandas.DataFrame columns containing specific dtype

There's a new feature in 0.14.1, select_dtypes to select columns by dtype, by providing a list of dtypes to include or exclude.

For example:

df = pd.DataFrame({'a': np.random.randn(1000),
                   'b': range(1000),
                   'c': ['a'] * 1000,
                   'd': pd.date_range('2000-1-1', periods=1000)})


df.select_dtypes(['float64','int64'])

Out[129]: 
            a    b
0    0.153070    0
1    0.887256    1
2   -1.456037    2
3   -1.147014    3
...

How to move columns in a MySQL table?

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

Capture HTML Canvas as gif/jpg/png/pdf?

If you are using jQuery, which quite a lot of people do, then you would implement the accepted answer like so:

var canvas = $("#mycanvas")[0];
var img = canvas.toDataURL("image/png");

$("#elememt-to-write-to").html('<img src="'+img+'"/>');

html select only one checkbox in a group

Necromancing:
And without jQuery, for a checkbox structure like this:

<label>
<input type="checkbox" id="mytrackers_1" name="blubb_1" value="">--- Bitte ausw&#228;hlen ---
</label>
<label>
<input type="checkbox" id="mytrackers_2" name="blubb_2" value="7">Testtracker
</label>
<label>
<input type="checkbox" id="mytrackers_3" name="blubb_3" value="3">Kundenanfrage
</label>
<label>
<input type="checkbox" id="mytrackers_4" name="blubb_4" value="2">Anpassung
</label>
<label>
<input type="checkbox" id="mytrackers_5" name="blubb_5" value="1" checked="checked" >Fehler
</label>
<label>
<input type="checkbox" id="mytrackers_6" name="blubb_6" value="4">Bedienung
</label>
<label>
<input type="checkbox" id="mytrackers_7" name="blubb_7" value="5">Internes
</label>
<label>
<input type="checkbox" id="mytrackers_8" name="blubb_8" value="6">&#196;nderungswunsch
</label>

you would do it like this:

    /// attach an event handler, now or in the future, 
    /// for all elements which match childselector,
    /// within the child tree of the element maching parentSelector.
    function subscribeEvent(parentSelector, eventName, childSelector, eventCallback) {
        if (parentSelector == null)
            throw new ReferenceError("Parameter parentSelector is NULL");
        if (childSelector == null)
            throw new ReferenceError("Parameter childSelector is NULL");
        // nodeToObserve: the node that will be observed for mutations
        var nodeToObserve = parentSelector;
        if (typeof (parentSelector) === 'string')
            nodeToObserve = document.querySelector(parentSelector);
        var eligibleChildren = nodeToObserve.querySelectorAll(childSelector);
        for (var i = 0; i < eligibleChildren.length; ++i) {
            eligibleChildren[i].addEventListener(eventName, eventCallback, false);
        } // Next i 
        // https://stackoverflow.com/questions/2712136/how-do-i-make-this-loop-all-children-recursively
        function allDescendants(node) {
            if (node == null)
                return;
            for (var i = 0; i < node.childNodes.length; i++) {
                var child = node.childNodes[i];
                allDescendants(child);
            } // Next i 
            // IE 11 Polyfill 
            if (!Element.prototype.matches)
                Element.prototype.matches = Element.prototype.msMatchesSelector;
            if (node.matches) {
                if (node.matches(childSelector)) {
                    // console.log("match");
                    node.addEventListener(eventName, eventCallback, false);
                } // End if ((<Element>node).matches(childSelector))
                // else console.log("no match");
            } // End if ((<Element>node).matches) 
            // else console.log("no matchfunction");
        } // End Function allDescendants 
        // Callback function to execute when mutations are observed
        var callback = function (mutationsList, observer) {
            for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                var mutation = mutationsList_1[_i];
                // console.log("mutation.type", mutation.type);
                // console.log("mutation", mutation);
                if (mutation.type == 'childList') {
                    for (var i = 0; i < mutation.addedNodes.length; ++i) {
                        var thisNode = mutation.addedNodes[i];
                        allDescendants(thisNode);
                    } // Next i 
                } // End if (mutation.type == 'childList') 
                // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
            } // Next mutation 
        }; // End Function callback 
        // Options for the observer (which mutations to observe)
        var config = { attributes: false, childList: true, subtree: true };
        // Create an observer instance linked to the callback function
        var observer = new MutationObserver(callback);
        // Start observing the target node for configured mutations
        observer.observe(nodeToObserve, config);
    } // End Function subscribeEvent 


    function radioCheckbox_onClick() 
    { 
        // console.log("click", this);
        let box = this;
        if (box.checked) 
        {
            let name = box.getAttribute("name");
            let pos = name.lastIndexOf("_");
            if (pos !== -1) name = name.substr(0, pos);

            let group = 'input[type="checkbox"][name^="' + name + '"]';
            // console.log(group);
            let eles = document.querySelectorAll(group);
            // console.log(eles);
            for (let j = 0; j < eles.length; ++j) 
            {
                eles[j].checked = false;
            }
            box.checked = true;
        }
        else
            box.checked = false;
    }


    // https://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group
    function radioCheckbox()
    { 
        // on instead of document...
        let elements = document.querySelectorAll('input[type="checkbox"]')

        for (let i = 0; i < elements.length; ++i)
        {
            // console.log(elements[i]);
            elements[i].addEventListener("click", radioCheckbox_onClick, false);

        } // Next i 

    } // End Function radioCheckbox 


    function onDomReady()
    {
        console.log("dom ready");
        subscribeEvent(document, "click", 
            'input[type="checkbox"]', 
            radioCheckbox_onClick
        ); 

        // radioCheckbox();
    }

    if (document.addEventListener) document.addEventListener("DOMContentLoaded", onDomReady, false);
    else if (document.attachEvent) document.attachEvent("onreadystatechange", onDomReady);
    else window.onload = onDomReady;

    function onPageLoaded() {
        console.log("page loaded");
    }

    if (window.addEventListener) window.addEventListener("load", onPageLoaded, false);
    else if (window.attachEvent) window.attachEvent("onload", onPageLoaded);
    else window.onload = onPageLoaded;

How to convert an integer to a string in any base?

Here is a recursive version that handles signed integers and custom digits.

import string

def base_convert(x, base, digits=None):
    """Convert integer `x` from base 10 to base `base` using `digits` characters as digits.
    If `digits` is omitted, it will use decimal digits + lowercase letters + uppercase letters.
    """
    digits = digits or (string.digits + string.ascii_letters)
    assert 2 <= base <= len(digits), "Unsupported base: {}".format(base)
    if x == 0:
        return digits[0]
    sign = '-' if x < 0 else ''
    x = abs(x)
    first_digits = base_convert(x // base, base, digits).lstrip(digits[0])
    return sign + first_digits + digits[x % base]

Creating hard and soft links using PowerShell

In Windows 7, the command is

fsutil hardlink create new-file existing-file

PowerShell finds it without the full path (c:\Windows\system32) or extension (.exe).

How to get substring in C

If you just want to print the substrings ...

char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);
}

sql primary key and index

Primary keys are always indexed by default.

You can define a primary key in SQL Server 2012 by using SQL Server Management Studio or Transact-SQL. Creating a primary key automatically creates a corresponding unique, clustered or nonclustered index.

http://technet.microsoft.com/en-us/library/ms189039.aspx

Using Switch Statement to Handle Button Clicks

Hi its quite simple to make switch between buttons using switch case:-

 package com.example.browsebutton;


    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

        public class MainActivity extends Activity implements OnClickListener {
        Button b1,b2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                b1=(Button)findViewById(R.id.button1);

                b2=(Button)findViewById(R.id.button2);
                b1.setOnClickListener(this);
                b2.setOnClickListener(this);
            }



            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 int id=v.getId();
                 switch(id) {
                    case R.id.button1:
                  Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
                //Your Operation

                  break;

                    case R.id.button2:
                          Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();


                          //Your Operation
                          break;
            }

        }}

Building executable jar with maven?

Right click the project and give maven build,maven clean,maven generate resource and maven install.The jar file will automatically generate.

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Pointers in C: when to use the ampersand and the asterisk?

I was looking through all the wordy explanations so instead turned to a video from University of New South Wales for rescue.Here is the simple explanation: if we have a cell that has address x and value 7, the indirect way to ask for address of value 7 is &7 and the indirect way to ask for value at address x is *x.So (cell: x , value: 7) == (cell: &7 , value: *x) .Another way to look into it: John sits at 7th seat.The *7th seat will point to John and &John will give address/location of the 7th seat. This simple explanation helped me and hope it will help others as well. Here is the link for the excellent video: click here.

Here is another example:

#include <stdio.h>

int main()
{ 
    int x;            /* A normal integer*/
    int *p;           /* A pointer to an integer ("*p" is an integer, so p
                       must be a pointer to an integer) */

    p = &x;           /* Read it, "assign the address of x to p" */
    scanf( "%d", &x );          /* Put a value in x, we could also use p here */
    printf( "%d\n", *p ); /* Note the use of the * to get the value */
    getchar();
}

Add-on: Always initialize pointer before using them.If not, the pointer will point to anything, which might result in crashing the program because the operating system will prevent you from accessing the memory it knows you don't own.But simply putting p = &x;, we are assigning the pointer a specific location.

Head and tail in one line

Under Python 3.x, you can do this nicely:

>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

A new feature in 3.x is to use the * operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.

It's also really readable.

As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:

it = iter(iterable)
head, tail = next(it), list(it)

As noted in the comments, this also provides an opportunity to get a default value for head rather than throwing an exception. If you want this behaviour, next() takes an optional second argument with a default value, so next(it, None) would give you None if there was no head element.

Naturally, if you are working on a list, the easiest way without the 3.x syntax is:

head, tail = seq[0], seq[1:]

Using global variables between files?

I just came across this post and thought of posting my solution, just in case of anyone being in the same situation as me, where there are quite some files in the developed program, and you don't have the time to think through the whole import sequence of your modules (if you didn't think of that properly right from the start, such as I did).

In such cases, in the script where you initiate your global(s), simply code a class which says like:

class My_Globals:
  def __init__(self):
    self.global1 = "initial_value_1"
    self.global2 = "initial_value_2"
    ...

and then use, instead of the line in the script where you initiated your globals, instead of

global1 = "initial_value_1"

use

globals = My_Globals()

I was then able to retrieve / change the values of any of these globals via

globals.desired_global

in any script, and these changes were automatically also applied to all the other scripts using them. All worked now, by using the exact same import statements which previously failed, due to the problems mentioned in this post / discussion here. I simply thought of global object's properties being changing dynamically without the need of considering / changing any import logic, in comparison to simple importing of global variables, and that definitely was the quickest and easiest (for later access) approach to solve this kind of problem for me.

Java Spring Boot: How to map my app root (“/”) to index.html?

I had the same problem. Spring boot knows where static html files are located.

  1. Add index.html into resources/static folder
  2. Then delete full controller method for root path like @RequestMapping("/") etc
  3. Run app and check http://localhost:8080 (Should work)

How can I check if an ip is in a network in Python?

From various sources above, and from my own research, this is how I got subnet and address calculation working. These pieces are enough to solve the question and other related questions.

class iptools:
    @staticmethod
    def dottedQuadToNum(ip):
        "convert decimal dotted quad string to long integer"
        return struct.unpack('>L', socket.inet_aton(ip))[0]

    @staticmethod
    def numToDottedQuad(n):
        "convert long int to dotted quad string"
        return socket.inet_ntoa(struct.pack('>L', n))

    @staticmethod
    def makeNetmask(mask):
        bits = 0
        for i in xrange(32-int(mask), 32):
            bits |= (1 << i)
        return bits

    @staticmethod
    def ipToNetAndHost(ip, maskbits):
        "returns tuple (network, host) dotted-quad addresses given"
        " IP and mask size"
        # (by Greg Jorgensen)
        n = iptools.dottedQuadToNum(ip)
        m = iptools.makeMask(maskbits)
        net = n & m
        host = n - mask
        return iptools.numToDottedQuad(net), iptools.numToDottedQuad(host)

How can I get the console logs from the iOS Simulator?

No NSLog or print content will write to system.log, which can be open by Select Simulator -> Debug -> Open System log on Xcode 11.

I figure out a way, write logs into a file and open the xx.log with Terminal.app.Then the logs will present in Terminal.app lively.

I use CocoaLumberjack achieve this.

STEP 1:

Add DDFileLogger DDOSLogger and print logs path. config() should be called when App lunch.

static func config() {
    #if DEBUG
    DDLog.add(DDOSLogger.sharedInstance) // Uses os_log
    let fileLogger: DDFileLogger = DDFileLogger() // File Logger
    fileLogger.rollingFrequency = 60 * 60 * 24 // 24 hours
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7
    DDLog.add(fileLogger)
    DDLogInfo("DEBUG LOG PATH: " + (fileLogger.currentLogFileInfo?.filePath ?? ""))
    #endif
}

STEP 2:

Replace print or NSLog with DDLogXXX.

STEP 3:

$ tail -f {path of log}

Here, message will present in Terminal.app lively.

One thing more. If there is no any message log out, make sure Environment Variables -> OS_ACTIVITY_MODE ISNOT disable.

Best Practices for mapping one object to another

Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.

Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.

Get the latest record with filter in Django

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

This question wasn't asking explicitly about Docker, but I received the same error when I had a pom.xml file that was targeting 1.9...

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.9</maven.compiler.source>
  <maven.compiler.target>1.9</maven.compiler.target>
</properties>

... but then tried to run tests against a Docker container by specifying "maven" by itself.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven mvn -e test

For me, the fix was to target the exact version I needed.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven:3.5.2-jdk-9 mvn test

(You can learn more here.)

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Validate select box

   <script type="text/JavaScript">  
function validate() 
{
if( document.form1.quali.value == "-1" )
   {
     alert( "Please select qualification!" );
     return false;
   }
}

</script>
<form name="form1" method="post" action="" onsubmit="return validate(this);">
<select name="quali" id="quali" ">
        <option value="-1" selected="selected">select</option>
        <option value="1">Graduate</option>
        <option value="2">Post Graduate</option>
      </select> 
</form>





// this code works 110% tested by me after many complex jquery method validation but it is simple javascript method plz try this if u fail in drop down required validation//

Grouping into interval of 5 minutes within a time range

select 
CONCAT(CAST(CREATEDATE AS DATE),' ',datepart(hour,createdate),':',ROUNd(CAST((CAST((CAST(DATEPART(MINUTE,CREATEDATE) AS DECIMAL (18,4)))/5 AS INT)) AS DECIMAL (18,4))/12*60,2)) AS '5MINDATE'
,count(something)
from TABLE
group by CONCAT(CAST(CREATEDATE AS DATE),' ',datepart(hour,createdate),':',ROUNd(CAST((CAST((CAST(DATEPART(MINUTE,CREATEDATE) AS DECIMAL (18,4)))/5 AS INT)) AS DECIMAL (18,4))/12*60,2))

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

HTML input arrays

Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>

Deserialize from string instead TextReader

static T DeserializeXml<T>(string sourceXML) where T : class
{
    var serializer = new XmlSerializer(typeof(T));
    T result = null;

    using (TextReader reader = new StringReader(sourceXML))
    {
        result = (T) serializer.Deserialize(reader);
    }

    return result;
}

Get fragment (value after hash '#') from a URL in php

You can't get the text after the hash mark. It is not sent to the server in a request.

In Java, what is the best way to determine the size of an object?

When using JetBrains IntelliJ, first enable "Attach memory agent" in File | Settings | Build, Execution, Deployment | Debugger.

When debugging, right-click a variable of interest and choose "Calculate Retained Size": Calculate Retained Size

Routing for custom ASP.NET MVC 404 Error page

This solution doesn't need web.config file changes or catch-all routes.

First, create a controller like this;

public class ErrorController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Regular Error";
        return View();
    }

    public ActionResult NotFound404()
    {
        ViewBag.Title = "Error 404 - File not Found";
        return View("Index");
    }
}

Then create the view under "Views/Error/Index.cshtml" as;

 @{
      Layout = "~/Views/Shared/_Layout.cshtml";
  }                     
  <p>We're sorry, page you're looking for is, sadly, not here.</p>

Then add the following in the Global asax file as below:

protected void Application_Error(object sender, EventArgs e)
{
        // Do whatever you want to do with the error

        //Show the custom error page...
        Server.ClearError(); 
        var routeData = new RouteData();
        routeData.Values["controller"] = "Error";

        if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
        {
            routeData.Values["action"] = "Index";
        }
        else
        {
            // Handle 404 error and response code
            Response.StatusCode = 404;
            routeData.Values["action"] = "NotFound404";
        } 
        Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
        IController errorsController = new ErrorController();
        HttpContextWrapper wrapper = new HttpContextWrapper(Context);
        var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
        errorsController.Execute(rc);

        Response.End();
}

If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:

<system.web>
   <customErrors mode="Off" />
</system.web>
<system.webServer>   
   <httpErrors>     
   </httpErrors>
</system.webServer>

How to read file using NPOI

Since you've asked to read and modify the xls file I have changed @mj82's answer to correspond your needs.

HSSFWorkbook does not have Save method, but it does have Write to a stream.

static void Main(string[] args)
        {
            string filepath = @"C:\test.xls";

            HSSFWorkbook hssfwb;

            using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                hssfwb = new HSSFWorkbook(file);
            }

            ISheet sheet = hssfwb.GetSheetAt(0);

            for (int row = 0; row <= sheet.LastRowNum; row++)
            {
                if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
                {
                    // Set new cell value
                    sheet.GetRow(row).GetCell(0).SetCellValue("foo");
                    Console.WriteLine("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue);
                }
            }

            // Save the file
            using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Write))
            {
                hssfwb.Write(file);
            }

            Console.ReadLine();
        }

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Rendering raw html with reactjs

export class ModalBody extends Component{
    rawMarkup(){
        var rawMarkup = this.props.content
        return { __html: rawMarkup };
    }
    render(){
        return(
                <div className="modal-body">
                     <span dangerouslySetInnerHTML={this.rawMarkup()} />

                </div>
            )
    }
}

Access VBA | How to replace parts of a string with another string

You could use a function similar to this also, it would allow you to add in different cases where you would like to change values:

Public Function strReplace(varValue As Variant) as Variant

    Select Case varValue

        Case "Avenue"
            strReplace = "Ave"

        Case "North"
            strReplace = "N"

        Case Else
            strReplace = varValue

    End Select

End Function

Then your SQL would read something like:

SELECT strReplace(Address) As Add FROM Tablename

How to check if iframe is loaded or it has a content?

You can use the iframe's load event to respond when the iframe loads.

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

connecting MySQL server to NetBeans

check the context.xml file in Web Pages -> META-INF, the username="user" must be the same as the database user, in my case was root, that solved the connection error

Hope helps

IOException: read failed, socket might closed - Bluetooth on Android 4.3

Bluetooth devices can operate in both classic and LE mode at the same time. Sometimes they use a different MAC address depending on which way you are connecting. Calling socket.connect() is using Bluetooth Classic, so you have to make sure the device you got when you scanned was really a classic device.

It's easy to filter for only Classic devices, however:

if(BluetoothDevice.DEVICE_TYPE_LE == device.getType()){ //socket.connect() }

Without this check, it's a race condition as to whether a hybrid scan will give you the Classic device or the BLE device first. It may appear as intermittent inability to connect, or as certain devices being able to connect reliably while others seemingly never can.

View RDD contents in Python Spark?

This error is because print isn't a function in Python 2.6.

You can either define a helper UDF that performs the print, or use the __future__ library to treat print as a function:

>>> from operator import add
>>> f = sc.textFile("README.md")
>>> def g(x):
...     print x
...
>>> wc.foreach(g)

or

>>> from __future__ import print_function
>>> wc.foreach(print)

However, I think it would be better to use collect() to bring the RDD contents back to the driver, because foreach executes on the worker nodes and the outputs may not necessarily appear in your driver / shell (it probably will in local mode, but not when running on a cluster).

>>> for x in wc.collect():
...     print x

IF EXISTS condition not working with PLSQL

Unfortunately PL/SQL doesn't have IF EXISTS operator like SQL Server. But you can do something like this:

begin
  for x in ( select count(*) cnt
               from dual 
              where exists (
                select 1 from courseoffering co
                  join co_enrolment ce on ce.co_id = co.co_id
                 where ce.s_regno = 403 
                   and ce.coe_completionstatus = 'C' 
                   and co.c_id = 803 ) )
  loop
        if ( x.cnt = 1 ) 
        then
           dbms_output.put_line('exists');
        else 
           dbms_output.put_line('does not exist');
        end if;
  end loop;
end;
/

Classes cannot be accessed from outside package

Maybe you should try removing "new" keyword and see if works. Because last time I got this error when I tried creating Typeface something like this:

Typeface typeface = new Typeface().create("Arial",Typeface.BOLD);

Python: Open file in zip without temporarily extracting it

import io, pygame, zipfile
archive = zipfile.ZipFile('images.zip', 'r')

# read bytes from archive
img_data = archive.read('img_01.png')

# create a pygame-compatible file-like object from the bytes
bytes_io = io.BytesIO(img_data)

img = pygame.image.load(bytes_io)

I was trying to figure this out for myself just now and thought this might be useful for anyone who comes across this question in the future.

How to get Month Name from Calendar?

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

For some languages (e.g. Russian) this is the only correct way to get the stand-alone month names.

This is what you get, if you use getDisplayName from the Calendar or DateFormatSymbols for January:

?????? (which is correct for a complete date string: "10 ??????, 2014")

but in case of a stand-alone month name you would expect:

??????

How do I delete everything in Redis?

One more option from my side:

In our production and pre-production databases there are thousands of keys. Time to time we need to delete some keys (by some mask), modify by some criteria etc. Of course, there is no way to do it manually from CLI, especially having sharding (512 logical dbs in each physical).

For this purpose I write java client tool that does all this work. In case of keys deletion the utility can be very simple, only one class there:

public class DataCleaner {

    public static void main(String args[]) {
        String keyPattern = args[0];
        String host = args[1];
        int port = Integer.valueOf(args[2]);
        int dbIndex = Integer.valueOf(args[3]);

        Jedis jedis = new Jedis(host, port);

        int deletedKeysNumber = 0;
        if(dbIndex >= 0){
            deletedKeysNumber += deleteDataFromDB(jedis, keyPattern, dbIndex);
        } else {
            int dbSize = Integer.valueOf(jedis.configGet("databases").get(1));
            for(int i = 0; i < dbSize; i++){
                deletedKeysNumber += deleteDataFromDB(jedis, keyPattern, i);
            }
        }

        if(deletedKeysNumber == 0) {
            System.out.println("There is no keys with key pattern: " + keyPattern + " was found in database with host: " + host);
        }
    }

    private static int deleteDataFromDB(Jedis jedis, String keyPattern, int dbIndex) {
        jedis.select(dbIndex);
        Set<String> keys = jedis.keys(keyPattern);
        for(String key : keys){
            jedis.del(key);
            System.out.println("The key: " + key + " has been deleted from database index: " + dbIndex);
        }

        return keys.size();
    }

}

Writing such kind of tools I find very easy and spend no more then 5-10 min.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

You need to tell it that you are using SSL:

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

In case you miss anything, here is working code:

String  d_email = "[email protected]",
            d_uname = "Name",
            d_password = "urpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Indoors Readable File: " + params[0].getName(),
            m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

Transport transport = session.getTransport("smtps");
            transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

Command to get latest Git commit hash from a branch

Note that when using "git log -n 1 [branch_name]" option. -n returns only one line of log but order in which this is returned is not guaranteed. Following is extract from git-log man page

.....
.....
Commit Limiting

Besides specifying a range of commits that should be listed using the special notations explained in the     description, additional commit limiting may be applied.

Using more options generally further limits the output (e.g. --since=<date1> limits to commits newer than <date1>, and using it with --grep=<pattern> further limits to commits whose log message has a line that matches <pattern>), unless otherwise noted.

Note that these are applied before commit ordering and formatting options, such as --reverse.

-<number>
-n <number>
.....
.....

Java Interfaces/Implementation naming convention

I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?

Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.

Cannot find name 'require' after upgrading to Angular4

As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.

_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
    .._x000D_
    "types": [_x000D_
      "node"_x000D_
    ]_x000D_
  }_x000D_
  .._x000D_
}
_x000D_
_x000D_
_x000D_

One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node

How can I get the full/absolute URL (with domain) in Django?

I came across this thread because I was looking to build an absolute URI for a success page. request.build_absolute_uri() gave me a URI for my current view but to get the URI for my success view I used the following....

request.build_absolute_uri(reverse('success_view_name'))

How to use breakpoints in Eclipse

To put breakpoints in your code, double click in the left margin on the line you want execution to stop on. You may alternatively put your cursor in this line and then press Shift+Ctrl+B.

To control execution use the Step Into, Step Over and Step Return buttons. They have the shortcuts F5, F6 and F7 respectively.

To allow execution to continue normally or until it hits the next breakpoint, hit the Resume button or F8.

How to change pivot table data source in Excel?

In order to change the data source from the ribbon in excel 2007...

Click on your pivot table in the worksheet. Go to the ribbon where it says Pivot Table Tools, Options Tab. Select the Change Data Source button. A dialog box will appear.

To get the right range and avoid an error message... select the contents of the existing field and delete it, then switch to the new data source worksheet and highlight the data area (the dialog box will stay on top of all windows). Once you've selected the new data source correctly, it will fill in the blank field (which you deleted before) in the dialog box. Click OK. Switch back to your pivot table and it should have updated with the new data from the new source.

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

Not the right function name I think

$(document).ready(function() {

    $('.datepicker').datetimepicker({
        format: 'dd/mm/yyyy'
    });
});

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

Install / upgrade gradle on Mac OS X

I had downloaded it from http://gradle.org/gradle-download/. I use Homebrew, but I missed installing gradle using it.

To save some MBs by downloading it over again using Homebrew, I symlinked the gradle binary from the downloaded (and extracted) zip archive in the /usr/local/bin/. This is the same place where Homebrew symlinks all other binaries.

cd /usr/local/bin/
ln -s ~/Downloads/gradle-2.12/bin/gradle

Now check whether it works or not:

gradle -v

GridView sorting: SortDirection always Ascending

Another one :) Don't need to hard code column names..

DataTable dt = GetData();

    SortDirection sd;
    string f;
    GridViewSortDirection(gvProductBreakdown, e, out sd, out f);
    dt.DefaultView.Sort = sd == SortDirection.Ascending ? f + " asc" : f + " desc";
    gvProductBreakdown.DataSource = dt;
    gvProductBreakdown.DataBind();

Ant then:

 private void GridViewSortDirection(GridView g, GridViewSortEventArgs e, out SortDirection d, out string f)
    {
        f = e.SortExpression;
        d = e.SortDirection;
 if (g.Attributes[f] != null)
        {
            d = g.Attributes[f] == "ASC" ? SortDirection.Descending : SortDirection.Ascending;

            g.Attributes[f] = d == SortDirection.Ascending ? "ASC" : "DESC";
        }
        else
        {
            g.Attributes[f] = "ASC";
            d = SortDirection.Ascending;
        }

Executing <script> elements inserted with .innerHTML

Try function eval().

data.newScript = '<script type="text/javascript">//my script...</script>'
var element = document.getElementById('elementToRefresh');
element.innerHTML = data.newScript;
eval(element.firstChild.innerHTML);

This is a real example from a project that i am developing. Thanks to this post

Does adding a duplicate value to a HashSet/HashMap replace the previous value

It the case of HashSet, it does NOT replace it.

From the docs:

http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)

"Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false."

Change Tomcat Server's timeout in Eclipse

double click tomcat , see configure setting with "timeout" modify the number. Maybe this not the tomcat error.U can see the DB connection is achievable.

How to continue a Docker container which has exited

Follow these steps:

  1. Run below command to see that all the container services both running and stopped on. Option -a is given to see that the container stops as well

    docker ps -a
    
  2. Then start the docker container either by container_id or container tag names

    docker start <CONTAINER_ID> or <NAMES>
    

    enter image description here

    Say from the above picture, container id 4b161b302337
    So command to be run is

    docker start 4b161b302337
    
  3. One can verify whether the container is running with

    docker ps
    

Java equivalent of unsigned long long?

Java does not have unsigned types. As already mentioned, incure the overhead of BigInteger or use JNI to access native code.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.

For those still facing this problem, I was able to resolve it as follows:

$ git commit --allow-empty -n -m "Initial commit".

Can an Android Toast be longer than Toast.LENGTH_LONG?

Toast duration can be hacked using a thread that runs the toast exclusively. This works (runs the toast for 10 secs, modify sleep and ctr to your liking):

final Toast toast = Toast.makeText(this, "Your Message", Toast.LENGTH_LONG);

Thread t = new Thread(){
    public void run(){
          int ctr = 0;
          try{
               while( ctr<10 ){
                    toast.show();
                    sleep(1000);
                    ctr++;
               }
          } catch (Exception e) {
               Log.e("Error", "", e);
          }
     }
 };
 t.start();

Boolean vs boolean in Java

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

int is not boolean

Consider

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

Bytes are not types or bits

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

keyword vs. type

Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

boolean foo = true;

vs.

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

Optimization is achieved due to trivial:

"Less runtime casting operations => more speed."

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).

Finally, autoboxing is slower than primitives

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.