Programs & Examples On #Html to pdf

For questions related to conversion of HTML pages to PDF files

ITextSharp HTML to PDF?

I came across the same question a few weeks ago and this is the result from what I found. This method does a quick dump of HTML to a PDF. The document will most likely need some format tweaking.

private MemoryStream createPDF(string html)
{
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);

    // step 2:
    // we create a writer that listens to the document
    // and directs a XML-stream to a file
    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

    // step 3: we create a worker parse the document
    HTMLWorker worker = new HTMLWorker(document);

    // step 4: we open document and start the worker on the document
    document.Open();
    worker.StartDocument();

    // step 5: parse the html into the document
    worker.Parse(reader);

    // step 6: close the document and the worker
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
}

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How to make an executable JAR file?

If you use maven, add the following to your pom.xml file:

<plugin>
    <!-- Build an executable JAR -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.path.to.YourMainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

Then you can run mvn package. The jar file will be located under in the target directory.

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

My guess is that you are trying to restore in lower versions which wont work

How to execute an oracle stored procedure?

I use oracle 12 and it tell me that if you need to invoke the procedure then use call keyword. In your case it should be:

begin
  call temp_proc;
end;

Convert String to java.util.Date

I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.

Nevertheless, this works fine for me:

String testDate = "29-Apr-2010,13:00:14 PM";
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(testDate);
System.out.println(date);

It prints "Thu Apr 29 13:00:14 CEST 2010".

How to embed HTML into IPython output?

Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:

Serving Local HTML

If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

Serving Remote HTML

If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:

_x000D_
_x000D_
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
_x000D_
_x000D_
_x000D_

annotation to make a private method public only for test classes

An article on Testing Private Methods lays out some approaches to testing private code. using reflection puts extra burden on the programmer to remember if refactoring is done, the strings aren't automatically changed, but I think it's the cleanest approach.

How to get the current directory in a C program?

Look up the man page for getcwd.

submitting a GET form with query string params and hidden params disappear

I usually write something like this:

foreach($_GET as $key=>$content){
        echo "<input type='hidden' name='$key' value='$content'/>";
}

This is working, but don't forget to sanitize your inputs against XSS attacks!

How to get a list of installed Jenkins plugins with name and version pair

From the Jenkins home page:

  1. Click Manage Jenkins.
  2. Click Manage Plugins.
  3. Click on the Installed tab.

Or

  1. Go to the Jenkins URL directly: {Your Jenkins base URL}/pluginManager/installed

Check OS version in Swift?

For iOS, try:

var systemVersion = UIDevice.current.systemVersion

For OS X, try:

var systemVersion = NSProcessInfo.processInfo().operatingSystemVersion

If you just want to check if the users is running at least a specific version, you can also use the following Swift 2 feature which works on iOS and OS X:

if #available(iOS 9.0, *) {
    // use the feature only available in iOS 9
    // for ex. UIStackView
} else {
    // or use some work around
}

BUT it is not recommended to check the OS version. It is better to check if the feature you want to use is available on the device than comparing version numbers. For iOS, as mentioned above, you should check if it responds to a selector; eg.:

if (self.respondsToSelector(Selector("showViewController"))) {
    self.showViewController(vc, sender: self)
} else {
    // some work around
}

Allowed characters in filename

For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.

$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);

Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.

The total number of locks exceeds the lock table size

Same issue I'm getting in my MYSQL while running sql script Please look into below image.. Error code 1206: The number of locks exceeds the lock table size Picture

This is Mysql configuration issue so I made some changes in my.ini and It's working on my system & issue resolved.

We need to make some changes in my.ini which is available on following Path:- C:\ProgramData\MySQL\MySQL Server 5.7\my.ini and please update following changes in my.ini config file fields:-

key_buffer_size=64M
read_buffer_size=64M
read_rnd_buffer_size=128M
innodb_log_buffer_size=10M
innodb_buffer_pool_size=256M
query_cache_type=2
max_allowed_packet=16M

After all above changes please restart the MYSQL Service. Please refer the image:- Microsoft MYSQL Service Picture

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

How to do a https request with bad certificate?

Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.

In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.

Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.

RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.

How to call a PHP function on the click of a button

The onclick attribute in HTML calls JavaScript functions, not PHP functions.

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

How to getText on an input in protractor

You can use jQuery to get text in textbox (work well for me), check in image detail

Code:

$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()

Example: 
$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()

Inject this above query to your code. Image detail:

enter image description here

Gather multiple sets of columns

With the recent update to melt.data.table, we can now melt multiple columns. With that, we can do:

require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"), 
     value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
 #    id       time loop_number         Q3.2        Q3.3
 # 1:  1 2009-01-01           1 -0.433978480  0.41227209
 # 2:  2 2009-01-02           1 -0.567995351  0.30701144
 # 3:  3 2009-01-03           1 -0.092041353 -0.96024077
 # 4:  4 2009-01-04           1  1.137433487  0.60603396
 # 5:  5 2009-01-05           1 -1.071498263 -0.01655584
 # 6:  6 2009-01-06           1 -0.048376809  0.55889996
 # 7:  7 2009-01-07           1 -0.007312176  0.69872938

You can get the development version from here.

AngularJS 1.2 $injector:modulerr

Its an injector error. You may have use lots of JavaScript files so the injector may be missing.

Some are here:

var app = angular.module('app', 
    ['ngSanitize', 'ui.router', 'pascalprecht.translate', 'ngResource', 
     'ngMaterial', 'angularMoment','md.data.table', 'angularFileUpload', 
     'ngMessages', 'ui.utils.masks', 'angular-sortable-view',          
     'mdPickers','ngDraggable','as.sortable', 'ngAnimate', 'ngTouch']
);

Please check the injector you need to insert in your app.js

add/remove active class for ul list with jquery?

I used this:

$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');

Since the active class is in the <li> element and what is clicked is the <a> element, the first line removes .active from all <li> and the second one (again, $(this) represents <a> which is the clicked element) adds .active to the direct parent, which is <li>.

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

Is there a better way to do optional function parameters in JavaScript?

In all cases where optionalArg is falsy you will end up with defaultValue.

function myFunc(requiredArg, optionalArg) {
    optionalArg = optionalArg || 'defaultValue';
    console.log(optionalArg);
    // Do stuff
}
myFunc(requiredArg);
myFunc(requiredArg, null);
myFunc(requiredArg, undefined);
myFunc(requiredArg, "");
myFunc(requiredArg, 0);
myFunc(requiredArg, false);

All of the above log defaultValue, because all of 6 are falsy. In case 4, 5, 6 you might not be interested to set optionalArg as defaultValue, but it sets since they are falsy.

How can I pass an Integer class correctly by reference?

There are 2 ways to pass by reference

  1. Use org.apache.commons.lang.mutable.MutableInt from Apache Commons library.
  2. Create custom class as shown below

Here's a sample code to do it:

public class Test {
    public static void main(String args[]) {
        Integer a = new Integer(1);
        Integer b = a;
        Test.modify(a);
        System.out.println(a);
        System.out.println(b);

        IntegerObj ao = new IntegerObj(1);
        IntegerObj bo = ao;
        Test.modify(ao);
        System.out.println(ao.value);
        System.out.println(bo.value);
    }


    static void modify(Integer x) {
        x=7;
    }
    static void modify(IntegerObj x) {
        x.value=7;
    }   
}

class IntegerObj {
    int value;
    IntegerObj(int val) {
        this.value = val;
    }
}

Output:

1
1
7
7

When does Java's Thread.sleep throw InterruptedException?

The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException. It's well worth reading and digesting.

remove url parameters with javascript or jquery

Well, I am using this:

stripUrl(urlToStrip){
        let stripped = urlToStrip.split('?')[0];
        stripped = stripped.split('&')[0];
        stripped = stripped.split('#')[0];
        return stripped;
    }

or:

    stripUrl(urlToStrip){
        return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
    }

Set cellpadding and cellspacing in CSS?

Try this:

table {
    border-collapse: separate;
    border-spacing: 10px;
}
table td, table th {
    padding: 10px;
}

Or try this:

table {
    border-collapse: collapse;
}
table td, table th {
    padding: 10px;
}

How to create a HTTP server in Android?

NanoHttpd works like a charm on Android -- we have code in production, in users hands, that's built on it.

The license absolutely allows commercial use of NanoHttpd, without any "viral" implications.

Why aren't programs written in Assembly more often?

The same reason we don't go to the bathroom outside anymore, or why we don't speak Latin or Aramaic.

Technology comes along and makes things easier and more accessible.

EDIT - to cease offending people, I've removed certain words.

SQL Update Multiple Fields FROM via a SELECT Statement

You can use:

UPDATE s SET
  s.Field1 = q.Field1,
  s.Field2 = q.Field2,
  (list of fields...)
FROM (
  SELECT Field1, Field2, (list of fields...)
  FROM ProfilerTest.dbo.BookingDetails 
  WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2

Iterating through all the cells in Excel VBA or VSTO 2005

For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.

For Excel 2003, this MSDN article is a good place to start. Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective

You'll basically need to do the following:

  • Start the Excel application.
  • Open the Excel workbook.
  • Retrieve the worksheet from the workbook by name or index.
  • Iterate through all the Cells in the worksheet which were retrieved as a range.
  • Sample (untested) code excerpt below for the last step.

    Excel.Range allCellsRng;
    string lowerRightCell = "IV65536";
    allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
    foreach (Range cell in allCellsRng)
    {
        if (null == cell.Value2 || isBlank(cell.Value2))
        {
          // Do something.
        }
        else if (isText(cell.Value2))
        {
          // Do something.
        }
        else if (isNumeric(cell.Value2))
        {
          // Do something.
        }
    }

For Excel 2007, try this MSDN reference.

Error in contrasts when defining a linear model in R

If your independent variable (RHS variable) is a factor or a character taking only one value then that type of error occurs.

Example: iris data in R

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species, data=iris))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, data = iris)

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#            2.2514             0.8036             1.4587             1.9468  

Now, if your data consists of only one species:

(model1 <- lm(Sepal.Length ~ Sepal.Width + Species,
              data=iris[iris$Species == "setosa", ]))
# Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
#   contrasts can be applied only to factors with 2 or more levels

If the variable is numeric (Sepal.Width) but taking only a single value say 3, then the model runs but you will get NA as coefficient of that variable as follows:

(model2 <-lm(Sepal.Length ~ Sepal.Width + Species,
             data=iris[iris$Sepal.Width == 3, ]))

# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Species, 
#    data = iris[iris$Sepal.Width == 3, ])

# Coefficients:
#       (Intercept)        Sepal.Width  Speciesversicolor   Speciesvirginica  
#             4.700                 NA              1.250              2.017

Solution: There is not enough variation in dependent variable with only one value. So, you need to drop that variable, irrespective of whether that is numeric or character or factor variable.

Updated as per comments: Since you know that the error will only occur with factor/character, you can focus only on those and see whether the length of levels of those factor variables is 1 (DROP) or greater than 1 (NODROP).

To see, whether the variable is a factor or not, use the following code:

(l <- sapply(iris, function(x) is.factor(x)))
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#        FALSE        FALSE        FALSE        FALSE         TRUE 

Then you can get the data frame of factor variables only

m <- iris[, l]

Now, find the number of levels of factor variables, if this is one you need to drop that

ifelse(n <- sapply(m, function(x) length(levels(x))) == 1, "DROP", "NODROP")

Note: If the levels of factor variable is only one then that is the variable, you have to drop.

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

How do you import an Eclipse project into Android Studio now?

Its Got simpler with Android Studio All you need is to first choose

  1. import project(eclipse.....) enter image description here
  2. then choose your folder eclipse based project.like this one below enter image description here

3.based on the type of project and library you used like (ActionBarSherlock) you may prompted special import wizard so go ahead and click next then finish. in this case it was simple one

enter image description here

4.And you are done. enter image description here

but sometimes the debug or Run options do not work and a error msg shows like

"this project structure is not gradle based or migrate it to gradle"

something to solve this close the opened eclipse project and reopen same project through the same process as we did before with import project (eclipse adt,gradle,etc)) this time android studio gonna add all necessary gradle files and green debug option will work too. i have did this somehow accidentally but it worked, i just hope it works for you too.

Unbound classpath container in Eclipse

For those using sdkman, this helped me.

Use Case:
I was using identifier 8.0.202-amzn
I decided to install Azul Zulu as follows: sdk install java 13.0.2-zulu

Error: And then i got this unbound error.

Solution:
1. Right-click on your project in Eclipse/STS
2. Choose Build Path > Configure Build Path...
3. Under Libraries, remove the JRE Library, for my case 8.0.202-amzn
4. Under Libraries, click on Modulepath > Add Library...
5. Choose JRE System Library, click Next
6. Choose Alternate JRE, click on Installed JREs...
7. Your previous configured value should be there
8. If it is there, edit it, if it is not there, add one
9. Make sure the name is: 13.0.2-zulu
10. And the location(JRE home) is: /Users/jumping_monkey/.sdkman/candidates/java/current
11. Click Apply and close
12. Click Finish
13. Voila!

You will see JRE System Library [13.0.2-zulu] in your Project Explorer and all errors gone

Bravo!

Match the path of a URL, minus the filename extension

Try this:

preg_match("/net(.*)\.php$/","http://php.net/manual/en/function.preg-match.php", $matches);
echo $matches[1];
// prints /manual/en/function.preg-match

How can I multiply and divide using only bit shifting and adding?

For anyone interested in a 16-bit x86 solution, there is a piece of code by JasonKnight here1 (he also includes a signed multiply piece, which I haven't tested). However, that code has issues with large inputs, where the "add bx,bx" part would overflow.

The fixed version:

softwareMultiply:
;    INPUT  CX,BX
;   OUTPUT  DX:AX - 32 bits
; CLOBBERS  BX,CX,DI
    xor   ax,ax     ; cheap way to zero a reg
    mov   dx,ax     ; 1 clock faster than xor
    mov   di,cx
    or    di,bx     ; cheap way to test for zero on both regs
    jz    @done
    mov   di,ax     ; DI used for reg,reg adc
@loop:
    shr   cx,1      ; divide by two, bottom bit moved to carry flag
    jnc   @skipAddToResult
    add   ax,bx
    adc   dx,di     ; reg,reg is faster than reg,imm16
@skipAddToResult:
    add   bx,bx     ; faster than shift or mul
    adc   di,di
    or    cx,cx     ; fast zero check
    jnz   @loop
@done:
    ret

Or the same in GCC inline assembly:

asm("mov $0,%%ax\n\t"
    "mov $0,%%dx\n\t"
    "mov %%cx,%%di\n\t"
    "or %%bx,%%di\n\t"
    "jz done\n\t"
    "mov %%ax,%%di\n\t"
    "loop:\n\t"
    "shr $1,%%cx\n\t"
    "jnc skipAddToResult\n\t"
    "add %%bx,%%ax\n\t"
    "adc %%di,%%dx\n\t"
    "skipAddToResult:\n\t"
    "add %%bx,%%bx\n\t"
    "adc %%di,%%di\n\t"
    "or %%cx,%%cx\n\t"
    "jnz loop\n\t"
    "done:\n\t"
    : "=d" (dx), "=a" (ax)
    : "b" (bx), "c" (cx)
    : "ecx", "edi"
);

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

How do I group Windows Form radio buttons?

I like the concept of grouping RadioButtons in WPF. There is a property GroupName that specifies which RadioButton controls are mutually exclusive (http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx).

So I wrote a derived class for WinForms that supports this feature:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;

namespace Use.your.own
{
    public class AdvancedRadioButton : CheckBox
    {
        public enum Level { Parent, Form };

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the level that specifies which RadioButton controls are affected."),
        DefaultValue(Level.Parent)]
        public Level GroupNameLevel { get; set; }

        [Category("AdvancedRadioButton"),
        Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
        public string GroupName { get; set; }

        protected override void OnCheckedChanged(EventArgs e)
        {
            base.OnCheckedChanged(e);

            if (Checked)
            {
                var arbControls = (dynamic)null;
                switch (GroupNameLevel)
                {
                    case Level.Parent:
                        if (this.Parent != null)
                            arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
                        break;
                    case Level.Form:
                        Form form = this.FindForm();
                        if (form != null)
                            arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
                        break;
                }
                if (arbControls != null)
                    foreach (Control control in arbControls)
                        if (control != this &&
                            (control as AdvancedRadioButton).GroupName == this.GroupName)
                            (control as AdvancedRadioButton).Checked = false;
            }
        }

        protected override void OnClick(EventArgs e)
        {
            if (!Checked)
                base.OnClick(e);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);

            RadioButtonState radioButtonState;
            if (Checked)
            {
                radioButtonState = RadioButtonState.CheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.CheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.CheckedDisabled;
            }
            else
            {
                radioButtonState = RadioButtonState.UncheckedNormal;
                if (Focused)
                    radioButtonState = RadioButtonState.UncheckedHot;
                if (!Enabled)
                    radioButtonState = RadioButtonState.UncheckedDisabled;
            }

            Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
            Rectangle rect = pevent.ClipRectangle;
            rect.Width -= glyphSize.Width;
            rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);

            RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
        }

        private IEnumerable<Control> GetAll(Control control, Type type)
        {
            var controls = control.Controls.Cast<Control>();

            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Concat(controls)
                                      .Where(c => c.GetType() == type);
        }
    }
}

How to go to a URL using jQuery?

Actually, you have to use the anchor # to play with this. If you reverse engineer the Gmail url system, you'll find

https://mail.google.com/mail/u/0/#inbox
https://mail.google.com/mail/u/0/#inbox?compose=new

Everything after # is the part your want to load in your page, then you just have to chose where to load it.

By the way, using document.location by adding a #something won't refresh your page.

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

Try this example

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

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

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

How can I clear the input text after clicking

try this

$("input[name=search-mini]").on("search", function() {
 //do something for search
});

REST vs JSON-RPC?

It would be better to choose JSON-RPC between REST and JSON-RPC to develop an API for a web application that is easier to understand. JSON-RPC is preferred because its mapping to method calls and communications can be easily understood.

Choosing the most suitable approach depends on the constraints or principal objective. For example, as far as performance is a major trait, it is advisable to go for JSON-RPC (for example, High Performance Computing). However, if the principal objective is to be agnostic in order to offer a generic interface to be inferred by others, it is advisable to go for REST. If you both goals are needed to be achieved, it is advisable to include both protocols.

The fact which actually splits REST from JSON-RPC is that it trails a series of carefully thought out constraints- confirming architectural flexibility. The constraints take in ensuring that the client as well as server are able to grow independently of each other (changes can be made without messing up with the application of client), the calls are stateless (the state is regarded as hypermedia), a uniform interface is offered for interactions, the API is advanced on a layered system (Hall, 2010). JSON-RPC is rapid and easy to consume, however as mentioned resources as well as parameters are tightly coupled and it is likely to depend on verbs (api/addUser, api/deleteUser) using GET/ POST whereas REST delivers loosely coupled resources (api/users) in a HTTP. REST API depends up on several HTTP methods such as GET, PUT, POST, DELETE, PATCH. REST is slightly tougher for inexperienced developers to implement.

JSON (denoted as JavaScript Object Notation) being a lightweight data-interchange format, is easy for humans to read as well as write. It is hassle free for machines to parse and generate. JSON is a text format which is entirely language independent but practices conventions that are acquainted to programmers of the family of languages, consisting of C#, C, C++, Java, Perl, JavaScript, Python, and numerous others. Such properties make JSON a perfect data-interchange language and a better choice to opt for.

How to go back last page

After all these awesome answers, I hope my answer finds someone and helps them out. I wrote a small service to keep track of route history. Here it goes.

import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';

@Injectable()
export class RouteInterceptorService {
  private _previousUrl: string;
  private _currentUrl: string;
  private _routeHistory: string[];

  constructor(router: Router) {
    this._routeHistory = [];
    router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
        this._setURLs(event);
      });
  }

  private _setURLs(event: NavigationEnd): void {
    const tempUrl = this._currentUrl;
    this._previousUrl = tempUrl;
    this._currentUrl = event.urlAfterRedirects;
    this._routeHistory.push(event.urlAfterRedirects);
  }

  get previousUrl(): string {
    return this._previousUrl;
  }

  get currentUrl(): string {
    return this._currentUrl;
  }

  get routeHistory(): string[] {
    return this._routeHistory;
  }
}

How to return value from Action()?

Your static method should go from:

public static class SimpleUsing
{
    public static void DoUsing(Action<MyDataContext> action)
    {
        using (MyDataContext db = new MyDataContext())
           action(db);
    }
}

To:

public static class SimpleUsing
{
    public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action)
    {
        using (MyDataContext db = new MyDataContext())
           return action(db);
    }
}

This answer grew out of comments so I could provide code. For a complete elaboration, please see @sll's answer below.

How to set tint for an image view programmatically in android?

Adding to ADev's answer (which in my opinion is the most correct), since the widespread adoption of Kotlin, and its useful extension functions:

fun ImageView.setTint(context: Context, @ColorRes colorId: Int) {
    val color = ContextCompat.getColor(context, colorId)
    val colorStateList = ColorStateList.valueOf(color)
    ImageViewCompat.setImageTintList(this, colorStateList)
}

I think this is a function which could be useful to have in any Android project!

Delete topic in Kafka 0.8.1.1

This steps will delete all topics and data

  • Stop Kafka-server and Zookeeper-server
  • Remove the tmp data directories of both services, by default they are C:/tmp/kafka-logs and C:/tmp/zookeeper.
  • then start Zookeeper-server and Kafka-server

How to check edittext's text is email address or not?

/**
 * method is used for checking valid email id format.
 * 
 * @param email
 * @return boolean true for valid false for invalid
 */
public static boolean isEmailValid(String email) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

Pass your edit text string in this function .

for right email verification you need server side authentication


Note there is now a built-in method in Android, see answers below.

Array slices in C#

For byte arrays System.Buffer.BlockCopy will give you the very best performance.

C# compiler error: "not all code paths return a value"

I also experienced this problem and found the easy solution to be

public string ReturnValues()
{
    string _var = ""; // Setting an innitial value

    if (.....)  // Looking at conditions
    {
        _var = "true"; // Re-assign the value of _var
    }

    return _var; // Return the value of var
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

Check for internet connection with Swift

Updated version of @martin's answer for Swift 5+ using Combine. This one also includes unavailibity reason check for iOS 14.

import Combine
import Network

enum NetworkType {
    case wifi
    case cellular
    case loopBack
    case wired
    case other
}

final class ReachabilityService: ObservableObject {

    @Published var reachabilityInfos: NWPath?
    @Published var isNetworkAvailable: Bool?
    @Published var typeOfCurrentConnection: NetworkType?

    private let monitor = NWPathMonitor()
    private let backgroundQueue = DispatchQueue.global(qos: .background)

    init() {
        setUp()
    }

    init(with interFaceType: NWInterface.InterfaceType) {
        setUp()
    }

    deinit {
        monitor.cancel()
    }
}

private extension ReachabilityService {

    func setUp() {

        monitor.pathUpdateHandler = { [weak self] path in
            self?.reachabilityInfos = path
            switch path.status {
            case .satisfied:
                print("ReachabilityService: satisfied")
                self?.isNetworkAvailable = true
                break
            case .unsatisfied:
                print("ReachabilityService: unsatisfied")

                if #available(iOS 14.2, *) {
                    switch path.unsatisfiedReason {

                    case .notAvailable:
                        print("ReachabilityService: unsatisfiedReason: notAvailable")
                        break
                    case .cellularDenied:
                        print("ReachabilityService: unsatisfiedReason: cellularDenied")
                        break
                    case .wifiDenied:
                        print("ReachabilityService: unsatisfiedReason: wifiDenied")
                        break
                    case .localNetworkDenied:
                        print("ReachabilityService: unsatisfiedReason: localNetworkDenied")
                        break
                    @unknown default:
                        print("ReachabilityService: unsatisfiedReason: default")
                    }
                } else {
                    // Fallback on earlier versions
                }

                self?.isNetworkAvailable = false
                break
            case .requiresConnection:
                print("ReachabilityService: requiresConnection")
                self?.isNetworkAvailable = false
                break
            @unknown default:
                print("ReachabilityService: default")
                self?.isNetworkAvailable = false
            }
            if path.usesInterfaceType(.wifi) {
                self?.typeOfCurrentConnection = .wifi
            } else if path.usesInterfaceType(.cellular) {
                self?.typeOfCurrentConnection = .cellular
            } else if path.usesInterfaceType(.loopback) {
                self?.typeOfCurrentConnection = .loopBack
            } else if path.usesInterfaceType(.wiredEthernet) {
                self?.typeOfCurrentConnection = .wired
            } else if path.usesInterfaceType(.other) {
                self?.typeOfCurrentConnection = .other
            }
        }

        monitor.start(queue: backgroundQueue)
    }
}

Usage:

In your view model:

private let reachability = ReachabilityService()

init() {
    reachability.$isNetworkAvailable.sink { [weak self] isConnected in
        self?.isConnected = isConnected ?? false
    }.store(in: &cancelBag)
}

In your controller:

viewModel.$isConnected.sink { [weak self] isConnected in
    print("isConnected: \(isConnected)")
    DispatchQueue.main.async {
        //Update your UI in here
    }
}.store(in: &bindings)

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


Datetime format Issue: String was not recognized as a valid DateTime

change the culture and try out like this might work for you

string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00", 
     formats, new CultureInfo("en-US"), DateTimeStyles.None);

Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application/javascript is the correct type to use but since it's not supported by IE6-8 you're going to be stuck with text/javascript. If you don't care about validity (HTML5 excluded) then just don't specify a type.

How to add custom method to Spring Data JPA

Considering your code snippet, please note that you can only pass Native objects to the findBy### method, lets say you want to load a list of accounts that belongs certain costumers, one solution is to do this,

@Query("Select a from Account a where a."#nameoffield"=?1")
List<Account> findByCustomer(String "#nameoffield");

Make sue the name of the table to be queried is thesame as the Entity class. For further implementations please take a look at this

split python source code into multiple files?

You can do the same in python by simply importing the second file, code at the top level will run when imported. I'd suggest this is messy at best, and not a good programming practice. You would be better off organizing your code into modules

Example:

F1.py:

print "Hello, "
import f2

F2.py:

print "World!"

When run:

python ./f1.py
Hello, 
World!

Edit to clarify: The part I was suggesting was "messy" is using the import statement only for the side effect of generating output, not the creation of separate source files.

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

How to get a product's image in Magento?

echo $_product->getImageUrl();

This method of the Product class should do the trick for you.

Setting UILabel text to bold

Use font property of UILabel:

label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)

or use default system font to bold text:

label.font = UIFont.boldSystemFont(ofSize: 16.0)

setup android on eclipse but don't know SDK directory

You can search your hard drive for one of the programs that's installed with the SDK. For instance, if you search for aapt.exe or adb.exe, they will be in the platform-tools directory underneath the installation directory (which is what you're after).

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

Sounds like you need to grant the execute permission to the user (or a group that they a part of) for the stored procedure in question.

For example, you could grant access thus:

USE zzzzzzz;
GRANT EXEC ON dbo.xxxxxxx TO PUBLIC

CSS Background Image Not Displaying

Its always good to have these additional properties besides the

background-image:url('path') no-repeat 0 0;

  1. set dimension to the element

    width:x; height:y;

  2. background-size:100%

    • This property helps to fit the image to the above dimension that you define for an element.

Where will log4net create this log file?

it will create the file in the root directory of your project/solution.

You can specify a location of choice in the web.config of your app as follows:

   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:/ServiceLogs/Olympus.Core.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value=".yyyyMMdd.log" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.RollingFileAppender+MinimalLock" />
      <maxSizeRollBackups value="-1" />
      <countDirection value="1" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level [%thread] %logger - %message%newline%exception" />
      </layout>
    </appender>

the file tag specifies the location.

Run reg command in cmd (bat file)?

You will probably get an UAC prompt when importing the reg file. If you accept that, you have more rights.

Since you are writing to the 'policies' key, you need to have elevated rights. This part of the registry protected, because it contains settings that are administered by your system administrator.

Alternatively, you may try to run regedit.exe from the command prompt.

regedit.exe /S yourfile.reg

.. should silently import the reg file. See RegEdit Command Line Options Syntax for more command line options.

Install apps silently, with granted INSTALL_PACKAGES permission

I have checked how ADB installs apps.
- It copies the APK to /data/local/tmp
- it runs 'shell:pm install /data/local/tmp/app.apk'

I have tried to replicate this behaviour by doing: (on pc, using usb-cable)
adb push app.apk /sdcard/app.apk
adb shell
$ pm install /sdcard/app.apk
This works. The app is installed.

I made an application (named AppInstall) which should install the other app.
(installed normally, non-rooted device)
It does:
Runtime.getRuntime().exec("pm install /sdcard/app.apk").waitFor();
But this gives the error:
java.lang.SecurityException: Neither user 10019 nor current process has android.permission.INSTALL_PACKAGES.
It seems like the error is thrown by pm, not by AppInstall.
Because the SecurityException is not catched by AppInstall and the app does not crash.

I've tried the same thing on a rooted device (same app and AppInstall) and it worked like a charm.
(Also normally installed, not in /system or anything)
AppInstall didn't even ask root-permission.
But thats because the shell is always # instead of $ on that device.

Btw, you need root to install an app in /system, correct?
I tried adb remount on the non-rooted device and got:
remount failed: Operation not permitted.
That's why I could not try the /system thing on the non-rooted device.

Conclusion: you should use a rooted device
Hope this helps :)

process.waitFor() never returns

For the same reason you can also use inheritIO() to map Java console with external app console like:

ProcessBuilder pb = new ProcessBuilder(appPath, arguments);

pb.directory(new File(appFile.getParent()));
pb.inheritIO();

Process process = pb.start();
int success = process.waitFor();

Passing parameter to controller action from a Html.ActionLink

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

iOS change navigation bar title font and color

There is nothing wrong with the other answers. I'm just sharing the storyboard version for setting the font.

1. Select Your Navigation Bar within your Navigation Controller

navbar

2. Change the Title Font in the Attributes Inspector

title-font

(You will likely need to toggle the Bar Tint for the Navigation Bar before Xcode picks up the new font)

Notes (Caveats)

Verified that this does work on Xcode 7.1.1+. (See the Samples below)

  1. You do need to toggle the nav bar tint before the font takes effect (seems like a bug in Xcode; you can switch it back to default and font will stick)
  2. If you choose a system font ~ Be sure to make sure the size is not 0.0 (Otherwise the new font will be ignored)

size

  1. Seems like this works with no problem when only one NavBar is in the view hierarchy. It appears that secondary NavBars in the same stack are ignored. (Note that if you show the master navigation controller's navBar all the other custom navBar settings are ignored).

Gotchas (deux)

Some of these are repeated which means they are very likely worth noting.

  1. Sometimes the storyboard xml gets corrupt. This requires you to review the structure in Storyboard as Source Code mode (right click the storyboard file > Open As ...)
  2. In some cases the navigationItem tag associated with user defined runtime attribute was set as an xml child of the view tag instead of the view controller tag. If so remove it from between the tags for proper operation.
  3. Toggle the NavBar Tint to ensure the custom font is used.
  4. Verify the size parameter of the font unless using a dynamic font style
  5. View hierarchy will override the settings. It appears that one font per stack is possible.

Result

navbar-italic

Samples

Handling Custom Fonts

Note ~ A nice checklist can be found from the Code With Chris website and you can see the sample download project.

If you have your own font and want to use that in your storyboard, then there is a decent set of answers on the following SO Question. One answer identifies these steps.

  1. Get you custom font file(.ttf,.ttc)
  2. Import the font files to your Xcode project
  3. In the app-info.plist,add a key named Fonts provided by application.It's an array type , add all your font file names to the array,note:including the file extension.
  4. In the storyboard , on the NavigationBar go to the Attribute Inspector,click the right icon button of the Font select area.In the popup panel , choose Font to Custom, and choose the Family of you embeded font name.

Custom Font Workaround

So Xcode naturally looks like it can handle custom fonts on UINavigationItem but that feature is just not updating properly (The font selected is ignored).

UINavigationItem

To workaround this:

One way is to fix using the storyboard and adding a line of code: First add a UIView (UIButton, UILabel, or some other UIView subclass) to the View Controller (Not the Navigation Item...Xcode is not currently allowing one to do that). After you add the control you can modify the font in the storyboard and add a reference as an outlet to your View Controller. Just assign that view to the UINavigationItem.titleView. You could also set the text name in code if necessary. Reported Bug (23600285).

@IBOutlet var customFontTitleView: UIButton!

//Sometime later...    
self.navigationItem.titleView = customFontTitleView

GIT clone repo across local file system in windows

Maybe map the share as a network drive and then do

git clone Z:\

Mostly just a guess; I always do this stuff using ssh. Following that suggstion of course will mean that you'll need to have that drive mapped every time you push/pull to/from the laptop. I'm not sure how you rig up ssh to work under windows but if you're going to be doing this a lot it might be worth investigating.

How to run python script with elevated privilege on windows

I found a very easy solution to this problem.

  1. Create a shortcut for python.exe
  2. Change the shortcut target into something like C:\xxx\...\python.exe your_script.py
  3. Click "advance..." in the property panel of the shortcut, and click the option "run as administrator"

I'm not sure whether the spells of these options are right, since I'm using Chinese version of Windows.

How to use npm with node.exe?

I am running node.js on Windows with npm. The trick is simply use cygwin. I followed the howto under https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows) . But make sure that you use version 0.4.11 of nodejs or npm will fail!

Close Window from ViewModel

It's simple. You can create your own ViewModel class for Login - LoginViewModel. You can create view var dialog = new UserView(); inside your LoginViewModel. And you can set-up Command LoginCommand into button.

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding LoginCommand}" />

and

<Button Name="btnCancel" IsDefault="True" Content="Login" Command="{Binding CancelCommand}" />

ViewModel class:

public class LoginViewModel
{
    Window dialog;
    public bool ShowLogin()
    {
       dialog = new UserView();
       dialog.DataContext = this; // set up ViewModel into View
       if (dialog.ShowDialog() == true)
       {
         return true;
       }

       return false;
    }

    ICommand _loginCommand
    public ICommand LoginCommand
    {
        get
        {
            if (_loginCommand == null)
                _loginCommand = new RelayCommand(param => this.Login());

            return _loginCommand;
        }
    }

    public void CloseLoginView()
    {
            if (dialog != null)
          dialog.Close();
    }   

    public void Login()
    {
        if(CheckLogin()==true)
        {
            CloseLoginView();         
        }
        else
        {
          // write error message
        }
    }

    public bool CheckLogin()
    {
      // ... check login code
      return true;
    }
}

Git - Undo pushed commits

You can do something like

git push origin +<short_commit_sha>^:<branch_name>

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

From comments I picked an answer like and also adding TimeZone:

String dateTime = "2015-07-18T13:32:56.971-0400";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
        .withLocale(Locale.ROOT)
        .withChronology(ISOChronology.getInstanceUTC());

DateTime dt = formatter.parseDateTime(dateTime);

How do I find the width & height of a terminal window?

Inspired by @pixelbeat's answer, here's a horizontal bar brought to existence by tput, slight misuse of printf padding/filling and tr

printf "%0$(tput cols)d" 0|tr '0' '='

Why would one omit the close tag?

In addition to everything that's been said already, I'm going to throw in another reason that was a huge pain for us to debug.

Apache 2.4.6 with PHP 5.4 actually segmentation faults on our production machines when there's empty space behind the closing php tag. I just wasted hours until I finally narrowed down the bug with strace.

Here is the error that Apache throws:

[core:notice] [pid 7842] AH00052: child pid 10218 exit signal Segmentation fault (11)

Get MD5 hash of big files in Python

Implementation of accepted answer for Django:

import hashlib
from django.db import models


class MyModel(models.Model):
    file = models.FileField()  # any field based on django.core.files.File

    def get_hash(self):
        hash = hashlib.md5()
        for chunk in self.file.chunks(chunk_size=8192):
            hash.update(chunk)
        return hash.hexdigest()

Spring Test & Security: How to mock authentication?

Short answer:

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
private Filter springSecurityFilterChain;

@Before
public void setUp() throws Exception {
    final MockHttpServletRequestBuilder defaultRequestBuilder = get("/dummy-path");
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
            .defaultRequest(defaultRequestBuilder)
            .alwaysDo(result -> setSessionBackOnRequestBuilder(defaultRequestBuilder, result.getRequest()))
            .apply(springSecurity(springSecurityFilterChain))
            .build();
}

private MockHttpServletRequest setSessionBackOnRequestBuilder(final MockHttpServletRequestBuilder requestBuilder,
                                                             final MockHttpServletRequest request) {
    requestBuilder.session((MockHttpSession) request.getSession());
    return request;
}

After perform formLogin from spring security test each of your requests will be automatically called as logged in user.

Long answer:

Check this solution (the answer is for spring 4): How to login a user with spring 3.2 new mvc testing

How to check if a variable is equal to one string or another string?

if var == 'stringone' or var == 'stringtwo':
    dosomething()

'is' is used to check if the two references are referred to a same object. It compare the memory address. Apparently, 'stringone' and 'var' are different objects, they just contains the same string, but they are two different instances of the class 'str'. So they of course has two different memory addresses, and the 'is' will return False.

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

JavaFX open new window

The code below worked for me I used part of the code above inside the button class.

public Button signupB;

public void handleButtonClick (){

    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
        /*
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 630, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }

}

}

Sequelize.js delete query?

In new version, you can try something like this

function (req,res) {    
        model.destroy({
            where: {
                id: req.params.id
            }
        })
        .then(function (deletedRecord) {
            if(deletedRecord === 1){
                res.status(200).json({message:"Deleted successfully"});          
            }
            else
            {
                res.status(404).json({message:"record not found"})
            }
        })
        .catch(function (error){
            res.status(500).json(error);
        });

C++ - Assigning null to a std::string

Many C APIs use a null pointer to indicate "use the default", e.g. mosquittopp. Here is the pattern I am using, based on David Cormack's answer:

    mosqpp::tls_set(
        MqttOptions->CAFile.length() > 0 ? MqttOptions->CAFile.c_str() : NULL,
        MqttOptions->CAPath.length() > 0 ? MqttOptions->CAPath.c_str() : NULL,
        MqttOptions->CertFile.length() > 0 ? MqttOptions->CertFile.c_str() : NULL,
        MqttOptions->KeyFile.length() > 0 ? MqttOptions->KeyFile.c_str() : NULL
    );

It is a little cumbersome, but allows one to keep everything as a std::string up until the API call itself.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Set a button group's width to 100% and make buttons equal width?

Angular - equal width button group

Assuming you have an array of 'things' in your scope...

  • Make sure the parent div has a width of 100%.
  • Use ng-repeat to create the buttons within the button group.
  • Use ng-style to calculate the width for each button.

<div class="btn-group"
     style="width: 100%;">
    <button ng-repeat="thing in things"
            class="btn btn-default"
            ng-style="{width: (100/things.length)+'%'}">
        {{thing}}
    </button>
</div>

How to escape single quotes in MySQL

In PHP, use mysqli_real_escape_string.

Example from the PHP Manual:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

Input jQuery get old value before onchange and get value after on change

my solution is here

function getVal() {
    var $numInput =  $('input');
    var $inputArr = [];
    for(let i=0; i < $numInput.length ; i++ ) 
       $inputArr[$numInput[i].name] = $numInput[i].value;
    return $inputArr;
}
var $inNum =  getVal();
$('input').on('change', function() {
    // inNum is last Val
    $inNum =  getVal(); 
    // in here we update value of input
    let $val = this.value;      
});

Cannot drop database because it is currently in use

A brute force workaround could be:

  1. Stop the SQL Server Service.

  2. Delete the corresponding .mdf and .ldf files.

  3. Start the SQL Server Service.

  4. Connect with SSMS and delete the database.

How to get height of entire document with JavaScript?

I lied, jQuery returns the correct value for both pages $(document).height();... why did I ever doubt it?

GIT vs. Perforce- Two VCS will enter... one will leave

What Perforce features are people using?

  • Multiple workspaces on a single machine
  • Numbered changelists
  • Developer branches
  • Integration with IDE (Visual Studio, Eclipse, SlickEdit, ...)
  • Many build variants
  • Composite workspaces
  • Integrating some fixes but not others
  • etc

I ask because if all folks are doing is get and put from the command line, git has that covered, and so do all the other RTS.

Where is android studio building my .apk file?

When Gradle builds your project, it puts all APKs in build/apk directory. You could also just do a simple recursive find command for *.apk in the top level directory of your project.

Here is a better description...

http://i.stack.imgur.com/XwjEZ.png

View full image at http://i.stack.imgur.com/XwjEZ.png

How can I make the computer beep in C#?

You can also use the relatively unused:

    System.Media.SystemSounds.Beep.Play();
    System.Media.SystemSounds.Asterisk.Play();
    System.Media.SystemSounds.Exclamation.Play();
    System.Media.SystemSounds.Question.Play();
    System.Media.SystemSounds.Hand.Play();

Documentation for this sounds is available in http://msdn.microsoft.com/en-us/library/system.media.systemsounds(v=vs.110).aspx

Using Powershell to stop a service remotely without WMI or remoting

This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.

**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I think the answer from cheez (https://stackoverflow.com/users/122933/cheez) is the easiest and most effective one. I'd elaborate a little bit over it so it would not modify a numpy function for the whole session period.

My suggestion is below. I´m using it to download the reuters dataset from keras which is showing the same kind of error:

old = np.load
np.load = lambda *a,**k: old(*a,**k,allow_pickle=True)

from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)

np.load = old
del(old)

What is sys.maxint in Python 3?

Python 3 ints do not have a maximum.

If your purpose is to determine the maximum size of an int in C when compiled the same way Python was, you can use the struct module to find out:

>>> import struct
>>> platform_c_maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1

If you are curious about the internal implementation details of Python 3 int objects, Look at sys.int_info for bits per digit and digit size details. No normal program should care about these.

Rails - How to use a Helper Inside a Controller

In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController.

Print Currency Number Format in PHP

From the docs

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

How to restart Postgresql

You can also restart postgresql by using this command, should work on both the versions :

sudo service postgresql start

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is crypted with password_hash function.

$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);

Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.

First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.

Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.

Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:

$sql_script = 'select * from USERS where password="'.$digested_password.'"'

Fourth, profit.

So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...

Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.

ASP.NET - How to write some html in the page? With Response.Write?

If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:

<body>
<% Response.Write(stringVariable); %>
</body>

A shorthand for this syntax is:

<body>
<%= stringVariable %>
</body>

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

Swift Open Link in Safari

New with iOS 9 and higher you can present the user with a SFSafariViewController (see documentation here). Basically you get all the benefits of sending the user to Safari without making them leave your app. To use the new SFSafariViewController just:

import SafariServices

and somewhere in an event handler present the user with the safari view controller like this:

let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)

The safari view will look something like this:

enter image description here

SQL Add foreign key to existing column

Maybe you got your columns backwards??

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)           <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id)   <-- this needs to be a column of the ActiveDirectories table

Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?

Then your command should be:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)
{

    var args = {};
    args.PostID = val;
    args.Comment = comment;

    $.ajax({
     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
     {
        // Something afterwards here

     }
    });

}

MySQL DROP all tables, ignoring foreign keys

From http://www.devdaily.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys:

SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;

(Note that this answers how to disable foreign key checks in order to be able to drop the tables in arbitrary order. It does not answer how to automatically generate drop-table statements for all existing tables and execute them in a single script. Jean's answer does.)

Return multiple fields as a record in PostgreSQL with PL/pgSQL

You need to define a new type and define your function to return that type.

CREATE TYPE my_type AS (f1 varchar(10), f2 varchar(10) /* , ... */ );

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
RETURNS my_type 
AS 
$$

DECLARE
  result_record my_type;

BEGIN
  SELECT f1, f2, f3
  INTO result_record.f1, result_record.f2, result_record.f3
  FROM table1
  WHERE pk_col = 42;

  SELECT f3 
  INTO result_record.f3
  FROM table2
  WHERE pk_col = 24;

  RETURN result_record;

END
$$ LANGUAGE plpgsql; 

If you want to return more than one record you need to define the function as returns setof my_type


Update

Another option is to use RETURNS TABLE() instead of creating a TYPE which was introduced in Postgres 8.4

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
  RETURNS TABLE (f1 varchar(10), f2 varchar(10) /* , ... */ )
...

Change a web.config programmatically with C# (.NET)

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
//section.SectionInformation.UnprotectSection();
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

In our case, the problem was with federated signon between a .Net site and ADFS. When redirecting to the ADFS endpoint the wctx parameter needed all three parameters for the WSFederationAuthenticationModule.CreateSignInRequest method: rm, id, and ru

Thanks to Guillaume Raymond for the tip to check the URL parameters!

Regex to validate date format dd/mm/yyyy

Here I wrote one for dd/mm/yyyy where separator can be one of -.,/ year range 0000-9999.

It deals with leap years and is designed for regex flavors, that support lookaheads, capturing groups and backreferences. NOT valid for such as d/m/yyyy. If needed add further separators to [-.,/]

^(?=\d{2}([-.,\/])\d{2}\1\d{4}$)(?:0[1-9]|1\d|[2][0-8]|29(?!.02.(?!(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)\d{2}(?:[02468][048]|[13579][26])))|30(?!.02)|31(?=.(?:0[13578]|10|12))).(?:0[1-9]|1[012]).\d{4}$

Test at regex101; as a Java string:

"^(?=\\d{2}([-.,\\/])\\d{2}\\1\\d{4}$)(?:0[1-9]|1\\d|[2][0-8]|29(?!.02.(?!(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)\\d{2}(?:[02468][048]|[13579][26])))|30(?!.02)|31(?=.(?:0[13578]|10|12))).(?:0[1-9]|1[012]).\\d{4}$"

explained:

(?x) # modifier x: free spacing mode (for comments)
     # verify date dd/mm/yyyy; possible separators: -.,/
     # valid year range: 0000-9999

^    # start anchor

# precheck xx-xx-xxxx,... add new separators here
(?=\d{2}([-.,\/])\d{2}\1\d{4}$)

(?:  # day-check: non caturing group

  # days 01-28
  0[1-9]|1\d|[2][0-8]| 

  # february 29d check for leap year: all 4y / 00 years: only each 400
  # 0400,0800,1200,1600,2000,...
  29
  (?!.02. # not if feb: if not ...
    (?!
      # 00 years: exclude !0 %400 years
      (?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)

      # 00,04,08,12,... 
      \d{2}(?:[02468][048]|[13579][26])
    )
  )|

  # d30 negative lookahead: february cannot have 30 days
  30(?!.02)|

  # d31 positive lookahead: month up to 31 days
  31(?=.(?:0[13578]|10|12))

) # eof day-check

# month 01-12
.(?:0[1-9]|1[012])

# year 0000-9999
.\d{4}

$ # end anchor

Also see SO Regex FAQ; Please let me know, if it fails.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

How do I import material design library to Android Studio?

First, add the Material Design dependency.

implementation 'com.google.android.material:material:<version>'

To get the latest material design library version. check the official website github repository.

Current version is 1.2.0.

So, you have to add,

implementation 'com.google.android.material:material:1.2.0'

Then, you need to change the app theme to material theme by adding,

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

in your style.xml. Dont forget to set the same theme in your application theme in your manifest file.

How to add parameters to a HTTP GET request in Android?

    HttpClient client = new DefaultHttpClient();

    Uri.Builder builder = Uri.parse(url).buildUpon();

    for (String name : params.keySet()) {
        builder.appendQueryParameter(name, params.get(name).toString());
    }

    url = builder.build().toString();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    return EntityUtils.toString(response.getEntity(), "UTF-8");

Making sure at least one checkbox is checked

This should work:

function valthisform()
{
    var checkboxs=document.getElementsByName("c1");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
            break;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}

If you have a question about the code, just comment.


I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

How can I create an editable dropdownlist in HTML?

A little CSS and you are done fiddle

<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2"  style="width: 140px;
    position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
        <div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
    onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
    top: 0px; left: 0px; z-index: 1; width: 165px;">
    <option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>
</select>

Align two divs horizontally side by side center to the page using bootstrap css

<div class="container">
    <div class="row">
       <div class="col-xs-6 col-sm-6 col-md-6">
          First Div
       </div>
       <div class="col-xs-6 col-sm-6 col-md-6">
          Second Div
       </div>
   </div>

This does the trick.

How to modify list entries during for loop?

One more for loop variant, looks cleaner to me than one with enumerate():

for idx in range(len(list)):
    list[idx]=... # set a new value
    # some other code which doesn't let you use a list comprehension

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

How can I mock an ES6 module import using Jest?

The claims that you have to mock it at the top of your file are false.

Mock a named ES Import:

// import the named module
import { useWalkthroughAnimations } from '../hooks/useWalkthroughAnimations';

// mock the file and its named export
jest.mock('../hooks/useWalkthroughAnimations', () => ({
  useWalkthroughAnimations: jest.fn()
}));

// do whatever you need to do with your mocked function
useWalkthroughAnimations.mockReturnValue({ pageStyles, goToNextPage, page });

npm WARN package.json: No repository field

If you don't want to specify a repository you can add the following lines to the package.json file:

"description":"",
"version":"0.0.1",
"private":true,

That worked for me.
By adding private, you don't need to link to a repo.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

For flutter projects you can also solve this issue

open your \android\app\build.gradle

you sould have the following:

android {
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28

    }

}

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in the defaultConfig. Like this

android {
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true 

    }

}

if your minSdkVersion is set to 20 or lower add multiDexEnabled true to the defaultConfig

And define the implementation

dependencies {
  implementation 'com.android.support:multidex:1.0.3'// or 2.0.1
}

At the end you should have:

android {
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true  // added this
    }

}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

For more information read this: https://developer.android.com/studio/build/multidex

Good Java graph algorithm library?

Instructional graph algorithm implementations in java could be found here (by prof. Sedgewick et al.): http://algs4.cs.princeton.edu/code/

I was introduced to them while attending these exceptional algorithm courses on coursera (also taught by prof. Sedgewick):

https://www.coursera.org/course/algs4partI

https://www.coursera.org/course/algs4partII

Difference between java HH:mm and hh:mm on SimpleDateFormat

Use the built-in localized formats

If this is for showing a time of day to a user, then in at least 19 out of 20 you don’t need to care about kk, HH nor hh. I suggest that you use something like this:

    DateTimeFormatter defaultTimeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    System.out.format("%s: %s%n",
            Locale.getDefault(), LocalTime.MIN.format(defaultTimeFormatter));

The point is that it gives different output in different default locales. For example:

en_SS: 12:00 AM
fr_BL: 00:00
ps_AF: 0:00
es_CO: 12:00 a.m.

The localized formats have been designed to conform with the expectations of different cultures. So they generally give the user a better experience and they save you of writing a format pattern string, which is always error-prone.

I furthermore suggest that you don’t use SimpleDateFormat. That class is notoriously troublesome and fortunately long outdated. Instead I use java.time, the modern Java date and time API. It is so much nicer to work with.

Four pattern letters for hour: H, h, k and K

Of course if you need to parse a string with a specified format, and also if you have a very specific formatting requirement, it’s good to use a format pattern string. There are actually four different pattern letters to choose from for hour (quoted from the documentation):

  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-day (1-24)    number            24
   H       hour-of-day (0-23)          number            0

In practice H and h are used. As far as I know k and K are not (they may just have been included for the sake of completeness). But let’s just see them all in action:

    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofPattern("hh:mm a  HH:mm  kk:mm  KK:mm a", Locale.ENGLISH);
    System.out.println(LocalTime.of(0, 0).format(timeFormatter));
    System.out.println(LocalTime.of(1, 15).format(timeFormatter));
    System.out.println(LocalTime.of(11, 25).format(timeFormatter));
    System.out.println(LocalTime.of(12, 35).format(timeFormatter));
    System.out.println(LocalTime.of(13, 40).format(timeFormatter));
12:00 AM  00:00  24:00  00:00 AM
01:15 AM  01:15  01:15  01:15 AM
11:25 AM  11:25  11:25  11:25 AM
12:35 PM  12:35  12:35  00:35 PM
01:40 PM  13:40  13:40  01:40 PM

If you don’t want the leading zero, just specify one pattern letter, that is h instead of hh or H instead of HH. It will still accept two digits when parsing, and if a number to be printed is greater than 9, two digits will still be printed.

Links

Create a List that contain each Line of a File

A file is almost a list of lines. You can trivially use it in a for loop.

myFile= open( "SomeFile.txt", "r" )
for x in myFile:
    print x
myFile.close()

Or, if you want an actual list of lines, simply create a list from the file.

myFile= open( "SomeFile.txt", "r" )
myLines = list( myFile )
myFile.close()
print len(myLines), myLines

You can't do someList[i] to put a new item at the end of a list. You must do someList.append(i).

Also, never start a simple variable name with an uppercase letter. List confuses folks who know Python.

Also, never use a built-in name as a variable. list is an existing data type, and using it as a variable confuses folks who know Python.

Sorting a Dictionary in place with respect to keys

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

Unclosed Character Literal error

'' encloses single char, while "" encloses a String.

Change

y = 'hello';

-->

y = "hello";

Creating a JSON dynamically with each input value using jquery

Like this:

function createJSON() {
    jsonObj = [];
    $("input[class=email]").each(function() {

        var id = $(this).attr("title");
        var email = $(this).val();

        item = {}
        item ["title"] = id;
        item ["email"] = email;

        jsonObj.push(item);
    });

    console.log(jsonObj);
}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 

What is the difference between i++ and ++i?

The typical answer to this question, unfortunately posted here already, is that one does the increment "before" remaining operations and the other does the increment "after" remaining operations. Though that intuitively gets the idea across, that statement is on the face of it completely wrong. The sequence of events in time is extremely well-defined in C#, and it is emphatically not the case that the prefix (++var) and postfix (var++) versions of ++ do things in a different order with respect to other operations.

It is unsurprising that you'll see a lot of wrong answers to this question. A great many "teach yourself C#" books also get it wrong. Also, the way C# does it is different than how C does it. Many people reason as though C# and C are the same language; they are not. The design of the increment and decrement operators in C# in my opinion avoids the design flaws of these operators in C.

There are two questions that must be answered to determine what exactly the operation of prefix and postfix ++ are in C#. The first question is what is the result? and the second question is when does the side effect of the increment take place?

It is not obvious what the answer to either question is, but it is actually quite simple once you see it. Let me spell out for you precisely what x++ and ++x do for a variable x.

For the prefix form (++x):

  1. x is evaluated to produce the variable
  2. The value of the variable is copied to a temporary location
  3. The temporary value is incremented to produce a new value (not overwriting the temporary!)
  4. The new value is stored in the variable
  5. The result of the operation is the new value (i.e. the incremented value of the temporary)

For the postfix form (x++):

  1. x is evaluated to produce the variable
  2. The value of the variable is copied to a temporary location
  3. The temporary value is incremented to produce a new value (not overwriting the temporary!)
  4. The new value is stored in the variable
  5. The result of the operation is the value of the temporary

Some things to notice:

First, the order of events in time is exactly the same in both cases. Again, it is absolutely not the case that the order of events in time changes between prefix and postfix. It is entirely false to say that the evaluation happens before other evaluations or after other evaluations. The evaluations happen in exactly the same order in both cases as you can see by steps 1 through 4 being identical. The only difference is the last step - whether the result is the value of the temporary, or the new, incremented value.

You can easily demonstrate this with a simple C# console app:

public class Application
{
    public static int currentValue = 0;

    public static void Main()
    {
        Console.WriteLine("Test 1: ++x");
        (++currentValue).TestMethod();

        Console.WriteLine("\nTest 2: x++");
        (currentValue++).TestMethod();

        Console.WriteLine("\nTest 3: ++x");
        (++currentValue).TestMethod();

        Console.ReadKey();
    }
}

public static class ExtensionMethods 
{
    public static void TestMethod(this int passedInValue) 
    {
        Console.WriteLine("Current:{0} Passed-in:{1}",
            Application.currentValue,
            passedInValue);
    }
}

Here are the results...

Test 1: ++x
Current:1 Passed-in:1

Test 2: x++
Current:2 Passed-in:1

Test 3: ++x
Current:3 Passed-in:3

In the first test, you can see that both currentValue and what was passed in to the TestMethod() extension show the same value, as expected.

However, in the second case, people will try to tell you that the increment of currentValue happens after the call to TestMethod(), but as you can see from the results, it happens before the call as indicated by the 'Current:2' result.

In this case, first the value of currentValue is stored in a temporary. Next, an incremented version of that value is stored back in currentValue but without touching the temporary which still stores the original value. Finally that temporary is passed to TestMethod(). If the increment happened after the call to TestMethod() then it would write out the same, non-incremented value twice, but it does not.

It's important to note that the value returned from both the currentValue++ and ++currentValue operations are based on the temporary and not the actual value stored in the variable at the time either operation exits.

Recall in the order of operations above, the first two steps copy the then-current value of the variable into the temporary. That is what's used to calculate the return value; in the case of the prefix version, it's that temporary value incremented while in the case of the suffix version, it's that value directly/non-incremented. The variable itself is not read again after the initial storage into the temporary.

Put more simply, the postfix version returns the value that was read from the variable (i.e. the value of the temporary) while the prefix version returns the value that was written back to the variable (i.e. the incremented value of the temporary). Neither return the variable's value.

This is important to understand because the variable itself could be volatile and have changed on another thread which means the return value of those operations could differ from the current value stored in the variable.

It is surprisingly common for people to get very confused about precedence, associativity, and the order in which side effects are executed, I suspect mostly because it is so confusing in C. C# has been carefully designed to be less confusing in all these regards. For some additional analysis of these issues, including me further demonstrating the falsity of the idea that prefix and postfix operations "move stuff around in time" see:

https://ericlippert.com/2009/08/10/precedence-vs-order-redux/

which led to this SO question:

int[] arr={0}; int value = arr[arr[0]++]; Value = 1?

You might also be interested in my previous articles on the subject:

https://ericlippert.com/2008/05/23/precedence-vs-associativity-vs-order/

and

https://ericlippert.com/2007/08/14/c-and-the-pit-of-despair/

and an interesting case where C makes it hard to reason about correctness:

https://docs.microsoft.com/archive/blogs/ericlippert/bad-recursion-revisited

Also, we run into similar subtle issues when considering other operations that have side effects, such as chained simple assignments:

https://docs.microsoft.com/archive/blogs/ericlippert/chaining-simple-assignments-is-not-so-simple

And here's an interesting post on why the increment operators result in values in C# rather than in variables:

Why can't I do ++i++ in C-like languages?

Can I use GDB to debug a running process?

Yes. Use the attach command. Check out this link for more information. Typing help attach at a GDB console gives the following:

(gdb) help attach

Attach to a process or file outside of GDB. This command attaches to another target, of the same type as your last "target" command ("info files" will show your target stack). The command may take as argument a process id, a process name (with an optional process-id as a suffix), or a device file. For a process id, you must have permission to send the process a signal, and it must have the same effective uid as the debugger. When using "attach" to an existing process, the debugger finds the program running in the process, looking first in the current working directory, or (if not found there) using the source file search path (see the "directory" command). You can also use the "file" command to specify the program, and to load its symbol table.


NOTE: You may have difficulty attaching to a process due to improved security in the Linux kernel - for example attaching to the child of one shell from another.

You'll likely need to set /proc/sys/kernel/yama/ptrace_scope depending on your requirements. Many systems now default to 1 or higher.

The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other
    process running under the same uid, as long as it is dumpable (i.e.
    did not transition uids, start privileged, or have called
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is
    unchanged.

1 - restricted ptrace: a process must have a predefined relationship
    with the inferior it wants to call PTRACE_ATTACH on. By default,
    this relationship is that of only its descendants when the above
    classic criteria is also met. To change the relationship, an
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare
    an allowed debugger PID to call PTRACE_ATTACH on the inferior.
    Using PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

Why check both isset() and !empty()

if we use same page to add/edit via submit button like below

<input type="hidden" value="<?echo $_GET['edit_id'];?>" name="edit_id">

then we should not use

isset($_POST['edit_id'])

bcoz edit_id is set all the time whether it is add or edit page , instead we should use check below condition

!empty($_POST['edit_id'])

TimeStamp on file name using PowerShell

Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

[string]$filePath = "C:\tempFile.zip";

[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);

Move-Item -LiteralPath $filePath -Destination $newFilePath;

Differences between key, superkey, minimal superkey, candidate key and primary key

Candidate Key: The candidate key can be defined as minimal set of attribute which can uniquely identify a tuple is known as candidate key. For Example, STUD_NO in below STUDENT relation.

  • The value of Candidate Key is unique and non-null for every tuple.
  • There can be more than one candidate key in a relation. For Example, STUD_NO as well as STUD_PHONE both are candidate keys for relation STUDENT.
  • The candidate key can be simple (having only one attribute) or composite as well. For Example, {STUD_NO, COURSE_NO} is a composite
    candidate key for relation STUDENT_COURSE.

enter image description here

Super Key: The set of attributes which can uniquely identify a tuple is known as Super Key. For Example, STUD_NO, (STUD_NO, STUD_NAME) etc. Adding zero or more attributes to candidate key generates super key. A candidate key is a super key but vice versa is not true. Primary Key: There can be more than one candidate key in a relation out of which one can be chosen as primary key. For Example, STUD_NO as well as STUD_PHONE both are candidate keys for relation STUDENT but STUD_NO can be chosen as primary key (only one out of many candidate keys).

Alternate Key: The candidate key other than primary key is called as alternate key. For Example, STUD_NO as well as STUD_PHONE both are candidate keys for relation STUDENT but STUD_PHONE will be alternate key (only one out of many candidate keys).

Foreign Key: If an attribute can only take the values which are present as values of some other attribute, it will be foreign key to the attribute to which it refers. The relation which is being referenced is called referenced relation and corresponding attribute is called referenced attribute and the relation which refers to referenced relation is called referencing relation and corresponding attribute is called referencing attribute. Referenced attribute of referencing attribute should be primary key. For Example, STUD_NO in STUDENT_COURSE is a foreign key to STUD_NO in STUDENT relation.

Pass a variable to a PHP script running from the command line

Using getopt() function we can also read a parameter from the command line just. Pass a value with the php running command:

php abc.php --name=xyz

File abc.php

$val = getopt(null, ["name:"]);
print_r($val); // Output: ['name' => 'xyz'];

ImportError: No module named apiclient.discovery

apiclient was the original name of the library.
At some point, it was switched over to be googleapiclient.

If your code is running on Google App Engine, both should work.

If you are running the application yourself, with the google-api-python-client installed, both should work as well.

Although, if we take a look at the source code of the apiclient package's __init__.py module, we can see that the apiclient module was simply kept around for backwards-compatibility.

Retain apiclient as an alias for googleapiclient.

So, you really should be using googleapiclient in your code, since the apiclient alias was just maintained as to not break legacy code.

# bad
from apiclient.discovery import build

# good
from googleapiclient.discovery import build

How to select data where a field has a min value in MySQL?

This is how I would do it (assuming I understand the question)

SELECT * FROM pieces ORDER BY price ASC LIMIT 1

If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.

Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.

`col-xs-*` not working in Bootstrap 4

In Bootstrap 4.3, col-xs-{value} is replaced by col-{value}

There is no change in sm, md, lg, xl remains the same.

.col-{value}
.col-sm-{value}
.col-md-{value}
.col-lg-{value}
.col-xl-{value}

Dynamic Web Module 3.0 -- 3.1

I opened the project org.eclipse.wst.common.project.facet.core.xml and first changed then removed line with web module tag. Cleaned project and launched on Tomcat each time but it still didn't run. Returned line (as was) and cleaned project. Opened Tomcat settings in Eclipse and manually added project to Tomcat startup (Right click + Add and Remove). Clicked on project and selected Run on server....and everything was fine.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Tools > Manage Add-ons, right click "Name" header and enable the "In Folder" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click "remove".

The opposite of Intersect()

I'm not 100% sure what your NonIntersect method is supposed to do (regarding set theory) - is it
B \ A (everything from B that does not occur in A)?
If yes, then you should be able to use the Except operation (B.Except(A)).

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

In my case this error was raised because table date column is not null-able

As below:

Create Table #TempTable(
 ...
 ApprovalDate datatime not null.
 ...)

To avoid this error just make it null-able

 Create Table #TempTable(
 ...
 ApprovalDate datatime null.
 ...)

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Get DOS path instead of Windows path

use this link, it will automatically convert any path you give to any format https://pathconverter-pp.azurewebsites.net

How to get overall CPU usage (e.g. 57%) on Linux

Try mpstat from the sysstat package

> sudo apt-get install sysstat
Linux 3.0.0-13-generic (ws025)  02/10/2012  _x86_64_    (2 CPU)  

03:33:26 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
03:33:26 PM  all    2.39    0.04    0.19    0.34    0.00    0.01    0.00    0.00   97.03

Then some cutor grepto parse the info you need:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a

TCPDF ERROR: Some data has already been output, can't send PDF file

for my case Footer method was having malformed html code (missing td) causing error on osx.

public function Footer() {
$this->SetY(-40);
$html = <<<EOD
<table>
<tr>
 Test Data
</tr>
</table>
EOD;
$this->writeHTML($html);
}

Android Studio is slow (how to speed up)?

This might sound stupid and off topic but in my case I was using an external 4k Monitor with my MacBook Pro 13' (MacOS High Sierra, 2016) and I had the resolution set to the wrong scaled resolution. Switching to another scaled resolution where there was no "using a scaled resolution may affect performance" warning resolved my overall performance issues. In my case I had to increase the resolution to max.

So for me it was an overall performance problem which first surfaced with Android Studio, it was not an Android Studio specific problem.

EDIT 25.11.2017

As a result I had to increase font sizes in Android Studio:

enter image description here

enter image description here

and on my Mac in General. I followed some of these tips to get that done.

How to set a cookie for another domain

In case you have a.my-company.com and b.my-company.com instead of just a.com and b.com you can issue a cookie for .my-company.com domain - it will be accepted and sent to both of the domains.

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).

iPhone/iPad browser simulator?

I use mobile-browser-emulator chrome plug-in which is has iphone device types. It actually uses user-agent and size of device on which based responsive pages are rendered

Convert LocalDateTime to LocalDateTime in UTC

Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {
        super();
    }

    public static void main(final String... args) {
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime utc = DateTimeUtil.toUtc(now);

        System.out.println("Now: " + now);
        System.out.println("UTC: " + utc);
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedtime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
    }

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
    }

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
    }
}

How to check if directory exists in %PATH%?

Building on rcar's answer, you have to make sure a substring of the target isn't found.

if a%X%==a%PATH% echo %X% is in PATH
echo %PATH% | find /c /i ";%X%"
if errorlevel 1 echo %X% is in PATH
echo %PATH% | find /c /i "%X%;"
if errorlevel 1 echo %X% is in PATH

Same font except its weight seems different on different browsers

Be sure the font is the same for all browsers. If it is the same font, then the problem has no solution using cross-browser CSS.

Because every browser has its own font rendering engine, they are all different. They can also differ in later versions, or across different OS's.

UPDATE: For those who do not understand the browser and OS font rendering differences, read this and this.

However, the difference is not even noticeable by most people, and users accept that. Forget pixel-perfect cross-browser design, unless you are:

  1. Trying to turn-off the subpixel rendering by CSS (not all browsers allow that and the text may be ugly...)
  2. Using images (resources are demanding and hard to maintain)
  3. Replacing Flash (need some programming and doesn't work on iOS)

UPDATE: I checked the example page. Tuning the kerning by text-rendering should help:

text-rendering: optimizeLegibility; 

More references here:

  1. Part of the font-rendering is controlled by font-smoothing (as mentioned) and another part is text-rendering. Tuning these properties may help as their default values are not the same across browsers.
  2. For Chrome, if this is still not displaying OK for you, try this text-shadow hack. It should improve your Chrome font rendering, especially in Windows. However, text-shadow will go mad under Windows XP. Be careful.

If else in stored procedure sql server

Try this one -

CREATE PROCEDURE sp_ADD_USER_EXTRANET_CLIENT_INDEX_PHY
AS
BEGIN

    DECLARE @ParLngId INT
    SELECT TOP 1 @ParLngId = ParLngId
    FROM dbo.T_Param
    WHERE ParStrNom = 'Extranet Client'

    IF (@ParLngId = 0)
    BEGIN
        INSERT INTO dbo.T_Param
        VALUES ('PHY', 'Extranet Client', NULL, NULL, 'T', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL)

        RETURN SCOPE_IDENTITY()
    END
    ELSE BEGIN

        RETURN @ParLngId 

    END

END

Gem Command not found

On Debian, Ubuntu or Linux Mint:

$ sudo apt-get install rubygems ruby-dev

On CentOS, Fedora or RHEL:

$ sudo yum install rubygems ruby-devel

How to escape double quotes in a title attribute

Here's a snippet of the HTML escape characters taken from a cached page on archive.org:

&#060   |   <   less than sign
&#064   |   @   at sign
&#093   |   ]   right bracket
&#123   |   {   left curly brace
&#125   |   }   right curly brace
&#133   |   …   ellipsis
&#135   |   ‡   double dagger
&#146   |   ’   right single quote
&#148   |   ”   right double quote
&#150   |   –   short dash
&#153   |   ™   trademark
&#162   |   ¢   cent sign
&#165   |   ¥   yen sign
&#169   |   ©   copyright sign
&#172   |   ¬   logical not sign
&#176   |   °   degree sign
&#178   |   ²   superscript 2
&#185   |   ¹   superscript 1
&#188   |   ¼   fraction 1/4
&#190   |   ¾   fraction 3/4
&#247   |   ÷   division sign
&#8221  |   ”   right double quote
&#062   |   >   greater than sign
&#091   |   [   left bracket
&#096   |   `   back apostrophe
&#124   |   |   vertical bar
&#126   |   ~   tilde
&#134   |   †   dagger
&#145   |   ‘   left single quote
&#147   |   “   left double quote
&#149   |   •   bullet
&#151   |   —   longer dash
&#161   |   ¡   inverted exclamation point
&#163   |   £   pound sign
&#166   |   ¦   broken vertical bar
&#171   |   «   double left than sign
&#174   |   ®   registered trademark sign
&#177   |   ±   plus or minus sign
&#179   |   ³   superscript 3
&#187   |   »   double greater-than sign
&#189   |   ½   fraction 1/2
&#191   |   ¿   inverted question mark
&#8220  |   “   left double quote
&#8212  |   —   dash

java: How can I do dynamic casting of a variable from one type to another?

So, this is an old post, however I think I can contribute something to it.

You can always do something like this:

package com.dyna.test;  

import java.io.File;  
import java.lang.reflect.Constructor;  

public class DynamicClass{  

  @SuppressWarnings("unchecked")  
  public Object castDynamicClass(String className, String value){  
    Class<?> dynamicClass;  

    try  
    {  
      //We get the actual .class object associated with the specified name  
      dynamicClass = Class.forName(className);  



    /* We get the constructor that received only 
     a String as a parameter, since the value to be used is a String, but we could
easily change this to be "dynamic" as well, getting the Constructor signature from
the same datasource we get the values from */ 


      Constructor<?> cons =  
        (Constructor<?>) dynamicClass.getConstructor(new Class<?>[]{String.class});  

      /*We generate our object, without knowing until runtime 
 what type it will be, and we place it in an Object as 
 any Java object extends the Object class) */  
      Object object = (Object) cons.newInstance(new Object[]{value});  

      return object;  
    }  
    catch (Exception e)  
    {  
      e.printStackTrace();  
    }  
    return null;  
  }  

  public static void main(String[] args)  
  {   
    DynamicClass dynaClass = new DynamicClass();  

    /* 
 We specify the type of class that should be used to represent 
 the value "3.0", in this case a Double. Both these parameters 
 you can get from a file, or a network stream for example. */  
    System.out.println(dynaClass.castDynamicClass("java.lang.Double", "3.0"));  

    /* 
We specify a different value and type, and it will work as 
 expected, printing 3.0 in the above case and the test path in the one below, as the Double.toString() and 
 File.toString() would do. */  
    System.out.println(dynaClass.castDynamicClass("java.io.File", "C:\\testpath"));  
  }  

Of course, this is not really dynamic casting, as in other languages (Python for example), because java is a statically typed lang. However, this can solve some fringe cases where you actually need to load some data in different ways, depending on some identifier. Also, the part where you get a constructor with a String parameter could be probably made more flexible, by having that parameter passed from the same data source. I.e. from a file, you get the constructor signature you want to use, and the list of values to be used, that way you pair up, say, the first parameter is a String, with the first object, casting it as a String, next object is an Integer, etc, but somehwere along the execution of your program, you get now a File object first, then a Double, etc.

In this way, you can account for those cases, and make a somewhat "dynamic" casting on-the-fly.

Hope this helps anyone as this keeps turning up in Google searches.

keyword not supported data source

I was getting the same error, then updated my connection string as below,

<add name="EmployeeContext" connectionString="data source=*****;initial catalog=EmployeeDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

Try this it will solve your issue.

Java random number with given length

If you need to specify the exact charactor length, we have to avoid values with 0 in-front.

Final String representation must have that exact character length.

String GenerateRandomNumber(int charLength) {
        return String.valueOf(charLength < 1 ? 0 : new Random()
                .nextInt((9 * (int) Math.pow(10, charLength - 1)) - 1)
                + (int) Math.pow(10, charLength - 1));
    }

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Settings->Preferences->Auto-Completion and there check Enable auto-completion on each input. Press Ctrl + Space to get a autocomplete hint. For auto-complete in code type the first letter then press Ctrl + Enter. all the inputs you have given will be listed.

How to set Toolbar text and back arrow color

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/actionBar"
app:titleTextAppearance="@style/ToolbarTitleText"
app:theme="@style/ToolBarStyle">

<TextView
    android:id="@+id/title"
    style="@style/ToolbarTitleText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="hh"/>

<!-- ToolBar -->
<style name="ToolBarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="actionMenuTextColor">#ff63BBF7</item>
</style>

use app:theme="@style/ToolBarStyle"

Reference resources:http://blog.csdn.net/wyyl1/article/details/45972371

SQL Server - Adding a string to a text column (concat equivalent)

Stop using the TEXT data type in SQL Server!

It's been deprecated since the 2005 version. Use VARCHAR(MAX) instead, if you need more than 8000 characters.

The TEXT data type doesn't support the normal string functions, while VARCHAR(MAX) does - your statement would work just fine, if you'd be using just VARCHAR types.

WPF What is the correct way of using SVG files as icons in WPF

Windows 10 build 15063 "Creators Update" natively supports SVG images (though with some gotchas) to UWP/UAP applications targeting Windows 10.

If your application is a WPF app rather than a UWP/UAP, you can still use this API (after jumping through quite a number of hoops): Windows 10 build 17763 "October 2018 Update" introduced the concept of XAML islands (as a "preview" technology but I believe allowed in the app store; in all cases, with Windows 10 build 18362 "May 2019 Update" XAML islands are no longer a preview feature and are fully supported) allowing you to use UWP APIs and controls in your WPF applications.

You need to first add the references to the WinRT APIs, and to use certain Windows 10 APIs that interact with user data or the system (e.g. loading images from disk in a Windows 10 UWP webview or using the toast notification API to show toasts), you also need to associate your WPF application with a package identity, as shown here (immensely easier in Visual Studio 2019). This shouldn't be necessary to use the Windows.UI.Xaml.Media.Imaging.SvgImageSource class, though.

Usage (if you're on UWP or you've followed the directions above and added XAML island support under WPF) is as simple as setting the Source for an <Image /> to the path to the SVG. That is equivalent to using SvgImageSource, as follows:

<Image>
    <Image.Source>
        <SvgImageSource UriSource="Assets/svg/icon.svg" />
    </Image.Source>
</Image>

However, SVG images loaded in this way (via XAML) may load jagged/aliased. One workaround is to specify a RasterizePixelHeight or RasterizePixelWidth value that is double+ your actual height/width:

<SvgImageSource RasterizePixelHeight="300" RasterizePixelWidth="300" UriSource="Assets/svg/icon.svg" /> <!-- presuming actual height or width is under 150 -->

This can be worked around dynamically by creating a new SvgImageSource in the ImageOpened event for the base image:

var svgSource = new SvgImageSource(new Uri("ms-appx://" + Icon));
PrayerIcon.ImageOpened += (s, e) =>
{
    var newSource = new SvgImageSource(svgSource.UriSource);
    newSource.RasterizePixelHeight = PrayerIcon.DesiredSize.Height * 2;
    newSource.RasterizePixelWidth = PrayerIcon.DesiredSize.Width * 2;
    PrayerIcon2.Source = newSource;
};
PrayerIcon.Source = svgSource;

The aliasing may be hard to see on non high-dpi screens, but here's an attempt to illustrate it.

This is the result of the code above: an Image that uses the initial SvgImageSource, and a second Image below it that uses the SvgImageSource created in the ImageOpened event:

enter image description here

This is a blown up view of the top image:

enter image description here

Whereas this is a blown-up view of the bottom (antialiased, correct) image:

enter image description here

(you'll need to open the images in a new tab and view at full size to appreciate the difference)

How to start a background process in Python?

Use subprocess.Popen() with the close_fds=True parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.

https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f

import os, time, sys, subprocess

if len(sys.argv) == 2:
    time.sleep(5)
    print 'track end'
    if sys.platform == 'darwin':
        subprocess.Popen(['say', 'hello'])
else:
    print 'main begin'
    subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
    print 'main end'

How is a CRC32 checksum calculated?

In order to reduce crc32 to taking the reminder you need to:

  1. Invert bits on each byte
  2. xor first four bytes with 0xFF (this is to avoid errors on the leading 0s)
  3. Add padding at the end (this is to make the last 4 bytes take part in the hash)
  4. Compute the reminder
  5. Reverse the bits again
  6. xor the result again.

In code this is:


func CRC32 (file []byte) uint32 {
    for i , v := range(file) {
        file[i] = bits.Reverse8(v)
    }
    for i := 0; i < 4; i++ {
        file[i] ^= 0xFF
    }

    // Add padding
    file = append(file, []byte{0, 0, 0, 0}...)
    newReminder := bits.Reverse32(reminderIEEE(file))

    return newReminder ^ 0xFFFFFFFF
}

where reminderIEEE is the pure reminder on GF(2)[x]

Drawing in Java using Canvas

You've got to override your Canvas's paint(Graphics g) method and perform your drawing there. See the paint() documentation.

As it states, the default operation is to clear the canvas, so your call to the canvas' graphics object doesn't perform as you would expect.

How do I detect if Python is running as a 64-bit application?

import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

How to fix nginx throws 400 bad request headers on any header testing tools?

Yes changing the error_to debug level as Emmanuel Joubaud suggested worked out (edit /etc/nginx/sites-enabled/default ):

        error_log /var/log/nginx/error.log debug;

Then after restaring nginx I got in the error log with my Python application using uwsgi:

        2017/02/08 22:32:24 [debug] 1322#1322: *1 connect to unix:///run/uwsgi/app/socket, fd:20 #2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 connected
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream connect: 0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 posix_memalign: 0000560E1F25A2A0:128 @16
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request body
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer buf fl:0 s:454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer in: 0000560E1F2A0928
        2017/02/08 22:32:24 [debug] 1322#1322: *1 writev: 454 of 454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer out: 0000000000000000
        2017/02/08 22:32:24 [debug] 1322#1322: *1 event timer add: 20: 60000:1486593204249
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http finalize request: -4, "/?" a:1, c:2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http request count:2 blk:0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5E40
        2017/02/08 22:32:24 [debug] 1322#1322: *1 delete posted event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http run request: "/?"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream check client, write event:1, "/"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream recv(): -1 (11: Resource temporarily unavailable)

Then I took a look to my uwsgi log and found out that:

        Invalid HTTP_HOST header: 'www.mysite.local'. You may need to add u'www.mysite.local' to ALLOWED_HOSTS.
        [pid: 10903|app: 0|req: 2/4] 192.168.221.2 () {38 vars in 450 bytes} [Wed Feb  8 22:32:24 2017] GET / => generated 54098 bytes in 55 msecs (HTTP/1.1 400) 4 headers in 135 bytes (1 switches on core 0)

And adding www.mysite.local to the settings.py ALLOWED_HOSTS fixed the issue :)

        ALLOWED_HOSTS = ['www.mysite.local']

How to reduce the image file size using PIL

If you hava a fact png (1MB for 400x400 etc.):

__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")

WCF timeout exception detailed investigation

You will also receive this error if you are passing an object back to the client that contains a property of type enum that is not set by default and that enum does not have a value that maps to 0. i.e enum MyEnum{ a=1, b=2};

How to search images from private 1.0 registry in docker?

List all images

docker search <registry_host>:<registry_port>/

List images like 'vcs'

docker search <registry_host>:<registry_port>/vcs

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

mysql is not recognised as an internal or external command,operable program or batch

MYSQL_HOME variable value:C:\Program Files\MySQL\MySQL Server 5.0\bin %MYSQL_HOME%\bin

See the problem? This resolves to a path of C:\Program Files\MySQL\MySQL Server 5.0\bin\bin

How do I configure different environments in Angular.js?

You could use lvh.me:9000 to access your AngularJS app, (lvh.me just points to 127.0.0.1) and then specify a different endpoint if lvh.me is the host:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

And then inject the Configuration service and use Configuration.API wherever you need to access the API:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

A tad clunky, but works fine for me, albeit in a slightly different situation (API endpoints differ in production and development).

MySQL COUNT DISTINCT

Overall

SELECT
       COUNT(DISTINCT `site_id`) as distinct_sites
  FROM `cp_visits`
 WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Or per site

  SELECT
         `site_id` as site,
         COUNT(DISTINCT `user_id`) as distinct_users_per_site
    FROM `cp_visits`
   WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`

Having the time column in the result doesn't make sense - since you are aggregating the rows, showing one particular time is irrelevant, unless it is the min or max you are after.

Splitting a C++ std::string using tokens, e.g. ";"

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
{
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        output.push_back(substring);

        prev_pos = ++pos;
    }

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;
}

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.beginPath();
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.closePath();
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.fill();
  context.strokeStyle = 'blue';
  context.stroke();
</script>
_x000D_
_x000D_
_x000D_

  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

_x000D_
_x000D_
    $.ajax({
      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
      }
    }).done(function(o) {
      console.log('saved'); 
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
    });
_x000D_
_x000D_
_x000D_

  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

How to print a list with integers without the brackets, commas and no quotes?

Something like this should do it:

for element in list_:
   sys.stdout.write(str(element))

Define constant variables in C++ header

You generally shouldn't use e.g. const int in a header file, if it's included in several source files. That is because then the variables will be defined once per source file (translation units technically speaking) because global const variables are implicitly static, taking up more memory than required.

You should instead have a special source file, Constants.cpp that actually defines the variables, and then have the variables declared as extern in the header file.

Something like this header file:

// Protect against multiple inclusions in the same source file
#ifndef CONSTANTS_H
#define CONSTANTS_H

extern const int CONSTANT_1;

#endif

And this in a source file:

const int CONSTANT_1 = 123;

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

Is it possible to get multiple values from a subquery?

Can't you use JOIN like this one?

SELECT
a.x , b.y, b.z 
FROM a 
LEFT OUTER JOIN b ON b.v = a.v

(I don't know Oracle Syntax. So I wrote SQL syntax)

What does the "no version information available" error from linux dynamic linker mean?

Have you seen this already? The cause seems to be a very old libpam on one of the sides, probably on that customer.

Or the links for the version might be missing : http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html

Getting one value from a tuple

You can write

i = 5 + tup()[0]

Tuples can be indexed just like lists.

The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

mysql: see all open connections to a given database?

If you're running a *nix system, also consider mytop.

To limit the results to one database, press "d" when it's running then type in the database name.

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

I don't know how to delete all at once, but you can use ipcs to list resources, and then use loop and delete with ipcrm. This should work, but it needs a little work. I remember that I made it work once in class.

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Empty responseText from XMLHttpRequest

PROBLEM RESOLVED

In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:

url: "http://mydomain.com/site/cgi-bin/serverApp.php"

But the correct way is to pass the value of url as:

url: "site/cgi-bin/serverApp.php"

Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:

http://mydomain.com/site/index.html

And put

http://www.mydomain.com/site/index.html

In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file

base href="http://mydomain.com/" <--- bad idea, remove it!

If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!

I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:

header('Content-type: application/json');

to ensure that browser get the data as "json data" ...

Changing file permission in Python

All the current answers clobber the non-writing permissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444 permissions -- but we can do better!

Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.

import os
import stat

def remove_write_permissions(path):
    """Remove write permissions from this path, while keeping all other permissions intact.

    Params:
        path:  The path whose permissions to alter.
    """
    NO_USER_WRITING = ~stat.S_IWUSR
    NO_GROUP_WRITING = ~stat.S_IWGRP
    NO_OTHER_WRITING = ~stat.S_IWOTH
    NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING

    current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
    os.chmod(path, current_permissions & NO_WRITING)

Why does this work?

As John La Rooy pointed out,stat.S_IWUSR basically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact opposite bitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~ operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&), it will zero out the corresponding bit.

We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &'ing them all together (forming the NO_WRITING bit constant).

The last step is to get the current file's permissions, and actually perform the bitwise-and operation.

How to get response from S3 getObject in Node.js?

Based on the answer by @peteb, but using Promises and Async/Await:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

async function getObject (bucket, objectKey) {
  try {
    const params = {
      Bucket: bucket,
      Key: objectKey 
    }

    const data = await s3.getObject(params).promise();

    return data.Body.toString('utf-8');
  } catch (e) {
    throw new Error(`Could not retrieve file from S3: ${e.message}`)
  }
}

// To retrieve you need to use `await getObject()` or `getObject().then()`
getObject('my-bucket', 'path/to/the/object.txt').then(...);

Angular2 change detection: ngOnChanges not firing for nested object

rawLapsData continues to point to the same array, even if you modify the contents of the array (e.g., add items, remove items, change an item).

During change detection, when Angular checks components' input properties for change, it uses (essentially) === for dirty checking. For arrays, this means the array references (only) are dirty checked. Since the rawLapsData array reference isn't changing, ngOnChanges() will not be called.

I can think of two possible solutions:

  1. Implement ngDoCheck() and perform your own change detection logic to determine if the array contents have changed. (The Lifecycle Hooks doc has an example.)

  2. Assign a new array to rawLapsData whenever you make any changes to the array contents. Then ngOnChanges() will be called because the array (reference) will appear as a change.

In your answer, you came up with another solution.

Repeating some comments here on the OP:

I still don't see how laps can pick up on the change (surely it must be using something equivalent to ngOnChanges() itself?) while map can't.

  • In the laps component your code/template loops over each entry in the lapsData array, and displays the contents, so there are Angular bindings on each piece of data that is displayed.
  • Even when Angular doesn't detect any changes to a component's input properties (using === checking), it still (by default) dirty checks all of the template bindings. When any of those change, Angular will update the DOM. That's what you are seeing.
  • The maps component likely doesn't have any bindings in its template to its lapsData input property, right? That would explain the difference.

Note that lapsData in both components and rawLapsData in the parent component all point to the same/one array. So even though Angular doesn't notice any (reference) changes to the lapsData input properties, the components "get"/see any array contents changes because they all share/reference that one array. We don't need Angular to propagate these changes, like we would with a primitive type (string, number, boolean). But with a primitive type, any change to the value would always trigger ngOnChanges() – which is something you exploit in your answer/solution.

As you probably figured out by now object input properties have the same behavior as array input properties.

setTimeout or setInterval?

I use setTimeout.

Apparently the difference is setTimeout calls the method once, setInterval calls it repeatdly.

Here is a good article explaining the difference: Tutorial: JavaScript timers with setTimeout and setInterval

How to create a byte array in C++?

Byte is not a standard type in C/C++, so it is represented by char.

An advantage of this is that you can treat a basic_string as a byte array allowing for safe storage and function passing. This will help you avoid the memory leaks and segmentation faults you might encounter when using the various forms of char[] and char*.

For example, this creates a string as a byte array of null values:

typedef basic_string<unsigned char> u_string;

u_string bytes = u_string(16,'\0');

This allows for standard bitwise operations with other char values, including those stored in other string variables. For example, to XOR the char values of another u_string across bytes:

u_string otherBytes = "some more chars, which are just bytes";
for(int i = 0; i < otherBytes.length(); i++)
    bytes[i%16] ^= (int)otherBytes[i];

How to access global js variable in AngularJS directive

Copy the global variable to a variable in the scope in your controller.

function MyCtrl($scope) {
   $scope.variable1 = variable1;
}

Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).

But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.

Visual Studio opens the default browser instead of Internet Explorer

Scott Guthrie has made a post on how to change Visual Studio's default browser:

1) Right click on a .aspx page in your solution explorer

2) Select the "browse with" context menu option

3) In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename

4) Click the "Set as Default" button to make this the default browser when you run any page on the site.

I however dislike the fact that this isn't as straightforward as it should be.

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

How to convert a timezone aware string to datetime in Python without dateutil?

Here is the Python Doc for datetime object using dateutil package..

from dateutil.parser import parse

get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj