Programs & Examples On #Trackbar

a graphical widget in Winforms, also called a slider in other environments.

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

Load HTML file into WebView

The Accepted Answer is not working for me, This is what works for me

WebSettings webSetting = webView.getSettings();
    webSetting.setBuiltInZoomControls(true);
    webView1.setWebViewClient(new WebViewClient());

   webView.loadUrl("file:///android_asset/index.html");

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Wampserver icon not going green fully, mysql services not starting up?

I had the same problem. Mysql didn't start.

  1. go to services.
  2. right click the wampmysqld go to properties.
  3. startup type select manual.
  4. right click and click start service.

worked for me.

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

z-index not working with position absolute

Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

How to vertically center content with variable height within a div?

Just add

position: relative;
top: 50%;
transform: translateY(-50%);

to the inner div.

What it does is moving the inner div's top border to the half height of the outer div (top: 50%;) and then the inner div up by half its height (transform: translateY(-50%)). This will work with position: absolute or relative.

Keep in mind that transform and translate have vendor prefixes which are not included for simplicity.

Codepen: http://codepen.io/anon/pen/ZYprdb

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Pandas magic at work. All logic is out.

The error message "ValueError: If using all scalar values, you must pass an index" Says you must pass an index.

This does not necessarily mean passing an index makes pandas do what you want it to do

When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.

a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])

    A   B
1   2   3

Passing a larger index:

df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])

    A   B
1   2   3
2   2   3
3   2   3
4   2   3

An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2 and 3 you want. You can however be more explicit about it

df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2

    A   B
0   2   3
1   2   3
2   2   3
3   2   3

The default index is 0 based though.

I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.

Getting next element while cycling through a list

The simple solution is to remove IndexError by incorporating the condition:

if(index<(len(li)-1))

The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.

Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.

li = [0, 1, 2, 3]

running = True
while running:
    for index, elem in enumerate(li):
        if(index<(len(li)-1)):
            thiselem = elem
            nextelem = li[index+1]

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

How to move a git repository into another directory and make that directory a git repository?

I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard

How to call javascript from a href?

Using JQuery would be good;

<a href="#" id="youLink">Call JavaScript </a>



$("#yourLink").click(function(e){
//do what ever you want...
});

What is <scope> under <dependency> in pom.xml for?

The <scope> element can take 6 values: compile, provided, runtime, test, system and import.

This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.

compile

This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

provided

This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

runtime

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

test

This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

system

This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

import (only available in Maven 2.0.9 or later)

This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

To answer the second part of your question:

How can we use it for running test?

Note that the test scope allows to use dependencies only for the test phase.

Read the documentation for full details.

Docker: Container keeps on restarting again on again

First check the logs why the container failed. Because your restart policy might bring your container back to running status. Better to fix the issue, Then probably you can build a new image with/without fix. Later execute below command

docker system prune

https://forums.docker.com/t/docker-registry-in-restarting-1-status-forever/12717/3

What are the applications of binary trees?

In C++ STL, and many other standard libraries in other languages, like Java and C#. Binary search trees are used to implement set and map.

Does Android support near real time push notification?

I recently started playing with MQTT http://mqtt.org for Android as a way of doing what you're asking for (i.e. not SMS but data driven, almost immediate message delivery, scalable, not polling, etc.)

I have a blog post with background information on this in case it's helpful http://dalelane.co.uk/blog/?p=938

(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)

Toggle visibility property of div

To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}
.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

How to determine one year from now in Javascript

As setYear() is deprecated, correct variant is:

// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)

All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)

How do you specify a byte literal in Java?

If you're passing literals in code, what's stopping you from simply declaring it ahead of time?

byte b = 0; //Set to desired value.
f(b);

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

SQL/mysql - Select distinct/UNIQUE but return all columns?

You're looking for a group by:

select *
from table
group by field1

Which can occasionally be written with a distinct on statement:

select distinct on field1 *
from table

On most platforms, however, neither of the above will work because the behavior on the other columns is unspecified. (The first works in MySQL, if that's what you're using.)

You could fetch the distinct fields and stick to picking a single arbitrary row each time.

On some platforms (e.g. PostgreSQL, Oracle, T-SQL) this can be done directly using window functions:

select *
from (
   select *,
          row_number() over (partition by field1 order by field2) as row_number
   from table
   ) as rows
where row_number = 1

On others (MySQL, SQLite), you'll need to write subqueries that will make you join the entire table with itself (example), so not recommended.

In C++ check if std::vector<string> contains a certain value

You can use std::find as follows:

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

To be able to use std::find: include <algorithm>.

How to force Docker for a clean build of an image

Most of information here are correct.
Here a compilation of them and my way of using them.

The idea is to stick to the recommended approach (build specific and no impact on other stored docker objects) and to try the more radical approach (not build specific and with impact on other stored docker objects) when it is not enough.

Recommended approach :

1) Force the execution of each step/instruction in the Dockerfile :

docker build --no-cache 

or with docker-compose build :

docker-compose build --no-cache

We could also combine that to the up sub-command that recreate all containers:

docker-compose build --no-cache &&
docker-compose up -d --force-recreate 

These way don't use cache but for the docker builder and the base image referenced with the FROM instruction.

2) Wipe the docker builder cache (if we use Buildkit we very probably need that) :

docker builder prune -af

3) If we don't want to use the cache of the parent images, we may try to delete them such as :

docker image rm -f fooParentImage

In most of cases, these 3 things are perfectly enough to allow a clean build of our image.
So we should try to stick to that.

More radical approach :

In corner cases where it seems that some objects in the docker cache are still used during the build and that looks repeatable, we should try to understand the cause to be able to wipe the missing part very specifically. If we really don't find a way to rebuild from scratch, there are other ways but it is important to remember that these generally delete much more than it is required. So we should use them with cautious overall when we are not in a local/dev environment.

1) Remove all images without at least one container associated to them :

docker image prune -a

2) Remove many more things :

docker system prune -a

That says :

WARNING! This will remove:
  - all stopped containers
  - all networks not used by at least one container
  - all images without at least one container associated to them
  - all build cache

Using that super delete command may not be enough because it strongly depends on the state of containers (running or not). When that command is not enough, I try to think carefully which docker containers could cause side effects to our docker build and to allow these containers to be exited in order to allow them to be removed with the command.

Should I use pt or px?

px ? Pixels

All of these answers seem to be incorrect. Contrary to intuition, in CSS the px is not pixels. At least, not in the simple physical sense.

Read this article from the W3C, EM, PX, PT, CM, IN…, about how px is a "magical" unit invented for CSS. The meaning of px varies by hardware and resolution. (That article is fresh, last updated 2014-10.)

My own way of thinking about it: 1 px is the size of a thin line intended by a designer to be barely visible.

To quote that article:

The px unit is the magic unit of CSS. It is not related to the current font and also not related to the absolute units. The px unit is defined to be small but visible, and such that a horizontal 1px wide line can be displayed with sharp edges (no anti-aliasing). What is sharp, small and visible depends on the device and the way it is used: do you hold it close to your eyes, like a mobile phone, at arms length, like a computer monitor, or somewhere in between, like a book? The px is thus not defined as a constant length, but as something that depends on the type of device and its typical use.

To get an idea of the appearance of a px, imagine a CRT computer monitor from the 1990s: the smallest dot it can display measures about 1/100th of an inch (0.25mm) or a little more. The px unit got its name from those screen pixels.

Nowadays there are devices that could in principle display smaller sharp dots (although you might need a magnifier to see them). But documents from the last century that used px in CSS still look the same, no matter what the device. Printers, especially, can display sharp lines with much smaller details than 1px, but even on printers, a 1px line looks very much the same as it would look on a computer monitor. Devices change, but the px always has the same visual appearance.

That article gives some guidance about using pt vs px vs em, to answer this Question.

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

How to switch to the new browser window, which opens after click on the button?

Just to add to the content ...

To go back to the main window(default window) .

use driver.switchTo().defaultContent();

MySQL Update Column +1?

How about:

update table
set columnname = columnname + 1
where id = <some id>

Converting a JS object to an array using jQuery

After some tests, here is a general object to array function convertor:

You have the object:

var obj = {
    some_key_1: "some_value_1"
    some_key_2: "some_value_2"
};

The function:

function ObjectToArray(o)
{
    var k = Object.getOwnPropertyNames(o);
    var v = Object.values(o);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
}

Function Use:

var arr = ObjectToArray(obj);

You Get:

arr {
    key: [
        "some_key_1",
        "some_key_2"
    ],
    value: [
        "some_value_1",
        "some_value_2"
    ],
    length: 2
}

So then you can reach all keys & values like:

for (var i = 0; i < arr.length; i++)
{
    console.log(arr.key[i] + " = " + arr.value[i]);
}

Result in console:

some_key_1 = some_value_1
some_key_2 = some_value_2

Edit:

Or in prototype form:

Object.prototype.objectToArray = function()
{
    if (
        typeof this != 'object' ||
        typeof this.length != "undefined"
    ) {
        return false;
    }

    var k = Object.getOwnPropertyNames(this);
    var v = Object.values(this);

    var c = function(l)
    {
        this.k = [];
        this.v = [];
        this.length = l;
    };

    var r = new c(k.length);

    for (var i = 0; i < k.length; i++)
    {
        r.k[i] = k[i];
        r.v[i] = v[i];
    }

    return r;
};

And then use like:

console.log(obj.objectToArray);

Finding the length of an integer in C

I think I got the most efficient way to find the length of an integer its a very simple and elegant way here it is:

int PEMath::LengthOfNum(int Num)
{
int count = 1;  //count starts at one because its the minumum amount of digits posible
if (Num < 0)
{
    Num *= (-1);
}

for(int i = 10; i <= Num; i*=10)
{
     count++;
}      
return count;
                // this loop will loop until the number "i" is bigger then "Num"
                // if "i" is less then "Num" multiply "i" by 10 and increase count
                // when the loop ends the number of count is the length of "Num".
}

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Based on BaileyP's answer. The main difference is that these methods return -1 if the pattern can't be matched.

Edit: Thanks to Jason Bunting's answer I got an idea. Why not modify the .lastIndex property of the regex? Though this will only work for patterns with the global flag (/g).

Edit: Updated to pass the test-cases.

String.prototype.regexIndexOf = function(re, startPos) {
    startPos = startPos || 0;

    if (!re.global) {
        var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
        re = new RegExp(re.source, flags);
    }

    re.lastIndex = startPos;
    var match = re.exec(this);

    if (match) return match.index;
    else return -1;
}

String.prototype.regexLastIndexOf = function(re, startPos) {
    startPos = startPos === undefined ? this.length : startPos;

    if (!re.global) {
        var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
        re = new RegExp(re.source, flags);
    }

    var lastSuccess = -1;
    for (var pos = 0; pos <= startPos; pos++) {
        re.lastIndex = pos;

        var match = re.exec(this);
        if (!match) break;

        pos = match.index;
        if (pos <= startPos) lastSuccess = pos;
    }

    return lastSuccess;
}

SELECT INTO Variable in MySQL DECLARE causes syntax error?

I am using version 6 (MySQL Workbench Community (GPL) for Windows version 6.0.9 revision 11421 build 1170) on Windows Vista. I have no problem with the following options. Probably they fixed it since these guys got the problems three years ago.

/* first option */
SELECT ID 
INTO @myvar 
FROM party 
WHERE Type = 'individual';

-- get the result
select @myvar;

/* second option */
SELECT @myvar:=ID
FROM party
WHERE Type = 'individual';


/* third option. The same as SQL Server does */
SELECT @myvar = ID FROM party WHERE Type = 'individual';

All option above give me a correct result.

Is <div style="width: ;height: ;background: "> CSS?

For example :

_x000D_
_x000D_
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
_x000D_
_x000D_

here.

you give css to div of height and width having 100px and background as black.

PS : try to avoid inline-css you can make external CSS and import in your html file.

you can refer here for CSS

hope this helps.

GIT commit as different user without email / or only email

The --author option doesn't work:

*** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

This does:

git -c user.name='A U Thor' -c [email protected] commit

How to change the default collation of a table?

MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.

E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.

Angular 4: How to include Bootstrap?

npm install --save bootstrap

afterwards, inside angular-cli.json (inside the project's root folder), find styles and add the bootstrap css file like this:

"styles": [
   "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   "styles.css"
],

UPDATE:
in angular 6+ angular-cli.json was changed to angular.json.

jQuery selector first td of each row

Use:

$("tr").find("td:first");

js fiddle - this example has .text() on the end to show that it is returning the elements.

Alternatively, you can use:

$("td:first-child");

.find() - jQuery API Documentation

jsPDF multi page PDF with HTML renderer

here's an example using html2canvas & jspdf, although how you generate the canvas doesn't matter--we're just going to use the height of that as the breakpoint on a for loop, in which a new page is created and content added to it.

after the for loop, the pdf is saved.

function makePDF() {

       var quotes = document.getElementById('container-fluid');
       html2canvas(quotes)
      .then((canvas) => {
            //! MAKE YOUR PDF
            var pdf = new jsPDF('p', 'pt', 'letter');

            for (var i = 0; i <= quotes.clientHeight/980; i++) {
                //! This is all just html2canvas stuff
                var srcImg  = canvas;
                var sX      = 0;
                var sY      = 980*i; // start 980 pixels down for every new page
                var sWidth  = 900;
                var sHeight = 980;
                var dX      = 0;
                var dY      = 0;
                var dWidth  = 900;
                var dHeight = 980;

                window.onePageCanvas = document.createElement("canvas");
                onePageCanvas.setAttribute('width', 900);
                onePageCanvas.setAttribute('height', 980);
                var ctx = onePageCanvas.getContext('2d');
                // details on this usage of this function: 
                // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
                ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);

                // document.body.appendChild(canvas);
                var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);

                var width         = onePageCanvas.width;
                var height        = onePageCanvas.clientHeight;

                //! If we're on anything other than the first page,
                // add another page
                if (i > 0) {
                    pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
                }
                //! now we declare that we're working on that page
                pdf.setPage(i+1);
                //! now we add content to that page!
                pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));

            }
            //! after the for loop is finished running, we save the pdf.
            pdf.save('Test.pdf');
        }
      });
    }

How to get the IP address of the docker host from inside a docker container

With https://docs.docker.com/machine/install-machine/

a) $ docker-machine ip

b) Get the IP address of one or more machines.

  $ docker-machine ip host_name

  $ docker-machine ip host_name1 host_name2

How to load specific image from assets with Swift

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")

Use cases for the 'setdefault' dict method

Another use case that I don't think was mentioned above. Sometimes you keep a cache dict of objects by their id where primary instance is in the cache and you want to set cache when missing.

return self.objects_by_id.setdefault(obj.id, obj)

That's useful when you always want to keep a single instance per distinct id no matter how you obtain an obj each time. For example when object attributes get updated in memory and saving to storage is deferred.

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

How do I perform a Perl substitution on a string while keeping the original?

Another pre-5.14 solution: http://www.perlmonks.org/?node_id=346719 (see japhy's post)

As his approach uses map, it also works well for arrays, but requires cascading map to produce a temporary array (otherwise the original would be modified):

my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

SMTP error 554

SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.

We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.

How to escape single quotes in MySQL

See my answer to "How to escape characters in MySQL"

Whatever library you are using to talk to MySQL will have an escaping function built in, e.g. in PHP you could use mysqli_real_escape_string or PDO::quote

How to check if object property exists with a variable holding the property name?

You can use hasOwnProperty, but based on the reference you need quotes when using this method:

if (myObj.hasOwnProperty('myProp')) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Another way is to use in operator, but you need quotes here as well:

if ('myProp' in myObj) {
    // do something
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Get just the filename from a path in a Bash script

Here is an easy way to get the file name from a path:

echo "$PATH" | rev | cut -d"/" -f1 | rev

To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

cut -d"." -f1

Best Way to View Generated Source of Webpage?

In the Web Developer Toolbar, have you tried the Tools -> Validate HTML or Tools -> Validate Local HTML options?

The Validate HTML option sends the url to the validator, which works well with publicly facing sites. The Validate Local HTML option sends the current page's HTML to the validator, which works well with pages behind a login, or those that aren't publicly accessible.

You may also want to try View Source Chart (also as FireFox add-on). An interesting note there:

Q. Why does View Source Chart change my XHTML tags to HTML tags?

A. It doesn't. The browser is making these changes, VSC merely displays what the browser has done with your code. Most common: self closing tags lose their closing slash (/). See this article on Rendered Source for more information (archive.org).

Getting Unexpected Token Export

I fixed this by making an entry point file like.

// index.js
require = require('esm')(module)
module.exports = require('./app.js')

and any file I imported inside app.js and beyond worked with imports/exports now you just run it like node index.js

Note: if app.js uses export default, this becomes require('./app.js').default when using the entry point file.

How to convert string to XML using C#

Use LoadXml Method of XmlDocument;

string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);

How can I check which version of Angular I'm using?

On your project folder, open the command terminal and type

ng -v

it will give you a list of items, in that you will be able to see the angular version. See the screenshot.

version details

Add up a column of numbers at the Unix shell

Here goes

cat files.txt | xargs ls -l | cut -c 23-30 | 
  awk '{total = total + $1}END{print total}'

What is the max size of localStorage values?

I'm doing the following:

getLocalStorageSizeLimit = function () {

    var maxLength = Math.pow(2,24);
    var preLength = 0;
    var hugeString = "0";
    var testString;
    var keyName = "testingLengthKey";

    //2^24 = 16777216 should be enough to all browsers
    testString = (new Array(Math.pow(2, 24))).join("X");

    while (maxLength !== preLength) {
        try  {
            localStorage.setItem(keyName, testString);

            preLength = testString.length;
            maxLength = Math.ceil(preLength + ((hugeString.length - preLength) / 2));

            testString = hugeString.substr(0, maxLength);
        } catch (e) {
            hugeString = testString;

            maxLength = Math.floor(testString.length - (testString.length - preLength) / 2);
            testString = hugeString.substr(0, maxLength);
        }
    }

    localStorage.removeItem(keyName);

    maxLength = JSON.stringify(this.storageObject).length + maxLength + keyName.length - 2;

    return maxLength;
};

Set width to match constraints in ConstraintLayout

in the office doc: https://developer.android.com/reference/android/support/constraint/ConstraintLayout

When a dimension is set to MATCH_CONSTRAINT, the default behavior is to have the resulting size take all the available space.

Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent"

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

Is there a CSS selector for elements containing certain text?

You could set content as data attribute and then use attribute selectors, as shown here:

_x000D_
_x000D_
/* Select every cell containing word "male" */
td[data-content="male"] {
  color: red;
}

/* Select every cell starting on "p" case insensitive */
td[data-content^="p" i] {
  color: blue;
}

/* Select every cell containing "4" */
td[data-content*="4"] {
  color: green;
}
_x000D_
<table>
  <tr>
    <td data-content="Peter">Peter</td>
    <td data-content="male">male</td>
    <td data-content="34">34</td>
  </tr>
  <tr>
    <td data-content="Susanne">Susanne</td>
    <td data-content="female">female</td>
    <td data-content="14">14</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

You can also use jQuery to easily set the data-content attributes:

$(function(){
  $("td").each(function(){
    var $this = $(this);
    $this.attr("data-content", $this.text());
  });
});

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

Should I use encodeURI or encodeURIComponent for encoding URLs?

encodeURIComponent() : assumes that its argument is a portion (such as the protocol, hostname, path, or query string) of a URI. Therefore it escapes the punctuation characters that are used to separate the portionsof a URI.

encodeURI(): is used for encoding existing url

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

$("#yourDialog").dialog({
    draggable: false
});

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

Unable to import a module that is definitely installed

Something that worked for me was:

python -m pip install -user {package name}

The command does not require sudo. This was tested on OSX Mojave.

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

UITableViewCell Selected Background Color on Multiple Selection

Swift 3

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
    cell.selectionStyle = .none
    return cell
}

Swift 2

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
     cell.selectionStyle = .None
     return cell
}

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet, it has nothing to do with the distance between the two routers. The propagation delay is the time taken by a bit to to propagate form one router to the next

php return 500 error but no error log

If you still have 500 error and no logs you can try to execute from command line:

php -f file.php

it will not work exactly like in a browser (from server) but if there is syntax error in your code, you will see error message in console.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

i think this also will be more helpfull.

for the architecture miss match,

i just copy the jdk file from the 32 bit file ?C:\Program Files (x86)\Java\jdk1.7.0_71 and paste it to the 64 bit file ?C:\Program Files\Java\jdk1.7.0_10, then rename the file to match the file you replace to avoid the IDE error(netbeans)

then your good to go.

note: You should buckup you 64bit files so when you want to create 64 bit application you can return it to its location

How to split a string by spaces in a Windows batch file?

see HELP FOR and see the examples

or quick try this

 for /F %%a in ("AAA BBB CCC DDD EEE FFF") do echo %%c

how to redirect to home page

window.location.href = "/";

This worked for me. If you have multiple folders/directories, you can use this:

window.location.href = "/folder_name/";

How to create id with AUTO_INCREMENT on Oracle?

FUNCTION UNIQUE2(
 seq IN NUMBER
) RETURN VARCHAR2
AS
 i NUMBER := seq;
 s VARCHAR2(9);
 r NUMBER(2,0);
BEGIN
  WHILE i > 0 LOOP
    r := MOD( i, 36 );
    i := ( i - r ) / 36;
    IF ( r < 10 ) THEN
      s := TO_CHAR(r) || s;
    ELSE
      s := CHR( 55 + r ) || s;
    END IF;
  END LOOP;
  RETURN 'ID'||LPAD( s, 14, '0' );
END;

Skip certain tables with mysqldump

Dump all databases with all tables but skip certain tables

on github: https://github.com/rubo77/mysql-backup.sh/blob/master/mysql-backup.sh

#!/bin/bash
# mysql-backup.sh

if [ -z "$1" ] ; then
  echo
  echo "ERROR: root password Parameter missing."
  exit
fi
DB_host=localhost
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
#MYSQL_CONN=""

BACKUP_DIR=/backup/mysql/

mkdir $BACKUP_DIR -p

MYSQLPATH=/var/lib/mysql/

IGNORE="database1.table1, database1.table2, database2.table1,"

# strpos $1 $2 [$3]
# strpos haystack needle [optional offset of an input string]
strpos()
{
    local str=${1}
    local offset=${3}
    if [ -n "${offset}" ]; then
        str=`substr "${str}" ${offset}`
    else
        offset=0
    fi
    str=${str/${2}*/}
    if [ "${#str}" -eq "${#1}" ]; then
        return 0
    fi
    echo $((${#str}+${offset}))
}

cd $MYSQLPATH
for i in */; do
    if [ $i != 'performance_schema/' ] ; then 
    DB=`basename "$i"` 
    #echo "backup $DB->$BACKUP_DIR$DB.sql.lzo"
    mysqlcheck "$DB" $MYSQL_CONN --silent --auto-repair >/tmp/tmp_grep_mysql-backup
    grep -E -B1 "note|warning|support|auto_increment|required|locks" /tmp/tmp_grep_mysql-backup>/tmp/tmp_grep_mysql-backup_not
    grep -v "$(cat /tmp/tmp_grep_mysql-backup_not)" /tmp/tmp_grep_mysql-backup

    tbl_count=0
    for t in $(mysql -NBA -h $DB_host $MYSQL_CONN -D $DB -e 'show tables') 
    do
      found=$(strpos "$IGNORE" "$DB"."$t,")
      if [ "$found" == "" ] ; then 
        echo "DUMPING TABLE: $DB.$t"
        mysqldump -h $DB_host $MYSQL_CONN $DB $t --events --skip-lock-tables | lzop -3 -f -o $BACKUP_DIR/$DB.$t.sql.lzo
        tbl_count=$(( tbl_count + 1 ))
      fi
    done
    echo "$tbl_count tables dumped from database '$DB' into dir=$BACKUP_DIR"
    fi
done

With a little help of https://stackoverflow.com/a/17016410/1069083

It uses lzop which is much faster, see:http://pokecraft.first-world.info/wiki/Quick_Benchmark:_Gzip_vs_Bzip2_vs_LZMA_vs_XZ_vs_LZ4_vs_LZO

How to build a query string for a URL in C#?

Assuming that you want to reduce dependencies to other assemblies and to keep things simple, you can do:

var sb = new System.Text.StringBuilder();

sb.Append("a=" + HttpUtility.UrlEncode("TheValueOfA") + "&");
sb.Append("b=" + HttpUtility.UrlEncode("TheValueOfB") + "&");
sb.Append("c=" + HttpUtility.UrlEncode("TheValueOfC") + "&");
sb.Append("d=" + HttpUtility.UrlEncode("TheValueOfD") + "&");

sb.Remove(sb.Length-1, 1); // Remove the final '&'

string result = sb.ToString();

This works well with loops too. The final ampersand removal needs to go outside of the loop.

Note that the concatenation operator is used to improve readability. The cost of using it compared to the cost of using a StringBuilder is minimal (I think Jeff Atwood posted something on this topic).

Why does this iterative list-growing code give IndexError: list assignment index out of range?

You could also use a list comprehension:

j = [l for l in i]

or make a copy of it using the statement:

j = i[:]

How to remove empty lines with or without whitespace in Python

you can simply use rstrip:

    for stuff in largestring:
        print(stuff.rstrip("\n")

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

HTML "overlay" which allows clicks to fall through to elements behind it

I was having this issue when viewing my website on a phone. While I was trying to close the overlay, I was pretty much clicking on anything under the overlay. A solution that I found working for myself is to just add a tag around the entire overlay

Keep values selected after form submission

After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.

But it also works for the Select option. See below for an example. Just try it out and play with it.

<?php
    $example = $_POST["example"];
?>
<form method="post">
    <select name="example">
        <option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
        <option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
        <option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
    </select>
    <input type="submit" name="submit" value="submit" />
</form>

File input 'accept' attribute - is it useful?

Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).

Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.

how to bypass Access-Control-Allow-Origin?

Put this on top of retrieve.php:

header('Access-Control-Allow-Origin: *');

Note that this effectively disables CORS protection, and leaves your users exposed to attack. If you're not completely certain that you need to allow all origins, you should lock this down to a more specific origin:

header('Access-Control-Allow-Origin: https://www.example.com');

Please refer to following stack answer for better understanding of Access-Control-Allow-Origin

https://stackoverflow.com/a/10636765/413670

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Difference between sh and bash

Shell is an interface between a user and OS to access to an operating system's services. It can be either GUI or CLI (Command Line interface).

sh (Bourne shell) is a shell command-line interpreter, for Unix/Unix-like operating systems. It provides some built-in commands. In scripting language we denote interpreter as #!/bin/sh. It was one most widely supported by other shells like bash (free/open), kash (not free).

Bash (Bourne again shell) is a shell replacement for the Bourne shell. Bash is superset of sh. Bash supports sh. POSIX is a set of standards defining how POSIX-compliant systems should work. Bash is not actually a POSIX compliant shell. In a scripting language we denote the interpreter as #!/bin/bash.

Analogy:

  • Shell is like an interface or specifications or API.
  • sh is a class which implements the Shell interface.
  • Bash is a subclass of the sh.

enter image description here

Make TextBox uneditable

If you want to do it using XAML set the property isReadOnly to true.

Trying to start a service on boot on Android

Along with

<action android:name="android.intent.action.BOOT_COMPLETED" />  

also use,

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

HTC devices dont seem to catch BOOT_COMPLETED

Override console.log(); for production

It would be super useful to be able to toggle logging in the production build. The code below turns the logger off by default.

When I need to see logs, I just type debug(true) into the console.

var consoleHolder = console;
function debug(bool){
    if(!bool){
        consoleHolder = console;
        console = {};
        Object.keys(consoleHolder).forEach(function(key){
            console[key] = function(){};
        })
    }else{
        console = consoleHolder;
    }
}
debug(false);

To be thorough, this overrides ALL of the console methods, not just console.log.

Play/pause HTML 5 video using JQuery

<video style="min-width: 100%; min-height: 100%; " id="vid" width="auto" height="auto" controls autoplay="true" loop="loop" preload="auto" muted="muted">
<source src="video/sample.mp4" type="video/mp4">
<source src="video/sample.ogg" type="video/ogg">
</video>
<script> 
$(document).ready(function(){
document.getElementById('vid').play(); });
</script> 

Sharing a variable between multiple different threads

AtomicBoolean

The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: AtomicBoolean.

You can think of the AtomicBoolean class as providing some thread-safety wrapping around a boolean value.

If you instantiate the AtomicBoolean only once, then you need not worry about the visibility issue in the Java Memory Model that requires volatile as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because AtomicBoolean performs that function of protecting multi-threaded access to its internal boolean value.

Let's look at some example code.

Firstly, in modern Java we generally do not address the Thread class directly. We now have the Executors framework to simplify handling of threads.

This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with ExecutorService being AutoCloseable for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.

The idea here is that we have three threads: the original thread, plus a ExecutorService that will create two more threads. The two new threads both report the value of our AtomicBoolean. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the AtomicBoolean object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered AtomicBoolean contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the AtomicBoolean simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the Atomic… classes.

try (
        ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
    AtomicBoolean flag = new AtomicBoolean( true );

    // This task, when run, will immediately report the flag.
    Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );

    // This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
    Runnable task2 = ( ) -> {
        try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
        System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
    };

    executorService.submit( task1 );
    executorService.submit( task2 );

    // Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
    try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
    System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
    flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );

Methods such as AtomicBoolean#get and AtomicBoolean#set are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.

When run:

First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone.2021-01-05T06:42:27.372597Z

Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

In Python How can I declare a Dynamic Array

In Python, a list is a dynamic array. You can create one like this:

lst = [] # Declares an empty list named lst

Or you can fill it with items:

lst = [1,2,3]

You can add items using "append":

lst.append('a')

You can iterate over elements of the list using the for loop:

for item in lst:
    # Do something with item

Or, if you'd like to keep track of the current index:

for idx, item in enumerate(lst):
    # idx is the current idx, while item is lst[idx]

To remove elements, you can use the del command or the remove function as in:

del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list

Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:

 for item in lst[:]: # Notice the [:] which makes a slice
       # Now we can modify lst, since we are iterating over a copy of it

How to get the squared symbol (²) to display in a string

I create equations with random numbers in VBA and for x squared put in x^2.

I read each square (or textbox) text into a string.

I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.

Say the hats were at positions 4, 8 and 12.

I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.

I now select each character in turn and change the font to superscript.

Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.

For big powers like x to the 23 I build x^2^3 and the above routine does it.

Removing items from a list

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
    String a = iter.next();
    if (...) {
        iter.remove();
    }
}

Making an additional assumption that the list is of strings. As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.

Where to find extensions installed folder for Google Chrome on Mac?

You can find all Chrome extensions in below location.

/Users/{mac_user}/Library/Application Support/Google/Chrome/Default/Extensions

How to set Toolbar text and back arrow color

Add this line to Toolbar. 100% working

android:theme="@style/Theme.AppCompat.Light.DarkActionBar"

Regular expressions in C: examples?

Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on this):

#include <regex.h>        
regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, "^a[[:alnum:]]", 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
    puts("Match");
}
else if (reti == REG_NOMATCH) {
    puts("No match");
}
else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
}

/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);

Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.

How can I override inline styles with external CSS?

!important, after your CSS declaration.

div {
   color: blue !important; 

   /* This Is Now Working */
}

Check if a temporary table exists and delete if it exists before creating a temporary table

Instead of dropping and re-creating the temp table you can truncate and reuse it

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    Truncate TABLE #Results
else
    CREATE TABLE #Results
    (
        Company             CHAR(3),
        StepId              TINYINT,
        FieldId             TINYINT,
    )

If you are using Sql Server 2016 or Azure Sql Database then use the below syntax to drop the temp table and recreate it. More info here MSDN

Syntax

DROP TABLE [ IF EXISTS ] [ database_name . [ schema_name ] . | schema_name . ] table_name [ ,...n ]

Query:

DROP TABLE IF EXISTS tempdb.dbo.#Results
CREATE TABLE #Results
  (
   Company             CHAR(3),
   StepId              TINYINT,
   FieldId             TINYINT,
  )

How do I create a shortcut via command-line in Windows?

To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"

Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357

How do I make an html link look like a button?

Why not just wrap an anchor tag around a button element.

<a href="somepage.html"><button type="button">Text of Some Page</button></a>

This will work for IE9+, Chrome, Safari, Firefox, and probably Opera.

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

How to check if a string "StartsWith" another string?

data.substring(0, input.length) === input

Hide text within HTML?

This will keep its space, but not show anything;

opacity: 0.0;

This will hide the object fully, plus its (reserved) space;

display: none;

MySQL Database won't start in XAMPP Manager-osx

If these commands don't work for you:

sudo killall mysqld
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

Try this:

For XAMPP 7.1.1-0, I changed the port number from 3306 to 3307.

  1. Click on Manage Servers
  2. Select MySQL Database
  3. Click on Configure on your right
  4. Change your port number to 3307
  5. Click OK
  6. Close your Control Panel and relaunch it.

You are now good to go.

Get variable from PHP to JavaScript

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>

How to read .pem file to get private and public key

Java supports using DER for public and private keys out of the box (which is basically the same as PEM, as the OP asks, except PEM files contain base 64 data plus header and footer lines).

You can rely on this code (modulo exception handling) without any external library if you are on Java 8+ (this assumes your key files are available in the classpath):

class Signer {
    private KeyFactory keyFactory;

    public Signer() {
        this.keyFactory = KeyFactory.getInstance("RSA");
    }

    public PublicKey getPublicKey() {
        byte[] publicKey = readFileAsBytes("public-key.der");

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

        return keyFactory.generatePublic(keySpec);
    }

    public PrivateKey getPrivateKey() {
        byte[] privateKey = readFileAsBytes("private-key.der");

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    
        return keyFactory.generatePrivate(keySpec);
    }

    private URI readFileAsBytes(String name) {
        URI fileUri = getClass().getClassLoader().getResource(name).toURI();

        return Files.readAllBytes(Paths.get(fileUri));
    }
}

For the record, you can convert a PEM key to a DER key with the following command:

$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private-key.pem -out private-key.der -nocrypt

And get the public key in DER with:

$ openssl rsa -in private-key.pem -pubout -outform DER -out public-key.der

HTML embed autoplay="false", but still plays automatically

<embed ... autostart="0">

Replace false with 0

How can I disable inherited css styles?

Cascading Style Sheet are designed for inheritance. Inheritance is intrinsic to their existence. If it wasn't built to be cascading, they would only be called "Style Sheets".

That said, if an inherited style doesn't fit your needs, you'll have to override it with another style closer to the object. Forget about the notion of "blocking inheritance".

You can also choose the more granular solution by giving styles to every individual objects, and not giving styles to the general tags like div, p, pre, etc.

For example, you can use styles that start with # for objects with a specific ID:

<style>
#dividstyle{
    font-family:MS Trebuchet;
}
</style>
<div id="dividstyle">Hello world</div>

You can define classes for objects:

<style>
.divclassstyle{
    font-family: Calibri;
}
</style>
<div class="divclassstyle">Hello world</div>

Hope it helps.

Does calling clone() on an array also clone its contents?

The clone is a shallow copy of the array.

This test code prints:

[1, 2] / [1, 2]
[100, 200] / [100, 2]

because the MutableInteger is shared in both arrays as objects[0] and objects2[0], but you can change the reference objects[1] independently from objects2[1].

import java.util.Arrays;                                                                                                                                 

public class CloneTest {                                                                                                                                 
    static class MutableInteger {                                                                                                                        
        int value;                                                                                                                                       
        MutableInteger(int value) {                                                                                                                      
            this.value = value;                                                                                                                          
        }                                                                                                                                                
        @Override                                                                                                                                        
        public String toString() {                                                                                                                       
            return Integer.toString(value);                                                                                                              
        }                                                                                                                                                
    }                                                                                                                                                    
    public static void main(String[] args) {                                                                                                             
        MutableInteger[] objects = new MutableInteger[] {
                new MutableInteger(1), new MutableInteger(2) };                                                
        MutableInteger[] objects2 = objects.clone();                                                                                                     
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                                
        objects[0].value = 100;                                                                                                                          
        objects[1] = new MutableInteger(200);                                                                                                            
        System.out.println(Arrays.toString(objects) + " / " + 
                            Arrays.toString(objects2));                                                               
    }                                                                                                                                                    
}                                                                                                                                                        

Generic type conversion FROM string

Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion.

Seems to work for me:

public object Get( string _toparse, Type _t )
{
    // Test for Nullable<T> and return the base type instead:
    Type undertype = Nullable.GetUnderlyingType(_t);
    Type basetype = undertype == null ? _t : undertype;
    return Convert.ChangeType(_toparse, basetype);
}

public T Get<T>(string _key)
{
    return (T)Get(_key, typeof(T));
}

public void test()
{
    int x = Get<int>("14");
    int? nx = Get<Nullable<int>>("14");
}

Retrieve the commit log for a specific line in a file?

In my case the line number had changed a lot over time. I was also on git 1.8.3 which does not support regex in "git blame -L". (RHEL7 still has 1.8.3)

myfile=haproxy.cfg
git rev-list HEAD -- $myfile | while read i
do
    git diff -U0 ${i}^ $i $myfile | sed "s/^/$i /"
done | grep "<sometext>"

Oneliner:

myfile=<myfile> ; git rev-list HEAD -- $myfile | while read i; do     git diff -U0 ${i}^ $i $myfile | sed "s/^/$i /"; done | grep "<sometext>"

This can of course be made into a script or a function.

iptables LOG and DROP in one rule

Example:

iptables -A INPUT -j LOG --log-prefix "INPUT:DROP:" --log-level 6
iptables -A INPUT -j DROP

Log Exampe:

Feb 19 14:18:06 servername kernel: INPUT:DROP:IN=eth1 OUT= MAC=aa:bb:cc:dd:ee:ff:11:22:33:44:55:66:77:88 SRC=x.x.x.x DST=x.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=117 ID=x PROTO=TCP SPT=x DPT=x WINDOW=x RES=0x00 SYN URGP=0

Other options:

   LOG
       Turn on kernel logging of matching packets.  When this option 
       is set for a rule, the Linux kernel will print some 
       information  on  all  matching  packets
       (like most IP header fields) via the kernel log (where it can 
       be read with dmesg or syslogd(8)).  This is a "non-terminating 
       target", i.e. rule traversal
       continues at the next rule.  So if you want to LOG the packets 
       you refuse, use two separate rules with the same matching 
       criteria, first using target LOG
       then DROP (or REJECT).

       --log-level level
              Level of logging (numeric or see syslog.conf(5)).

       --log-prefix prefix
              Prefix log messages with the specified prefix; up to 29 
              letters long, and useful for distinguishing messages in 
              the logs.

       --log-tcp-sequence
              Log TCP sequence numbers. This is a security risk if the 
              log is readable by users.

       --log-tcp-options
              Log options from the TCP packet header.

       --log-ip-options
              Log options from the IP packet header.

       --log-uid
              Log the userid of the process which generated the packet.

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

I think, there is something wrong with PHP configration.
First, debug your database connection using this script at the end of ./config/database.php :

...
  ...
  ...
  echo '<pre>';
  print_r($db['default']);
  echo '</pre>';

  echo 'Connecting to database: ' .$db['default']['database'];
  $dbh=mysql_connect
  (
    $db['default']['hostname'],
    $db['default']['username'],
    $db['default']['password'])
    or die('Cannot connect to the database because: ' . mysql_error());
    mysql_select_db ($db['default']['database']);

    echo '<br />   Connected OK:'  ;
    die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); 

Then see what the problem is.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

hide div tag on mobile view only?

try this

@media handheld{
    #title_message { display: none; }
}

What is the difference between C++ and Visual C++?

What is the difference between c++ and visaul c++?

Visual C++ is an IDE. There's also C++Builder from Embarcadero. (Used to be Borland.) There are also a few other C++ IDE's.

I know that c++ has the portability and all so if you know c++ how is it related to visual c++?

C++ is as portable as the libraries that you use in your C++ application. VC++ has some specialized libraries to use with Windows, so if you use those libraries in your C++ application, you're stuck with Windows. But a simple "Hello, World" application that just uses the console as output can be compiled on Windows, Linux, VMS, AS/400, Smartphones, FreeBSD, MS-DOS, CP80 and almost any other system for which you can find a C++ compiler. Injteresting fact: at http://nethack.org/ you can download the C sourcecode for an almost antique game, where you have to walk through a bunch of mazes, kick some monsters around, find treasures and steal some valuable amulet and bring that amulet back out. (It's also a game where you can encounter your characters from previous, failed attempts to get that amulet. :-) The sourcecode of NetHack is a fine example of how portable C (C++) code can be.

Is visual c++ mostly for online apps?

No. But it can be used for online apps. Actually, C# is used more often for server-side web applications while C++ (VC++) is used for all kinds of (server) components that your application will be depending upon.

Would visual basic be better for desktop applications?

Or Embarcadero Delphi. Delphi and Basic are languages that are easier to learn than C++ and both have very good IDE's to develop GUI applications with. Unfortunately, Visual Basic is now running on .NET only, while there are still many developers who need to create WIN32 applications. Those developers often have to choose between Delphi or C++ or else convince management to move to .NET development.

What is the correct way to create a single-instance WPF application?

Not using Mutex though, simple answer:

System.Diagnostics;    
...
string thisprocessname = Process.GetCurrentProcess().ProcessName;

if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                return;

Put it inside the Program.Main().
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Sample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //simple add Diagnostics namespace, and these 3 lines below 
            string thisprocessname = Process.GetCurrentProcess().ProcessName;
            if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
                return;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample());
        }
    }
}

You can add MessageBox.Show to the if-statement and put "Application already running".
This might be helpful to someone.

How do I convert datetime to ISO 8601 in PHP

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21

How to set image to fit width of the page using jsPDF?

        var width = doc.internal.pageSize.width;    
        var height = doc.internal.pageSize.height;

How to pass a JSON array as a parameter in URL

& is a keyword for the next parameter like this ur?param1=1&param2=2

so effectively you send a second param named R". You should urlencode your string. Isn't POST an option?

How to do a SUM() inside a case statement in SQL server

You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.

WITH PercentageOfTotal (Id, Percentage) 
AS 
(
    SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT 
    CASE
        WHEN o.TotalType = 'Average' THEN r.avgscore
        WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
        ELSE o.cnt
    END AS [displayscore]
FROM PercentageOfTotal pt
    JOIN dbo.MyTable t ON pt.Id = t.Id

Save range to variable

To save a range and then call it later, you were just missing the "Set"

Set Remember_Range = Selection    or    Range("A3")
Remember_Range.Activate

But for copying and pasting, this quicker. Cuts out the middle man and its one line

Sheets("Copy").Range("A3").Value = Sheets("Paste").Range("A3").Value

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

map vs. hash_map in C++

Some of the key differences are in the complexity requirements.

  • A map requires O(log(N)) time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.

  • An unordered_map requires an 'average' time of O(1) for inserts and finds, but is allowed to have a worst-case time of O(N). This is because it's implemented using Hash Table data structure.

So, usually, unordered_map will be faster, but depending on the keys and the hash function you store, can become much worse.

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Make can tell you what it knows and what it will do. Suppose you have an "install" target, which executes commands like:

cp <filelist> <destdir>/

In your generic rules, add:

uninstall :; MAKEFLAGS= ${MAKE} -j1 -spinf $(word 1,${MAKEFILE_LIST}) install \
              | awk '/^cp /{dest=$NF; for (i=NF; --i>0;) {print dest"/"$i}}' \
              | xargs rm -f

A similar trick can do a generic make clean.

How do I start a process from C#?

I used the following in my own program.

Process.Start("http://www.google.com/etc/etc/test.txt")

It's a bit basic, but it does the job for me.

How do I get the application exit code from a Windows command line?

It might not work correctly when using a program that is not attached to the console, because that app might still be running while you think you have the exit code. A solution to do it in C++ looks like below:

#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "tchar.h"
#include "stdio.h"
#include "shellapi.h"

int _tmain( int argc, TCHAR *argv[] )
{

    CString cmdline(GetCommandLineW());
    cmdline.TrimLeft('\"');
    CString self(argv[0]);
    self.Trim('\"');
    CString args = cmdline.Mid(self.GetLength()+1);
    args.TrimLeft(_T("\" "));
    printf("Arguments passed: '%ws'\n",args);
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc < 2 )
    {
        printf("Usage: %s arg1,arg2....\n", argv[0]);
        return -1;
    }

    CString strCmd(args);
    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        (LPTSTR)(strCmd.GetString()),        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d)\n", GetLastError() );
        return GetLastError();
    }
    else
        printf( "Waiting for \"%ws\" to exit.....\n", strCmd );

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );
    int result = -1;
    if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))
    { 
        printf("GetExitCodeProcess() failed (%d)\n", GetLastError() );
    }
    else
        printf("The exit code for '%ws' is %d\n",(LPTSTR)(strCmd.GetString()), result );
    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
    return result;
}

Rails: Adding an index after adding column

For references you can call

rails generate migration AddUserIdColumnToTable user:references

If in the future you need to add a general index you can launch this

rails g migration AddOrdinationNumberToTable ordination_number:integer:index

Generate code:

class AddOrdinationNumberToTable < ActiveRecord::Migration
  def change
   add_column :tables, :ordination_number, :integer
   add_index :tables, :ordination_number, unique: true
  end
end

Remove Select arrow on IE

I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.

Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.

Anyway, let's start with the modern browsers and then we will see the solution for the older ones.

Drop-down Arrow for Chrome, Firefox, Opera, Internet Explorer 10+

For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.

To do so, you have to reset the browser's default style for the select tag and set new background rules (like suggested before).

select {
    /* you should keep these firsts rules in place to maintain cross-browser behaviour */
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    appearance: none;
    background-image: url('<custom_arrow_image_url_here>');
    background-position: 98% center;
    background-repeat: no-repeat;
    outline: none;
    ...
}

The appearance rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.

The background rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).

In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.

Drop-down Arrow for Internet Explorer 8 (IE8) and Internet Explorer 9 (IE9) using Icon Font

This is the harder part... Or maybe not.

There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select CSS rule for more details about the inline SVG used).

The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html tag to recognize the older IE browser.

After that, every select in the HTML have to be wrapped by a div (or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.

<div class="selectTagWrapper prefix-icon-arrow-down-fill">
    ...
</div>

In easy words, this wrapper is used to simulate the select tag.

To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select.

Notice that we cannot use the select border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden rule applied to the select itself.

The custom arrow icon-font is placed in the pseudo class :before where the rule content contains the reference for the arrow (in this case it is a right parenthesis).

We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).

.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
    content: ")";
    position: absolute;
    top: 43%;
    left: 93%;
    font-size: 6px;
    ...
}

You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image rule or making a new icon font file by yourself.

Design Patterns web based applications

I have used the struts framework and find it fairly easy to learn. When using the struts framework each page of your site will have the following items.

1) An action which is used is called every time the HTML page is refreshed. The action should populate the data in the form when the page is first loaded and handles interactions between the web UI and the business layer. If you are using the jsp page to modify a mutable java object a copy of the java object should be stored in the form rather than the original so that the original data doesn't get modified unless the user saves the page.

2) The form which is used to transfer data between the action and the jsp page. This object should consist of a set of getter and setters for attributes that need to be accessible to the jsp file. The form also has a method to validate data before it gets persisted.

3) A jsp page which is used to render the final HTML of the page. The jsp page is a hybrid of HTML and special struts tags used to access and manipulate data in the form. Although struts allows users to insert Java code into jsp files you should be very cautious about doing that because it makes your code more difficult to read. Java code inside jsp files is difficult to debug and can not be unit tested. If you find yourself writing more than 4-5 lines of java code inside a jsp file the code should probably be moved to the action.

PHP - auto refreshing page

Try out this as well. Your page will refresh every 10sec

<html>
 <head>

  <meta http-equiv="refresh" content="10; url="<?php echo $_SERVER['PHP_SELF']; ?>">
 </head>
 <body>

 </body>
</html>

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:

Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!

How can I remove the last character of a string in python?

As you say, you don't need to use a regex for this. You can use rstrip.

my_file_path = my_file_path.rstrip('/')

If there is more than one / at the end, this will remove all of them, e.g. '/file.jpg//' -> '/file.jpg'. From your question, I assume that would be ok.

Installing Pandas on Mac OSX

You need to install newest version of xCode from appStore. It contains the compiler for C(gcc) and C++(g++) for mac. Then you can install pandas without any problem. Use the following commands in terminal:

  1. xcode-select --install

  2. pip3 install pandas

It might take some time as it installs other packages too. Please be patient.

Get the value of checked checkbox?

I am using this in my code.Try this

var x=$("#checkbox").is(":checked");

If the checkbox is checked x will be true otherwise it will be false.

error opening trace file: No such file or directory (2)

I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.

What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).

screenshot of the AVD creation screen

Additional information:

while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:

"/Applications/Android Studio.app/sdk/tools/emulator" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none

WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img

I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.

JavaScript: Class.method vs. Class.prototype.method

Yes, the first one is a static method also called class method, while the second one is an instance method.

Consider the following examples, to understand it in more detail.

In ES5

function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
}

Person.isPerson = function(obj) {
   return obj.constructor === Person;
}

Person.prototype.sayHi = function() {
   return "Hi " + this.firstName;
}

In the above code, isPerson is a static method, while sayHi is an instance method of Person.

Below, is how to create an object from Person constructor.

var aminu = new Person("Aminu", "Abubakar");

Using the static method isPerson.

Person.isPerson(aminu); // will return true

Using the instance method sayHi.

aminu.sayHi(); // will return "Hi Aminu"

In ES6

class Person {
   constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   static isPerson(obj) {
      return obj.constructor === Person;
   }

   sayHi() {
      return `Hi ${this.firstName}`;
   }
}

Look at how static keyword was used to declare the static method isPerson.

To create an object of Person class.

const aminu = new Person("Aminu", "Abubakar");

Using the static method isPerson.

Person.isPerson(aminu); // will return true

Using the instance method sayHi.

aminu.sayHi(); // will return "Hi Aminu"

NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.

Getting "cannot find Symbol" in Java project in Intellij

This works for me, say class A depends on class B(and class c, d etc) but the error throws on class A which does not have any errors. So I try to compile class A alone first ->it shows error on the package of class B. So tried to compile whole package of class B. Now it throws which is the exact error class(on my case class B had error). Usually Intellj shows the exact error class with line number when compile/build. On some occasions it throws error in wrong place/class. Have a try.

No connection could be made because the target machine actively refused it (PHP / WAMP)

You might need:

  • In wamp\bin\mysql\mysqlX.X.XX\my.ini find these lines:

    [client] ... port = 3308 ... [wampmysqld64] ... port = 3308

As you see, the port number is 3308. You should :

  • use that port in applications, like WordPress: define('DB_HOST', 'localhost:3308')

or

  • change it globally in wamp\bin\apache\apache2.X.XXX\bin\php.ini change mysqli.default_port = ... to 3308

How to embed an autoplaying YouTube video in an iframe?

<iframe width="560" height="315" 
        src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1" 
        frameborder="0" allowfullscreen></iframe>

Can I mask an input text in a bat file?

You can set the forground color to black such:

:: see https://stackoverflow.com/questions/33293220/what-is-the-fastest-color-function-in-batch
@echo off
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
set color_white=%ESC%[37m
set color_black=%ESC%[30m
echo(
set /p user=Username:
set /p pass=password:%color_black%
echo %color_white%
echo blablablba

Enjoy!!! C.

How to show shadow around the linearlayout in Android?

  1. save this 9.png. (change name it to 9.png)

enter image description here

2.save it in your drawable.

3.set it to your layout.

4.set padding.

For example :

<LinearLayout  
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="@drawable/shadow"
  android:paddingBottom="6dp"
  android:paddingLeft="5dp"
  android:paddingRight="5dp"
  android:paddingTop="6dp"
>

.
.
.
</LinearLayout>

How to handle onchange event on input type=file in jQuery?

Demo : http://jsfiddle.net/NbGBj/

$("document").ready(function(){

    $("#upload").change(function() {
        alert('changed!');
    });
});

CSS background-size: cover replacement for Mobile Safari

I've had this issue on a lot of mobile views I've recently built.

My solution is still a pure CSS Fallback

http://css-tricks.com/perfect-full-page-background-image/ as three great methods, the latter two are fall backs for when CSS3's cover doesn't work.

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspect ratio */
  min-width: 100%;
  min-height: 100%;
}

How to use hex() without 0x in Python?

>>> format(3735928559, 'x')
'deadbeef'

Visual Studio move project to a different folder

Remove the project from your solution by right-clicking it in the Solution Explorer window and choosing Remove. Move the entire project folder, including subdirectories wherever you want it to go. Add the project back to your solution.

Namespace names is something completely different, just edit the source code.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

Should __init__() call the parent class's __init__()?

In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"

It's incredible: he is wording exactly the contrary of the principle of inheritance.


It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__

So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??

It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.
In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.
NOT the contrary.


Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ . That's exactly what is said in the official doc:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance

That's all the story:

  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class

  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class

  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__


What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.

MySQL: is a SELECT statement case sensitive?

Try with:

order by lower(column_name) asc;

How to fire an event when v-model changes?

You can actually simplify this by removing the v-on directives:

<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">

And use the watch method to listen for the change:

new Vue ({
    el: "#app",
    data: {
        cases: [
            { name: 'case A', status: '1' },
            { name: 'case B', status: '0' },
            { name: 'case C', status: '1' }
        ],
        activeCases: [],
        srStatus: ''
    },
    watch: {
        srStatus: function(val, oldVal) {
            for (var i = 0; i < this.cases.length; i++) {
                if (this.cases[i].status == val) {
                    this.activeCases.push(this.cases[i]);
                    alert("Fired! " + val);
                }
            }
        }
    }
});

Why do I get permission denied when I try use "make" to install something?

Execute chmod 777 -R scripts/, it worked fine for me ;)

SVG rounded corner

Not sure why nobody posted an actual SVG answer. Here is an SVG rectangle with rounded corners (radius 3) on the top:

<svg:path d="M0,0 L0,27 A3,3 0 0,0 3,30 L7,30 A3,3 0 0,0 10,27 L10,0 Z" />

This is a Move To (M), Line To (L), Arc To (A), Line To (L), Arc To (A), Line To (L), Close Path (Z).

The comma-delimited numbers are absolute coordinates. The arcs are defined with additional parameters specifying the radius and type of arc. This could also be accomplished with relative coordinates (use lower-case letters for L and A).

The complete reference for those commands is on the W3C SVG Paths page, and additional reference material on SVG paths can be found in this article.

Initialize Array of Objects using NSArray

There is also a shorthand of doing this:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

DBMS_OUTPUT.PUT_LINE not printing

  1. Ensure that you have your Dbms Output window open through the view option in the menubar.
  2. Click on the green '+' sign and add your database name.
  3. Write 'DBMS_OUTPUT.ENABLE;' within your procedure as the first line. Hope this solves your problem.

Object of class stdClass could not be converted to string - laravel

I was recieving the same error when I was tring to call an object element by using another objects return value like;

$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes

$this->array2->$this->array1->country;// Error line

The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;

$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes

$this->array2->{$this->array1->country};

If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

The following has worked for me very well:

$("#button").attr('disabled', 'disabled');

Count number of lines in a git repository

I was playing around with cmder (http://gooseberrycreative.com/cmder/) and I wanted to count the lines of html,css,java and javascript. While some of the answers above worked, or pattern in grep didn't - I found here (https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns) that I had to escape it

So this is what I use now:

git ls-files | grep "\(.html\|.css\|.js\|.java\)$" | xargs wc -l

How do you convert a time.struct_time object into a datetime object?

This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct_time object is providing, vs. what other time fields may have.

Assuming you have both a time.struct_time object, and some other date/time string, compare the two, and be sure you are not losing data and inadvertently creating a naive datetime object, when you can do otherwise.

For example, the excellent feedparser module will return a "published" field and may return a time.struct_time object in its "published_parsed" field:

time.struct_time(tm_year=2013, tm_mon=9, tm_mday=9, tm_hour=23, tm_min=57, tm_sec=42, tm_wday=0, tm_yday=252, tm_isdst=0)

Now note what you actually get with the "published" field.

Mon, 09 Sep 2013 19:57:42 -0400

By Stallman's Beard! Timezone information!

In this case, the lazy man might want to use the excellent dateutil module to keep the timezone information:

from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()

which gives us:

published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00

One could then use the timezone-aware datetime object to normalize all time to UTC or whatever you think is awesome.

Is optimisation level -O3 dangerous in g++?

Recently I experienced a problem using optimization with g++. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:

unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
    pciMemory[ 0 ] = someCommand[ i ];

The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ] into pciMemory, omitting all preceding writes.

In conclusion: be accurate and attentive with optimization.

How to fluently build JSON in Java?

If you are using Jackson do a lot of JsonNode building in code, you may be interesting in the following set of utilities. The benefit of using them is that they support a more natural chaining style that better shows the structure of the JSON under construction.

Here is an example usage:

import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;

...

val request = object("x", "1").with("y", array(object("z", "2"))).end();

Which is equivalent to the following JSON:

{"x":"1", "y": [{"z": "2"}]}

Here are the classes:

import static lombok.AccessLevel.PRIVATE;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

/**
 * Convenience {@link JsonNode} builder.
 */
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {

  /**
   * Factory methods for an {@link ObjectNode} builder.
   */

  public static ObjectNodeBuilder object() {
    return object(JsonNodeFactory.instance);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
    return object(k1, v1).with(k2, v2);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
      @NonNull String k3, String v3) {
    return object(k1, v1, k2, v2).with(k3, v3);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
    return object().with(k1, builder);
  }

  public static ObjectNodeBuilder object(JsonNodeFactory factory) {
    return new ObjectNodeBuilder(factory);
  }

  /**
   * Factory methods for an {@link ArrayNode} builder.
   */

  public static ArrayNodeBuilder array() {
    return array(JsonNodeFactory.instance);
  }

  public static ArrayNodeBuilder array(@NonNull boolean... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull int... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull String... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
    return array().with(builders);
  }

  public static ArrayNodeBuilder array(JsonNodeFactory factory) {
    return new ArrayNodeBuilder(factory);
  }

  public interface JsonNodeBuilder<T extends JsonNode> {

    /**
     * Construct and return the {@link JsonNode} instance.
     */
    T end();

  }

  @RequiredArgsConstructor
  private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {

    /**
     * The source of values.
     */
    @NonNull
    protected final JsonNodeFactory factory;

    /**
     * The value under construction.
     */
    @NonNull
    protected final T node;

    /**
     * Returns a valid JSON string, so long as {@code POJONode}s not used.
     */
    @Override
    public String toString() {
      return node.toString();
    }

  }

  public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {

    private ObjectNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.objectNode());
    }

    public ObjectNodeBuilder withNull(@NonNull String field) {
      return with(field, factory.nullNode());
    }

    public ObjectNodeBuilder with(@NonNull String field, int value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, float value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, boolean value) {
      return with(field, factory.booleanNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, String value) {
      return with(field, factory.textNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
      node.set(field, value);
      return this;
    }

    public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
      return with(field, builder.end());
    }

    public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
      return with(field, factory.pojoNode(pojo));
    }

    @Override
    public ObjectNode end() {
      return node;
    }

  }

  public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {

    private ArrayNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.arrayNode());
    }

    public ArrayNodeBuilder with(boolean value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull boolean... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(int value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull int... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(float value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(String value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull String... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNode value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull JsonNode... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
      return with(value.end());
    }

    public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
      for (val builder : builders)
        with(builder);
      return this;
    }

    @Override
    public ArrayNode end() {
      return node;
    }

  }

}

Note that the implementation uses Lombok, but you can easily desugar it to fill in the Java boilerplate.

C# cannot convert method to non delegate type

You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.

string t = obj.getTitle();

Extra Non-Essential Information

Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle() and setTitle(string value), but you could do it like this:

public string Title // Note: public fields, methods and properties use PascalCasing
{
    get // This replaces your getTitle method
    {
        return _title; // Where _title is a field somewhere
    }
    set // And this replaces your setTitle method
    {
        _title = value; // value behaves like a method parameter
    }
}

Or you could use auto-implemented properties, which would use this by default:

public string Title { get; set; }

And you wouldn't have to create your own backing field (_title), the compiler would create it itself.

Also, you can change access levels for property accessors (getters and setters):

public string Title { get; private set; }

You use properties as if they were fields, i.e.:

this.Title = "Example";
string local = this.Title;

std::enable_if to conditionally compile a member function

From this post:

Default template arguments are not part of the signature of a template

But one can do something like this:

#include <iostream>

struct Foo {
    template < class T,
               class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
    void f(const T& value)
    {
        std::cout << "Not int" << std::endl;
    }

    template<class T,
             class std::enable_if<std::is_integral<T>::value, int>::type = 0>
    void f(const T& value)
    {
        std::cout << "Int" << std::endl;
    }
};

int main()
{
    Foo foo;
    foo.f(1);
    foo.f(1.1);

    // Output:
    // Int
    // Not int
}

pandas dataframe columns scaling with sklearn

You can do it using pandas only:

In [235]:
dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],'B':[103.02,107.26,110.35,114.23,114.68], 'C':['big','small','big','small','small']})
df = dfTest[['A', 'B']]
df_norm = (df - df.min()) / (df.max() - df.min())
print df_norm
print pd.concat((df_norm, dfTest.C),1)

          A         B
0  0.000000  0.000000
1  0.926219  0.363636
2  0.935335  0.628645
3  1.000000  0.961407
4  0.938495  1.000000
          A         B      C
0  0.000000  0.000000    big
1  0.926219  0.363636  small
2  0.935335  0.628645    big
3  1.000000  0.961407  small
4  0.938495  1.000000  small

How to decompile to java files intellij idea

As of August 2017 and IntelliJ V2017.2, the accepted answer does not seem to be entirely accurate anymore: there is no fernflower.jar to use.

The jar file is called java-decompiler.jar and does not include a main manifest... Instead you can use the following command (from a Mac install):

java -cp "/Applications/IntelliJ IDEA.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler

(you will get the wrong Usage command, but it does work).

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

Change your default port in [tomcat_home_dir]/conf/server.xml find

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

change it to

<Connector port="8090" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

Using Helvetica Neue in a Website

I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:

http://css-tricks.com/snippets/css/better-helvetica/

He basically recommends the following declaration for covering all the bases:

body {
    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
    font-weight: 300;
}

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

How to make a JSONP request from Javascript without JQuery?

If you are using ES6 with NPM, you can try node module "fetch-jsonp". Fetch API Provides support for making a JsonP call as a regular XHR call.

Prerequisite: you should be using isomorphic-fetch node module in your stack.

Jquery : Refresh/Reload the page on clicking a button

You can also use window.location.href=window.location.href;

What is the "hasClass" function with plain JavaScript?

You can check whether element.className matches /\bthatClass\b/.
\b matches a word break.

Or, you can use jQuery's own implementation:

var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 ) 

To answer your more general question, you can look at jQuery's source code on github or at the source for hasClass specifically in this source viewer.

How to change Visual Studio 2012,2013 or 2015 License Key?

For me, with Visual Studio 2013, it wasn't enough to remove the license key and perform a repair (the repair restored the license key instead of reverting to a trial, and running it without the repair (after deleting the key) claimed the license had expired but wouldn't let me enter a new key).

I had to:

  • Discover what license key Visual Studio was looking for in the registry with Process Monitor (it was HKCR\Licenses\E79B3F9C-6543-4897-BBA5-5BFB0A02BB5C)
  • Completely uninstall Visual Studio 2013 (save CurrentSettings.vssettings first)
  • Delete the license key from the registry by hand in regedit
  • Install Visual Studio using the publicly available web installer (which doesn't have any baked-in license key -- it installs a 30-day trial)
  • Enter my new license key
  • (Re-)install updates (Update 1 at this time)
  • Restore settings by importing the backup I made of CurrentSettings.vssettings

Link to reload current page

<a href="<?php echo $_SERVER["REQUEST_URI"]; ?>">Click me</a>

Get day of week in SQL Server 2005/2008

Use DATENAME or DATEPART:

SELECT DATENAME(dw,GETDATE()) -- Friday
SELECT DATEPART(dw,GETDATE()) -- 6

Rounded Corners Image in Flutter

user decoration Image for a container.

  @override
  Widget build(BuildContext context) {
    final alucard = Container(
        decoration: new BoxDecoration(
        borderRadius: BorderRadius.circular(10),
          image: new DecorationImage(
              image: new AssetImage("images/logo.png"),
              fit: BoxFit.fill,
          )
        )
    );

How do I check to see if my array includes an object?

Why not do it simply by picking eight different numbers from 0 to Horse.count and use that to get your horses?

offsets = (0...Horse.count).to_a.sample(8)
@suggested_horses = offsets.map{|i| Horse.first(:offset => i) }

This has the added advantage that it won't cause an infinite loop if you happen to have less than 8 horses in your database.

Note: Array#sample is new to 1.9 (and coming in 1.8.8), so either upgrade your Ruby, require 'backports' or use something like shuffle.first(n).

How to concatenate string variables in Bash

I wanted to build a string from a list. Couldn't find an answer for that so I post it here. Here is what I did:

list=(1 2 3 4 5)
string=''

for elm in "${list[@]}"; do
    string="${string} ${elm}"
done

echo ${string}

and then I get the following output:

1 2 3 4 5

Creating/writing into a new file in Qt

It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.

In that case, it might be that you program exits before the writing can be finished.

If your program uses an event loop (like with a GUI application, e.g. QMainWindow) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).

stream << "something" << endl;
stream.flush();

This guarantees that the changes are committed to the file before the program continues from this instruction.

The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.

How to update /etc/hosts file in Docker image during "docker build"

Tis is me Dockefile
FROM XXXXX
ENV DNS_1="10.0.0.1 TEST1.COM"
ENV DNS_1="10.0.0.1 TEST2.COM" 
CMD ["bash","change_hosts.sh"]`

#cat change_hosts.sh
su - root -c "env | grep DNS | akw -F "=" '{print $2}' >> /etc/hosts"
  • info
  • user must su

ORA-00972 identifier is too long alias column name

No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the Oracle SQL Language Reference.

However, from version 12.2 they can be up to 128 bytes long. (Note: bytes, not characters).

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

It stopped after publishing on the production server. The reason why it showed me this error was because it was deployed to a subfolder. In IIS i clicked right on the subfolder and excuted "Convert to application" and after this it worked.

Submit form after calling e.preventDefault()

came across the same prob and found no straight solution to it on the forums etc. Finally the following solution worked perfectly for me: simply implement the following logic inside your event handler function for the form 'submit' Event:

document.getElementById('myForm').addEventListener('submit', handlerToTheSubmitEvent);

function handlerToTheSubmitEvent(e){
    //DO NOT use e.preventDefault();
   
    /*
    your form validation logic goes here
    */

    if(allInputsValidatedSuccessfully()){
         return true;
     }
     else{
         return false; 
     }
}

SIMPLE AS THAT; NOTE: when a 'false' is returned from the handler of the form 'submit' event, the form is not submitted to the URI specified in the action attribute of your html markup; until and unless a 'true' is returned by the handler; and as soon as all your input fields are validated a 'true' will be returned by the Event handler, and your form is gonna be submitted;

ALSO NOTE THAT: the function call inside the if() condition is basically your own implementation of ensuring that all the fields are validated and consequently a 'true' must be returned from there otherwise 'false'

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

As of jackson 2.7.4 (or earlier maybe), the class is in jacskon-jaxrs-base.jar, which is contained in jackson-jaxrs-json-provider

How to read file with async/await properly?

To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

const fs = require('fs');
const util = require('util');

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

function getStuff() {
  return readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

Compiler error "archive for required library could not be read" - Spring Tool Suite

Delete corrupted files from your local .m2 repository and Ctrl+F5 (Update Maven Project) in Eclipse/STS. It'll download and install these files.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Android Studio Run/Debug configuration error: Module not specified

I realized following line was missing in settings.gradle file

include ':app'

make sure you include ":app" module

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

Installing Node.js (and npm) on Windows 10

The reason why you have to modify the AppData could be:

  1. Node.js couldn't handle path longer then 256 characters, windows tend to have very long PATH.
  2. If you are login from a corporate environment, your AppData might be on the server - that won't work. The npm directory must be in your local drive.

Even after doing that, the latest LTE (4.4.4) still have problem with Windows 10, it worked for a little while then whenever I try to:

$ npm install _some_package_ --global 

Node throw the "FATAL ERROR CALL_AND_RETRY_LAST Allocation failed - process out of memory" error. Still try to find a solution to that problem.

The only thing I find works is to run Vagrant or Virtual box, then run the Linux command line (must matching the path) which is quite a messy solution.

Is "delete this" allowed in C++?

This is an old, answered, question, but @Alexandre asked "Why would anyone want to do this?", and I thought that I might provide an example usage that I am considering this afternoon.

Legacy code. Uses naked pointers Obj*obj with a delete obj at the end.

Unfortunately I need sometimes, not often, to keep the object alive longer.

I am considering making it a reference counted smart pointer. But there would be lots of code to change, if I was to use ref_cnt_ptr<Obj> everywhere. And if you mix naked Obj* and ref_cnt_ptr, you can get the object implicitly deleted when the last ref_cnt_ptr goes away, even though there are Obj* still alive.

So I am thinking about creating an explicit_delete_ref_cnt_ptr. I.e. a reference counted pointer where the delete is only done in an explicit delete routine. Using it in the one place where the existing code knows the lifetime of the object, as well as in my new code that keeps the object alive longer.

Incrementing and decrementing the reference count as explicit_delete_ref_cnt_ptr get manipulated.

But NOT freeing when the reference count is seen to be zero in the explicit_delete_ref_cnt_ptr destructor.

Only freeing when the reference count is seen to be zero in an explicit delete-like operation. E.g. in something like:

template<typename T> class explicit_delete_ref_cnt_ptr { 
 private: 
   T* ptr;
   int rc;
   ...
 public: 
   void delete_if_rc0() {
      if( this->ptr ) {
        this->rc--;
        if( this->rc == 0 ) {
           delete this->ptr;
        }
        this->ptr = 0;
      }
    }
 };

OK, something like that. It's a bit unusual to have a reference counted pointer type not automatically delete the object pointed to in the rc'ed ptr destructor. But it seems like this might make mixing naked pointers and rc'ed pointers a bit safer.

But so far no need for delete this.

But then it occurred to me: if the object pointed to, the pointee, knows that it is being reference counted, e.g. if the count is inside the object (or in some other table), then the routine delete_if_rc0 could be a method of the pointee object, not the (smart) pointer.

class Pointee { 
 private: 
   int rc;
   ...
 public: 
   void delete_if_rc0() {
        this->rc--;
        if( this->rc == 0 ) {
           delete this;
        }
      }
    }
 };

Actually, it doesn't need to be a member method at all, but could be a free function:

map<void*,int> keepalive_map;
template<typename T>
void delete_if_rc0(T*ptr) {
        void* tptr = (void*)ptr;
        if( keepalive_map[tptr] == 1 ) {
           delete ptr;
        }
};

(BTW, I know the code is not quite right - it becomes less readable if I add all the details, so I am leaving it like this.)

Iterating a JavaScript object's properties using jQuery

You can use each for objects too and not just for arrays:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});

How to get selected value of a html select with asp.net

If you would use asp:dropdownlist you could select it easier by testSelect.Text.

Now you'd have to do a Request.Form["testSelect"] to get the value after pressed btnTes.

Hope it helps.

EDIT: You need to specify a name of the select (not only ID) to be able to Request.Form["testSelect"]

Difference between null and empty ("") Java String

A string can be empty or have a null value. If a string is null, it isn't referring to anything in memory. Try s.length()>0. This is because if a string is empty, it still returns a length of 0. So if you enter nothing for the same, then it will still continue looping since it doesn't register the string as null. Whereas if you check for length, then it will exit out of it's loop.