Programs & Examples On #Anti bot

The function of anti-bot software is to determine when another application is trying to access it as if a real user would and prevent any action that should only be allowed by humans.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

it was the problem i recently faced which i solved with using

<f:attribute name="collectionType" value="java.util.ArrayList" />

more detailed decription here and this saved my day.

CentOS 7 and Puppet unable to install nc

You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:

root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}

#we capture release hash
$curr_os = $os['release']

case $curr_os['major'] {
  '7': { .... something }
  *: {something}
}

That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.

The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.

Update Multiple Rows in Entity Framework from a list of ids

var idList=new int[]{1, 2, 3, 4};
var friendsToUpdate = await Context.Friends.Where(f => 
    idList.Contains(f.Id).ToListAsync();

foreach(var item in previousEReceipts)
{
  item.msgSentBy = "1234";
}

You can use foreach to update each element that meets your condition.

Here is an example in a more generic way:

var itemsToUpdate = await Context.friends.Where(f => f.Id == <someCondition>).ToListAsync();

foreach(var item in itemsToUpdate)
{
   item.property = updatedValue;
}
Context.SaveChanges()

In general you will most probably use async methods with await for db queries.

Route.get() requires callback functions but got a "object Undefined"

My problem was a mistake in importing:

I imported my function into the router/index.js like below:

const { index } = require('../controllers');

and used it like this:

router.get('/', index.index);

This was my mistake. I must have used this:

router.get('/', index);

So I changed it to the line above and my problem got solved.

Difference between "@id/" and "@+id/" in Android

There's a bug with Eclipse where sometimes if you just created a new @+id/.., it won't be added immediately to the R.java file, even after clean-building the project. The solution is to restart Eclipse.

This I think should be solved as soon as possible, because it may (and from experience, will) confuse some developers into thinking that there's something wrong with their syntax, and try to debug it even if there's really nothing to debug.

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

Difference between Date(dateString) and new Date(dateString)

The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.

For More Information:

Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

How To Run PHP From Windows Command Line in WAMPServer

Try using batch file

  1. Open notepad
  2. type php -S localhost:8000
  3. save file as .bat extension, server.bat
  4. now click on server.bat file your server is ready on http://localhost:8000

Dependency

if you got error php not recognize any internal or external command then goto environment variable and edit path to php.exe "C:\wamp\bin\php\php5.4.3"

Regular expression to search multiple strings (Textpad)

To get the lines that contain the texts 8768, 9875 or 2353, use:

^.*(8768|9875|2353).*$

What it means:

^                      from the beginning of the line
.*                     get any character except \n (0 or more times)
(8768|9875|2353)       if the line contains the string '8768' OR '9875' OR '2353'
.*                     and get any character except \n (0 or more times)
$                      until the end of the line

If you do want the literal * char, you'd have to escape it:

^.*(\*8768|\*9875|\*2353).*$

How do I copy to the clipboard in JavaScript?

To copy a selected text ('Text To Copy') to your clipboard, create a Bookmarklet (browser bookmark that executes JavaScript) and execute it (click on it). It will create a temporary textarea.

Code from GitHub:

https://gist.github.com/stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d

(function (text) {
  var node = document.createElement('textarea');
  var selection = document.getSelection();

  node.textContent = text;
  document.body.appendChild(node);

  selection.removeAllRanges();
  node.select();
  document.execCommand('copy');

  selection.removeAllRanges();
  document.body.removeChild(node);
})('Text To Copy');

Black transparent overlay on image hover with only CSS?

See what I've done here: http://jsfiddle.net/dyarbrough93/c8wEC/

First off, you never set the dimensions of the overlay, meaning it wasn't showing up in the first place. Secondly, I recommend just changing the z-index of the overlay when you hover over the image. Change the opacity / color of the overlay to suit your needs.

.image { position: relative; width: 200px; height: 200px;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background-color: gray; z-index: -10; width: 200px; height: 200px; opacity: 0.5}
.image:hover .overlay { z-index: 10}

Error:java: javacTask: source release 8 requires target release 1.8

I just re-import maven button, then the error disappeared.

enter image description here

Could not connect to React Native development server on Android

Make sure NPM server is running. Else run it again. It will solve the issue.

Can I use CASE statement in a JOIN condition?

Try this:

...JOIN sys.allocation_units a ON 
  (a.type=2 AND a.container_id = p.partition_id)
  OR (a.type IN (1, 3) AND a.container_id = p.hobt_id)

How to pass anonymous types as parameters?

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
    foreach (dynamic item in list)
    {
        string name = item.Name;
        int id = item.Id;
    }
}

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.

How to view changes made to files on a certain revision in Subversion

Call this in the project:

svn diff -r REVNO:HEAD --summarize

REVNO is the start revision number and HEAD is the end revision number. If HEAD is equal to the last revision number, it can skip it.

The command returns a list with all files that are changed/added/deleted in this revision period.

The command can be called with the URL revision parameter to check changes like this:

svn diff -r REVNO:HEAD --summarize SVN_URL

how to get the attribute value of an xml node using java

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
    System.out.println(key);
}

PDOException “could not find driver”

I spent the last day trying to figure out why I was getting the following error. I am running Ubuntu 14.04.

The Problem:
I noticed that my PHP-CLI version was running php7.0 but php_info() (the web version) was displaying php 5.5.9. Even though php_info() said pdo was enabled, using the command line (CLI) wasn't recognizing the pdo_mysql command. It turns out that mysql was enabled for my old version but not the CLI version. All I did was install mysql for php7.0 and it was able to work.

This is what worked:

To check the version:

php -v

To install mysql for php7.0

sudo apt-get install php7.0-mysql

1) make sure your CLI version is the same as your web version
2) If they are different, make sure your CLI version has the mysql plug-in since it doesn't come with it as a default.

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set Java SDK path in AndroidStudio?

Generally speaking, it is set in the "Project Structure" dialog.

Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.

enter image description here

To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".

Older Versions

Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.

To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.

Import/Index a JSON file into Elasticsearch

As of Elasticsearch 7.7, you have to specify the content type also:

curl -s -H "Content-Type: application/json" -XPOST localhost:9200/_bulk --data-binary @<absolute path to JSON file>

Animate element transform rotate

As far as I know, basic animates can't animate non-numeric CSS properties.

I believe you could get this done using a step function and the appropriate css3 transform for the users browser. CSS3 transform is a bit tricky to cover all your browsers in (IE6 you need to use the Matrix filter, for instance).

EDIT: here's an example that works in webkit browsers (Chrome, Safari): http://jsfiddle.net/ryleyb/ERRmd/

If you wanted to support IE9 only, you could use transform instead of -webkit-transform, or -moz-transform would support FireFox.

The trick used is to animate a CSS property we don't care about (text-indent) and then use its value in a step function to do the rotation:

$('#foo').animate(
..
step: function(now,fx) {
  $(this).css('-webkit-transform','rotate('+now+'deg)'); 
}
...

How to pass multiple parameters in thread in VB

In addition to what Dario stated about the Delegates you could execute a delegate with several parameters:

Predefine your delegate:

Private Delegate Sub TestThreadDelegate(ByRef goodList As List(Of String), ByVal coolvalue As Integer)

Get a handle to the delegate, create parameters in an array, DynamicInvoke on the Delegate:

Dim tester As TestThreadDelegate = AddressOf Me.testthread
Dim params(1) As Object
params(0) = New List(Of String)
params(1) = 0

tester.DynamicInvoke(params)

CakePHP find method with JOIN

There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.

It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.

The CakePHP Way

You would create a relationship with your User model and Messages Model, and use the containable behavior:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Message');
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('User');
}

You need to change the messages.from column to be messages.user_id so that cake can automagically associate the records for you.

Then you can do this from the messages controller:

$this->Message->find('all', array(
    'contain' => array('User')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

The (other) CakePHP way

I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController:

$this->Message->find('all', array(
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'UserJoin',
            'type' => 'INNER',
            'conditions' => array(
                'UserJoin.id = Message.from'
            )
        )
    ),
    'conditions' => array(
        'Message.to' => 4
    ),
    'fields' => array('UserJoin.*', 'Message.*'),
    'order' => 'Message.datetime DESC'
));

Note, I've left the field name messages.from the same as your current table in this example.

Using two relationships to the same model

Here is how you can do the first example using two relationships to the same model:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array(
        'MessagesSent' => array(
            'className'  => 'Message',
            'foreignKey' => 'from'
         )
    );
    public $belongsTo = array(
        'MessagesReceived' => array(
            'className'  => 'Message',
            'foreignKey' => 'to'
         )
    );
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array(
        'UserFrom' => array(
            'className'  => 'User',
            'foreignKey' => 'from'
        )
    );
    public $hasMany = array(
        'UserTo' => array(
            'className'  => 'User',
            'foreignKey' => 'to'
        )
    );
}

Now you can do your find call like this:

$this->Message->find('all', array(
    'contain' => array('UserFrom')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

Java logical operator short-circuiting

Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.

Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.

Connecting to MySQL from Android with JDBC

try changing in the gradle file the targetSdkVersion to 8

targetSdkVersion 8

How to clear Tkinter Canvas?

Items drawn to the canvas are persistent. create_rectangle returns an item id that you need to keep track of. If you don't remove old items your program will eventually slow down.

From Fredrik Lundh's An Introduction to Tkinter:

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coords, itemconfig, and move to modify the items, or use delete to remove them.

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

Can lambda functions be templated?

C++11 lambdas can't be templated as stated in other answers but decltype() seems to help when using a lambda within a templated class or function.

#include <iostream>
#include <string>

using namespace std;

template<typename T>
void boring_template_fn(T t){
    auto identity = [](decltype(t) t){ return t;};
    std::cout << identity(t) << std::endl;
}

int main(int argc, char *argv[]) {
    std::string s("My string");
    boring_template_fn(s);
    boring_template_fn(1024);
    boring_template_fn(true);
}

Prints:

My string
1024
1

I've found this technique is helps when working with templated code but realize it still means lambdas themselves can't be templated.

How can I ping a server port with PHP?

socket_create needs to be run as root on a UNIX system with;

$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);

Get DOS path instead of Windows path

$fso = New-Object -com scripting.filesystemobject
$fso.GetFolder('c:\Program Files (x86)').ShortName()

PROGRA~2

Inspired by Dr. Scripto's answer

Is it possible to run a .NET 4.5 app on XP?

Sadly, no, you can't run 4.5 programs on XP.

And the relevant post from that Connect page:

Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

Can't install gems on OS X "El Capitan"

sudo chown -R $(whoami):admin /usr/local

That will give permissions back (Homebrew installs ruby there)

Time calculation in php (add 10 hours)?

$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

see DateTime Class (PHP 5 >= 5.2.0)

How do I create a file at a specific path?

It will be created once you close the file (with or without writing). Use os.path.join() to create your path eg

filepath = os.path.join("c:\\","test.py")

package javax.servlet.http does not exist

Got this error on linux because of weird file permissions in tomcat distro. Some files an directories are not readable for other users. I use separate CATALINA_HOME and CATALINA_BASE, so my tomcat is owned by root and is runned by restricted user.

Fixing it like that:

( cd /usr/local/share/tomcat9/ && for file in `find ./ -type d ! -perm -o=r`; do echo "$file"; chmod o+rx "$file"; done && for file in `find ./ ! -perm -o=r`; do echo "$file"; chmod o+r "$file"; done )
for file in `find /usr/local/share/tomcat9/ ! -perm -o=x -name '*.sh'`; do echo "$file"; chmod o+x "$file"; done 

How to loop through all enum values in C#?

 Enum.GetValues(typeof(Foos))

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I can also confirm this error.

Workaround: is to use external maven inside m2eclipse, instead of it's embedded maven.

That is done in three steps:

1 Install maven on local machine (the test-machine was Ubuntu 10.10)

mvn --version

Apache Maven 2.2.1 (rdebian-4) Java version: 1.6.0_20 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-32-generic" arch: "amd64" Family: "unix"

2 Run maven externally link how to run maven from console

> cd path-to-pom.xml
> mvn test
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Simple
    [INFO]    task-segment: [test]
    [INFO] ------------------------------------------------------------------------
    [...]
    [INFO] Surefire report directory: [...]/workspace/Simple/target/surefire-reports
    
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running net.tverrbjelke.experiment.MainAppTest
    Hello World
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 sec
    
    Results :
    
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    [...]

3 inside m2eclipse: switch from embedded maven to local maven

  • find out where local maven home installation dir is (mvn --version, or google for your MAVEN_HOME, for me this helped me that is /usr/share/maven2 )
  • in eclipse Menu->Window->Preferences->Maven->Installation-> enter that string. Then you should have switched to your new external maven.
  • then run your Project as e.g. "maven test".

The error-message should be gone.

Check/Uncheck all the checkboxes in a table

Actually your checkAll(..) is hanging without any attachment.

1) Add onchange event handler

<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>

2) Modified the code to handle check/uncheck

 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
 }

Updated Fiddle

How to git-svn clone the last n revisions from a Subversion repository?

I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).

# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase

And a good way to find out where a branch started is to do a svn log it and find the first one on the branch (the last one listed when doing):

svn log --stop-on-copy svn://some/repo/branch/some-branch

So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.

Search for a particular string in Oracle clob column

Below code can be used to search a particular string in Oracle clob column

select *  
from RLOS_BINARY_BP
where dbms_lob.instr(DED_ENQ_XML,'2003960067') > 0;

where RLOS_BINARY_BP is table name and DED_ENQ_XML is column name (with datatype as CLOB) of Oracle database.

Reading data from a website using C#

 WebClient client = new WebClient();
            using (Stream data = client.OpenRead(Text))
            {
                using (StreamReader reader = new StreamReader(data))
                {
                    string content = reader.ReadToEnd();
                    string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
                    MatchCollection matches = Regex.Matches(content,pattern);
                    List<string> urls = new List<string>();
                    foreach (Match match in matches)
                    {
                            urls.Add(match.Value);
                    }

              }

How do I find the PublicKeyToken for a particular dll?

Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName

Will result in

System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Assigning default values to shell variables with a single command in bash

FWIW, you can provide an error message like so:

USERNAME=${1:?"Specify a username"}

This displays a message like this and exits with code 1:

./myscript.sh
./myscript.sh: line 2: 1: Specify a username

A more complete example of everything:

#!/bin/bash
ACTION=${1:?"Specify 'action' as argv[1]"}
DIRNAME=${2:-$PWD}
OUTPUT_DIR=${3:-${HOMEDIR:-"/tmp"}}

echo "$ACTION"
echo "$DIRNAME"
echo "$OUTPUT_DIR"

Output:

$ ./script.sh foo
foo
/path/to/pwd
/tmp

$ export HOMEDIR=/home/myuser
$ ./script.sh foo
foo
/path/to/pwd
/home/myuser
  • $ACTION takes the value of the first argument, and exits if empty
  • $DIRNAME is the 2nd argument, and defaults to the current directory
  • $OUTPUT_DIR is the 3rd argument, or $HOMEDIR (if defined), else, /tmp. This works on OS X, but I'm not positive that it's portable.

Get integer value from string in swift

I'd use:

var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)

Note toInt():

If the string represents an integer that fits into an Int, returns the corresponding integer.

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

When to use RSpec let()?

let is functional as its essentially a Proc. Also its cached.

One gotcha I found right away with let... In a Spec block that is evaluating a change.

let(:object) {FactoryGirl.create :object}

expect {
  post :destroy, id: review.id
}.to change(Object, :count).by(-1)

You'll need to be sure to call let outside of your expect block. i.e. you're calling FactoryGirl.create in your let block. I usually do this by verifying the object is persisted.

object.persisted?.should eq true

Otherwise when the let block is called the first time a change in the database will actually happen due to the lazy instantiation.

Update

Just adding a note. Be careful playing code golf or in this case rspec golf with this answer.

In this case, I just have to call some method to which the object responds. So I invoke the _.persisted?_ method on the object as its truthy. All I'm trying to do is instantiate the object. You could call empty? or nil? too. The point isn't the test but bringing the object ot life by calling it.

So you can't refactor

object.persisted?.should eq true

to be

object.should be_persisted 

as the object hasn't been instantiated... its lazy. :)

Update 2

leverage the let! syntax for instant object creation, which should avoid this issue altogether. Note though it will defeat a lot of the purpose of the laziness of the non banged let.

Also in some instances you might actually want to leverage the subject syntax instead of let as it may give you additional options.

subject(:object) {FactoryGirl.create :object}

Google Maps v3 - limit viewable area and zoom level

One solution is like, If you know the specific lat/lng.

google.maps.event.addListener(map, 'idle', function() {

    map.setCenter(new google.maps.LatLng(latitude, longitude));
    map.setZoom(8);

});

If don't have specific lat/lng

google.maps.event.addListener(map, 'idle', function() {

    map.setCenter(map.getCenter());
    map.setZoom(8);

});

or

google.maps.event.addListener(map, 'idle', function() {

    var bounds = new google.maps.LatLngBounds();
    map.setCenter(bounds.getCenter());
    map.setZoom(8);

});

Redirect in Spring MVC

i know this is late , but you should try redirecting to a path and not to a file ha ha

window.open target _self v window.location.href?

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

Get UTC time and local time from NSDate object

Xcode 9 • Swift 4 (also works Swift 3.x)

extension Formatter {
    // create static date formatters for your date representations
    static let preciseLocalTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
    static let preciseGMTTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
}

extension Date {
    // you can create a read-only computed property to return just the nanoseconds from your date time
    var nanosecond: Int { return Calendar.current.component(.nanosecond,  from: self)   }
    // the same for your local time
    var preciseLocalTime: String {
        return Formatter.preciseLocalTime.string(for: self) ?? ""
    }
    // or GMT time
    var preciseGMTTime: String {
        return Formatter.preciseGMTTime.string(for: self) ?? ""
    }
}

Playground testing

Date().preciseLocalTime // "09:13:17.385"  GMT-3
Date().preciseGMTTime   // "12:13:17.386"  GMT
Date().nanosecond       // 386268973

This might help you also formatting your dates:

enter image description here

Expected initializer before function name

Try adding a semi colon to the end of your structure:

 struct sotrudnik {
    string name;
    string speciality;
    string razread;
    int zarplata;
} //Semi colon here

Wait for Angular 2 to load/resolve model before rendering view/template

EDIT: The angular team has released the @Resolve decorator. It still needs some clarification, in how it works, but until then I'll take someone else's related answer here, and provide links to other sources:


EDIT: This answer works for Angular 2 BETA only. Router is not released for Angular 2 RC as of this edit. Instead, when using Angular 2 RC, replace references to router with router-deprecated to continue using the beta router.

The Angular2-future way to implement this will be via the @Resolve decorator. Until then, the closest facsimile is CanActivate Component decorator, per Brandon Roberts. see https://github.com/angular/angular/issues/6611

Although beta 0 doesn't support providing resolved values to the Component, it's planned, and there is also a workaround described here: Using Resolve In Angular2 Routes

A beta 1 example can be found here: http://run.plnkr.co/BAqA98lphi4rQZAd/#/resolved . It uses a very similar workaround, but slightly more accurately uses the RouteData object rather than RouteParams.

@CanActivate((to) => {
    return new Promise((resolve) => {
        to.routeData.data.user = { name: 'John' }

Also, note that there is also an example workaround for accessing nested/parent route "resolved" values as well, and other features you expect if you've used 1.x UI-Router.

Note you'll also need to manually inject any services you need to accomplish this, since the Angular Injector hierarchy is not currently available in the CanActivate decorator. Simply importing an Injector will create a new injector instance, without access to the providers from bootstrap(), so you'll probably want to store an application-wide copy of the bootstrapped injector. Brandon's second Plunk link on this page is a good starting point: https://github.com/angular/angular/issues/4112

Should I use alias or alias_method?

A point in favor of alias instead of alias_method is that its semantic is recognized by rdoc, leading to neat cross references in the generated documentation, while rdoc completely ignore alias_method.

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

How to install PHP intl extension in Ubuntu 14.04

May be universe repository is disabled, here is your package in it

Enable it

sudo add-apt-repository universe

Update

sudo apt-get update

And install

sudo apt-get install php5-intl

Standard Android Button with a different color

values\styles.xml

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

<style name="RedAccentButton" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorAccent">#ff0000</item>
</style>

then:

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="text"
    android:theme="@style/RedAccentButton" />

<Button
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:text="text"
    android:theme="@style/RedAccentButton" />

result

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

How do I find Waldo with Mathematica?

I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.

The two challenges with training a Waldo classifier would be:

  1. Determining the right image feature transform. This is where @Heike's answer would be useful: a red filter and a stripped pattern detector (e.g., wavelet or DCT decomposition) would be a good way to turn raw pixels into a format that the classification algorithm could learn from. A block-based decomposition that assesses all subsections of the image would also be required ... but this is made easier by the fact that Waldo is a) always roughly the same size and b) always present exactly once in each image.
  2. Obtaining enough training examples. SVMs work best with at least 100 examples of each class. Commercial applications of boosting (e.g., the face-focusing in digital cameras) are trained on millions of positive and negative examples.

A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!

However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!

sweet-alert display HTML code in text

Use SweetAlert's html setting.

You can set output html direct to this option:

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Or

swal({
    title: "" + txt + "", 
    html: "Testno  sporocilo za objekt <b>teste</b>",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

How to Upload Image file in Retrofit 2

Retrofit 2.0 solution

@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);

and

    Map<String, RequestBody> params = new HashMap<>();

    params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));



 Call<CommonResponse> call = request.requestUpdateImage(params);

you can use
image/jpg image/png image/gif

Map enum in JPA with fixed values?

The problem is, I think, that JPA was never incepted with the idea in mind that we could have a complex preexisting Schema already in place.

I think there are two main shortcomings resulting from this, specific to Enum:

  1. The limitation of using name() and ordinal(). Why not just mark a getter with @Id, the way we do with @Entity?
  2. Enum's have usually representation in the database to allow association with all sorts of metadata, including a proper name, a descriptive name, maybe something with localization etc. We need the easy of use of an Enum combined with the flexibility of an Entity.

Help my cause and vote on JPA_SPEC-47

Would this not be more elegant than using a @Converter to solve the problem?

// Note: this code won't work!!
// it is just a sample of how I *would* want it to work!
@Enumerated
public enum Language {
  ENGLISH_US("en-US"),
  ENGLISH_BRITISH("en-BR"),
  FRENCH("fr"),
  FRENCH_CANADIAN("fr-CA");
  @ID
  private String code;
  @Column(name="DESCRIPTION")
  private String description;

  Language(String code) {
    this.code = code;
  }

  public String getCode() {
    return code;
  }

  public String getDescription() {
    return description;
  }
}

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

How to make sure that string is valid JSON using JSON.NET

Through Code:

Your best bet is to use parse inside a try-catch and catch exception in case of failed parsing. (I am not aware of any TryParse method).

(Using JSON.Net)

Simplest way would be to Parse the string using JToken.Parse, and also to check if the string starts with { or [ and ends with } or ] respectively (added from this answer):

private static bool IsValidJson(string strInput)
{
    if (string.IsNullOrWhiteSpace(strInput)) { return false;}
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            Console.WriteLine(jex.Message);
            return false;
        }
        catch (Exception ex) //some other exception
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
    }
    else
    {
        return false;
    }
}

The reason to add checks for { or [ etc was based on the fact that JToken.Parse would parse the values such as "1234" or "'a string'" as a valid token. The other option could be to use both JObject.Parse and JArray.Parse in parsing and see if anyone of them succeeds, but I believe checking for {} and [] should be easier. (Thanks @RhinoDevel for pointing it out)

Without JSON.Net

You can utilize .Net framework 4.5 System.Json namespace ,like:

string jsonString = "someString";
try
{
    var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
    //Invalid json format
    Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
    Console.WriteLine(ex.ToString());
}

(But, you have to install System.Json through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343 on Package Manager Console) (taken from here)

Non-Code way:

Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).

Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".

Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.

std::wstring VS std::string

string? wstring?

std::string is a basic_string templated on a char, and std::wstring on a wchar_t.

char vs. wchar_t

char is supposed to hold a character, usually an 8-bit character.
wchar_t is supposed to hold a wide character, and then, things get tricky:
On Linux, a wchar_t is 4 bytes, while on Windows, it's 2 bytes.

What about Unicode, then?

The problem is that neither char nor wchar_t is directly tied to unicode.

On Linux?

Let's take a Linux OS: My Ubuntu system is already unicode aware. When I work with a char string, it is natively encoded in UTF-8 (i.e. Unicode string of chars). The following code:

#include <cstring>
#include <iostream>

int main(int argc, char* argv[])
{
   const char text[] = "olé" ;


   std::cout << "sizeof(char)    : " << sizeof(char) << std::endl ;
   std::cout << "text            : " << text << std::endl ;
   std::cout << "sizeof(text)    : " << sizeof(text) << std::endl ;
   std::cout << "strlen(text)    : " << strlen(text) << std::endl ;

   std::cout << "text(ordinals)  :" ;

   for(size_t i = 0, iMax = strlen(text); i < iMax; ++i)
   {
      std::cout << " " << static_cast<unsigned int>(
                              static_cast<unsigned char>(text[i])
                          );
   }

   std::cout << std::endl << std::endl ;

   // - - - 

   const wchar_t wtext[] = L"olé" ;

   std::cout << "sizeof(wchar_t) : " << sizeof(wchar_t) << std::endl ;
   //std::cout << "wtext           : " << wtext << std::endl ; <- error
   std::cout << "wtext           : UNABLE TO CONVERT NATIVELY." << std::endl ;
   std::wcout << L"wtext           : " << wtext << std::endl;

   std::cout << "sizeof(wtext)   : " << sizeof(wtext) << std::endl ;
   std::cout << "wcslen(wtext)   : " << wcslen(wtext) << std::endl ;

   std::cout << "wtext(ordinals) :" ;

   for(size_t i = 0, iMax = wcslen(wtext); i < iMax; ++i)
   {
      std::cout << " " << static_cast<unsigned int>(
                              static_cast<unsigned short>(wtext[i])
                              );
   }

   std::cout << std::endl << std::endl ;

   return 0;
}

outputs the following text:

sizeof(char)    : 1
text            : olé
sizeof(text)    : 5
strlen(text)    : 4
text(ordinals)  : 111 108 195 169

sizeof(wchar_t) : 4
wtext           : UNABLE TO CONVERT NATIVELY.
wtext           : ol?
sizeof(wtext)   : 16
wcslen(wtext)   : 3
wtext(ordinals) : 111 108 233

You'll see the "olé" text in char is really constructed by four chars: 110, 108, 195 and 169 (not counting the trailing zero). (I'll let you study the wchar_t code as an exercise)

So, when working with a char on Linux, you should usually end up using Unicode without even knowing it. And as std::string works with char, so std::string is already unicode-ready.

Note that std::string, like the C string API, will consider the "olé" string to have 4 characters, not three. So you should be cautious when truncating/playing with unicode chars because some combination of chars is forbidden in UTF-8.

On Windows?

On Windows, this is a bit different. Win32 had to support a lot of application working with char and on different charsets/codepages produced in all the world, before the advent of Unicode.

So their solution was an interesting one: If an application works with char, then the char strings are encoded/printed/shown on GUI labels using the local charset/codepage on the machine. For example, "olé" would be "olé" in a French-localized Windows, but would be something different on an cyrillic-localized Windows ("ol?" if you use Windows-1251). Thus, "historical apps" will usually still work the same old way.

For Unicode based applications, Windows uses wchar_t, which is 2-bytes wide, and is encoded in UTF-16, which is Unicode encoded on 2-bytes characters (or at the very least, the mostly compatible UCS-2, which is almost the same thing IIRC).

Applications using char are said "multibyte" (because each glyph is composed of one or more chars), while applications using wchar_t are said "widechar" (because each glyph is composed of one or two wchar_t. See MultiByteToWideChar and WideCharToMultiByte Win32 conversion API for more info.

Thus, if you work on Windows, you badly want to use wchar_t (unless you use a framework hiding that, like GTK+ or QT...). The fact is that behind the scenes, Windows works with wchar_t strings, so even historical applications will have their char strings converted in wchar_t when using API like SetWindowText() (low level API function to set the label on a Win32 GUI).

Memory issues?

UTF-32 is 4 bytes per characters, so there is no much to add, if only that a UTF-8 text and UTF-16 text will always use less or the same amount of memory than an UTF-32 text (and usually less).

If there is a memory issue, then you should know than for most western languages, UTF-8 text will use less memory than the same UTF-16 one.

Still, for other languages (chinese, japanese, etc.), the memory used will be either the same, or slightly larger for UTF-8 than for UTF-16.

All in all, UTF-16 will mostly use 2 and occassionally 4 bytes per characters (unless you're dealing with some kind of esoteric language glyphs (Klingon? Elvish?), while UTF-8 will spend from 1 to 4 bytes.

See http://en.wikipedia.org/wiki/UTF-8#Compared_to_UTF-16 for more info.

Conclusion

  1. When I should use std::wstring over std::string?

    On Linux? Almost never (§).
    On Windows? Almost always (§).
    On cross-platform code? Depends on your toolkit...

    (§) : unless you use a toolkit/framework saying otherwise

  2. Can std::string hold all the ASCII character set including special characters?

    Notice: A std::string is suitable for holding a 'binary' buffer, where a std::wstring is not!

    On Linux? Yes.
    On Windows? Only special characters available for the current locale of the Windows user.

    Edit (After a comment from Johann Gerell):
    a std::string will be enough to handle all char-based strings (each char being a number from 0 to 255). But:

    1. ASCII is supposed to go from 0 to 127. Higher chars are NOT ASCII.
    2. a char from 0 to 127 will be held correctly
    3. a char from 128 to 255 will have a signification depending on your encoding (unicode, non-unicode, etc.), but it will be able to hold all Unicode glyphs as long as they are encoded in UTF-8.
  3. Is std::wstring supported by almost all popular C++ compilers?

    Mostly, with the exception of GCC based compilers that are ported to Windows.
    It works on my g++ 4.3.2 (under Linux), and I used Unicode API on Win32 since Visual C++ 6.

  4. What is exactly a wide character?

    On C/C++, it's a character type written wchar_t which is larger than the simple char character type. It is supposed to be used to put inside characters whose indices (like Unicode glyphs) are larger than 255 (or 127, depending...).

VBA: Selecting range by variables

If you just want to select the used range, use

ActiveSheet.UsedRange.Select

If you want to select from A1 to the end of the used range, you can use the SpecialCells method like this

With ActiveSheet
    .Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select
End With

Sometimes Excel gets confused on what is the last cell. It's never a smaller range than the actual used range, but it can be bigger if some cells were deleted. To avoid that, you can use Find and the asterisk wildcard to find the real last cell.

Dim rLastCell As Range

With Sheet1
    Set rLastCell = .Cells.Find("*", .Cells(1, 1), xlValues, xlPart, , xlPrevious)

    .Range(.Cells(1, 1), rLastCell).Select
End With

Finally, make sure you're only selecting if you really need to. Most of what you need to do in Excel VBA you can do directly to the Range rather than selecting it first. Instead of

.Range(.Cells(1, 1), rLastCell).Select
Selection.Font.Bold = True

You can

.Range(.Cells(1,1), rLastCells).Font.Bold = True

Adding new line of data to TextBox

Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.

Should C# or C++ be chosen for learning Games Programming (consoles)?

I think that C++.

Because c# needs additional instalation for C# runtime which only absorbs space on a disk. And C# is of course a bit slower.

How do I debug jquery AJAX calls?

2020 answer with Chrome dev tools

To debug any XHR request:

  1. Open Chrome DEV tools (F12)
  2. Right-click your Ajax url in the console

Chrome console Ajax request

for a GET request:

  • click Open in new tab

for a POST request:

  1. click Reveal in Network panel

  2. In the Network panel:

    1. click on your request

    2. click on the response tab to see the details Chrome Network panel's response tab

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Thanks for the question. For YouTube iframe the first issue is the URL you have given, is it embedded URL or URL link from address bar. this error for non embed URL but if you want to give non embed URL then you need to code in "safe Pipe" like(for both non embedded or embed URL ) :

import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';

@Pipe({name: 'safe'})
export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) {

}

transform(value: any, url: any): any {
    if (value && !url) {
        const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
        let match = value.match(regExp);
        if (match && match[2].length == 11) {
            console.log(match[2]);
            let sepratedID = match[2];
            let embedUrl = '//www.youtube.com/embed/' + sepratedID;
            return this.sanitizer.bypassSecurityTrustResourceUrl(embedUrl);
        }

     }

   }
}

it will split out "vedioId". You have to get video id then set to URL as embedded. In Html

 <div>
   <iframe width="100%" height="300" [src]="video.url | safe"></iframe>
 </div>

Angular 2/5 thanks again.

Change input value onclick button - pure javascript or jQuery

My Attempt ( JsFiddle)

Javascript

$(document).ready(function () {
    $('#buttons input[type=button]').on('click', function () {
        var qty = $(this).data('quantity');
        var price = $('#totalPrice').text(); 
        $('#count').val(price * qty);
    });
});

Html

  Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
    <input id='qty2' type="button" data-quantity='2' value="2&#x00A;Qty">
    <input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4&#x00A;Qty">
</div>
<br>Total
<input type="text" id="count" value="1">

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

After reading the documentation of VideoCapture. I figured out that you can tell VideoCapture, which frame to process next time we call VideoCapture.read() (or VideoCapture.grab()).

The problem is that when you want to read() a frame which is not ready, the VideoCapture object stuck on that frame and never proceed. So you have to force it to start again from the previous frame.

Here is the code

import cv2

cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
    cap = cv2.VideoCapture("./out.mp4")
    cv2.waitKey(1000)
    print "Wait for the header"

pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
    flag, frame = cap.read()
    if flag:
        # The frame is ready and already captured
        cv2.imshow('video', frame)
        pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
        print str(pos_frame)+" frames"
    else:
        # The next frame is not ready, so we try to read it again
        cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
        print "frame is not ready"
        # It is better to wait for a while for the next frame to be ready
        cv2.waitKey(1000)

    if cv2.waitKey(10) == 27:
        break
    if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
        # If the number of captured frames is equal to the total number of frames,
        # we stop
        break

jquery to validate phone number

This one is work for me:-

/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/

Windows Explorer "Command Prompt Here"

Almost the same as yours:

  • Alt+d, Ctrl+c
  • Win+r
  • cmd /K cd , Ctrl+v, ENTER

Transform DateTime into simple Date in Ruby on Rails

In Ruby 1.9.2 and above they added a .to_date function to DateTime:

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

This instance method doesn't appear to be present in earlier versions like 1.8.7.

MySQL combine two columns into one column

It's work for me

SELECT CONCAT(column1, ' ' ,column2) AS newColumn;

How do I return an int from EditText? (Android)

For now, use an EditText. Use android:inputType="number" to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())).

In the future, you might consider a NumberPicker widget, once that becomes available (slated to be in Honeycomb).

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Reading Excel file using node.js

Useful link

https://ciphertrick.com/read-excel-files-convert-json-node-js/

 var express = require('express'); 
    var app = express(); 
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var xlstojson = require("xls-to-json-lc");
    var xlsxtojson = require("xlsx-to-json-lc");
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage,
                    fileFilter : function(req, file, callback) { //file filter
                        if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                            return callback(new Error('Wrong extension type'));
                        }
                        callback(null, true);
                    }
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        var exceltojson;
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
            /** Multer gives us file info in req.file object */
            if(!req.file){
                res.json({error_code:1,err_desc:"No file passed"});
                return;
            }
            /** Check the extension of the incoming file and 
             *  use the appropriate module
             */
            if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                exceltojson = xlsxtojson;
            } else {
                exceltojson = xlstojson;
            }
            try {
                exceltojson({
                    input: req.file.path,
                    output: null, //since we don't need output.json
                    lowerCaseHeaders:true
                }, function(err,result){
                    if(err) {
                        return res.json({error_code:1,err_desc:err, data: null});
                    } 
                    res.json({error_code:0,err_desc:null, data: result});
                });
            } catch (e){
                res.json({error_code:1,err_desc:"Corupted excel file"});
            }
        })
    }); 
    app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

Max or Default?

I think the issue is what do you want to happen when the query has no results. If this is an exceptional case then I would wrap the query in a try/catch block and handle the exception that the standard query generates. If it's ok to have the query return no results, then you need to figure out what you want the result to be in that case. It may be that @David's answer (or something similar will work). That is, if the MAX will always be positive, then it may be enough to insert a known "bad" value into the list that will only be selected if there are no results. Generally, I would expect a query that is retrieving a maximum to have some data to work on and I would go the try/catch route as otherwise you are always forced to check if the value you obtained is correct or not. I'd rather that the non-exceptional case was just able to use the obtained value.

Try
   Dim x = (From y In context.MyTable _
            Where y.MyField = value _
            Select y.MyCounter).Max
   ... continue working with x ...
Catch ex As SqlException
       ... do error processing ...
End Try

How to change color in circular progress bar?

for me theme wasn't working with accentColor. But it did work with colorControlActivated

    <style name="Progressbar.White" parent="AppTheme">
        <item name="colorControlActivated">@color/white</item>
    </style>

  <ProgressBar
        android:layout_width="@dimen/d_40"
        android:layout_height="@dimen/d_40"
        android:indeterminate="true"
        android:theme="@style/Progressbar.White"/>

Two Radio Buttons ASP.NET C#

In order to make it work, you have to set property GroupName of both radio buttons to the same value:

<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>

Personally, I prefer to use a RadioButtonList:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
    <asp:ListItem Text="Metric" Value="metric" />
    <asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I was able to fix this by running the command prompt/bash as admin and closing VSCode! Seems like VSCode was locking some files. Potentially something else could be locking these files for you.

Imported a csv-dataset to R but the values becomes factors

You can set this globally for all read.csv/read.* commands with options(stringsAsFactors=F)

Then read the file as follows: my.tab <- read.table( "filename.csv", as.is=T )

Getting "Cannot call a class as a function" in my React Project

In my case, I accidentally put component name (Home) as the first argument to connect function while it was supposed to be at the end. duh.

This one -surely- gave me the error:

export default connect(Home)(mapStateToProps, mapDispatchToProps)

But this one worked -surely- fine:

export default connect(mapStateToProps, mapDispatchToProps)(Home)

How to show all shared libraries used by executables in Linux?

On UNIX system, suppose binary (executable) name is test. Then we use the following command to list the libraries used in the test is

ldd test

Simple example of threading in C++

Create a function that you want the thread to execute, eg:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join(); 

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).


The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

Cannot read property 'addEventListener' of null

This is because the element hadn't been loaded at the time when the bundle js was being executed.

I'd move the <script src="sample.js" type="text/javascript"></script> to the very bottom of the index.html file. This way you can ensure script is executed after all the html elements have been parsed and rendered .

How do I make a comment in a Dockerfile?

# this is comment
this isn't comment

is the way to do it. You can place it anywhere in the line and anything that comes later will be ignored

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

mongod --configsvr --smallfiles --nojournal --dbpath cfg/1 --port 26052 --fork --logpath cfg/3.log >/dev/null

Create a single mongos server on the default port

sleep 2000
mongos --configdb ${HOSTNAME}:26050,${HOSTNAME}:26051,${HOSTNAME}:26052 --fork --logpath mongos.log >/dev/null

Sleep for some time before starting the mongos you will not face the problem

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Bootstrap 3 - How to load content in modal body via AJAX?

Check this SO answer out.

It looks like the only way is to provide the whole modal structure with your ajax response.

As you can check from the bootstrap source code, the load function is binded to the root element.

In case you can't modify the ajax response, a simple workaround could be an explicit call of the $(..).modal(..) plugin on your body element, even though it will probably break the show/hide functions of the root element.

JavaFX Location is not set error message

I converted a simple NetBeans 8 Java FXML application to the Maven-driven one. Then I got problems, because the getResource() methods weren't able to find the .fxml files. In mine original application the fxmls were scattered through the package tree - each beside its controller class file. After I made Clean and build in NetBeans, I checked the result .jar in the target folder - the .jar didn't contain any fxml at all. All the fxmls were strangely disappeared.

Then I put all fxmls into the resources/fxml folder and set the getResource method parameters accordingly, for example: FXMLLoader(App.class.getClassLoader().getResource("fxml/ObjOverview.fxml")); In this case everything went OK. The fxml folder appeared int the .jar's root and it contained all my fxmls. The program was working as expected.

Parse large JSON file in Nodejs

I think you need to use a database. MongoDB is a good choice in this case because it is JSON compatible.

UPDATE: You can use mongoimport tool to import JSON data into MongoDB.

mongoimport --collection collection --file collection.json

Visual Studio: How to break on handled exceptions?

The online documentation seems a little unclear, so I just performed a little test. Choosing to break on Thrown from the Exceptions dialog box causes the program execution to break on any exception, handled or unhandled. If you want to break on handled exceptions only, it seems your only recourse is to go through your code and put breakpoints on all your handled exceptions. This seems a little excessive, so it might be better to add a debug statement whenever you handle an exception. Then when you see that output, you can set a breakpoint at that line in the code.

XSLT - How to select XML Attribute by Attribute?

I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t

<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>

Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.

Can jQuery read/write cookies to a browser?

A new jQuery plugin for cookie retrieval and manipulation with binding for forms, etc: http://plugins.jquery.com/project/cookies

MS SQL compare dates?

The simple one line solution is

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')=0

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')<=1

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')>=1

You can try various option with this other than "dd"

How to resolve TypeError: Cannot convert undefined or null to object

Make sure that destination object is not empty ( null or undefined ).

You can initialize destination object with empty object like below:

var destinationObj = {};

Object.assign(destinationObj, sourceObj);

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

Cannot simply use PostgreSQL table name ("relation does not exist")

If a table name contains underscores or upper case, you need to surround it in double-quotes.

SELECT * from "Table_Name";

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

Favicon dimensions?

favicon.ico is 16x16

<link rel="shortcut icon" href="favicon.ico"/>

And I use these ones to be beautiful in mobile and tablet:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/ico144.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/ico114.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/ico72.png">
<link rel="apple-touch-icon-precomposed" href="img/ico57.png">

It's important to use the name "favicon.ico" in the root because many browsers will try to find there first.

Removing Duplicate Values from ArrayList

public static List<String> removeDuplicateElements(List<String> array){
    List<String> temp = new ArrayList<String>();
    List<Integer> count = new ArrayList<Integer>();
    for (int i=0; i<array.size()-2; i++){
        for (int j=i+1;j<array.size()-1;j++)
            {
                if (array.get(i).compareTo(array.get(j))==0) {
                    count.add(i);
                    int kk = i;
                }
            }
        }
        for (int i = count.size()+1;i>0;i--) {
            array.remove(i);
        }
        return array;
    }
}

How to Get a Specific Column Value from a DataTable?

foreach (DataRow row in Datatable.Rows) 
{
    if (row["CountryName"].ToString() == userInput) 
    {
        return row["CountryID"];
    }
}

While this may not compile directly you should get the idea, also I'm sure it would be vastly superior to do the query through SQL as a huge datatable will take a long time to run through all the rows.

Disable cache for some images

i had this problem and overcoming like this.

var newtags='<div class="addedimage"><h5>preview image</h5><img src="'+one+'?nocache='+Math.floor(Math.random() * 1000)+'"></div>';

How to print the number of characters in each line of a text file

while IFS= read -r line; do echo ${#line}; done < abc.txt

It is POSIX, so it should work everywhere.

Edit: Added -r as suggested by William.

Edit: Beware of Unicode handling. Bash and zsh, with correctly set locale, will show number of codepoints, but dash will show bytes—so you have to check what your shell does. And then there many other possible definitions of length in Unicode anyway, so it depends on what you actually want.

Edit: Prefix with IFS= to avoid losing leading and trailing spaces.

Get file from project folder java

Well, there are many different ways to get a file in Java, but that's the general gist.

Don't forget that you'll need to wrap that up inside a try {} catch (Exception e){} at the very least, because File is part of java.io which means it must have try-catch block.

Not to step on Ericson's question, but if you are using actual packages, you'll have issues with locations of files, unless you explicitly use it's location. Relative pathing gets messed up with Packages.

ie,

src/
    main.java
    x.txt

In this example, using File f = new File("x.txt"); inside of main.java will throw a file-not-found exception.

However, using File f = new File("src/x.txt"); will work.

Hope that helps!

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

Read CSV file column by column

Well, how about this !!

This code calculates both row and column count in a csv file. Try this out !!

    static int[] getRowsColsNo() {
    Scanner scanIn = null;
    int rows = 0;
    int cols = 0;
    String InputLine = "";
    try {
        scanIn = new Scanner(new BufferedReader(
                new FileReader("filename.csv")));
        scanIn.useDelimiter(",");
        while (scanIn.hasNextLine()) {
            InputLine = scanIn.nextLine();
            String[] InArray = InputLine.split(",");
            rows++;
            cols = InArray.length;
        }

    } catch (Exception e) {
        System.out.println(e);
    }
    return new int[] { rows, cols };
}

Undo a particular commit in Git that's been pushed to remote repos

I don't like the auto-commit that git revert does, so this might be helpful for some.

If you just want the modified files not the auto-commit, you can use --no-commit

% git revert --no-commit <commit hash>

which is the same as the -n

% git revert -n <commit hash>

Storing images in SQL Server?

When storing images in SQL Server do not use the 'image' datatype, according to MS it is being phased out in new versions of SQL server. Use varbinary(max) instead

https://msdn.microsoft.com/en-us/library/ms187993.aspx

How do I use Join-Path to combine more than two strings into a file path?

Since PowerShell 6.0, Join-Path has a new parameter called -AdditionalChildPath and can combine multiple parts of a path out-of-the-box. Either by providing the extra parameter or by just supplying a list of elements.

Example from the documentation:

Join-Path a b c d e f g
a\b\c\d\e\f\g

So in PowerShell 6.0 and above your variant

$path = Join-Path C: "Program Files" "Microsoft Office"

works as expected!

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

php: check if an array has duplicates

Find this useful solution

function get_duplicates( $array ) {
    return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}

After that count result if greater than 0 than duplicates else unique.

How to get the groups of a user in Active Directory? (c#, asp.net)

First of all, GetAuthorizationGroups() is a great function but unfortunately has 2 disadvantages:

  1. Performance is poor, especially in big company's with many users and groups. It fetches a lot more data then you actually need and does a server call for each loop iteration in the result
  2. It contains bugs which can cause your application to stop working 'some day' when groups and users are evolving. Microsoft recognized the issue and is related with some SID's. The error you'll get is "An error occurred while enumerating the groups"

Therefore, I've wrote a small function to replace GetAuthorizationGroups() with better performance and error-safe. It does only 1 LDAP call with a query using indexed fields. It can be easily extended if you need more properties than only the group names ("cn" property).

// Usage: GetAdGroupsForUser2("domain\user") or GetAdGroupsForUser2("user","domain")
public static List<string> GetAdGroupsForUser2(string userName, string domainName = null)
{
    var result = new List<string>();

    if (userName.Contains('\\') || userName.Contains('/'))
    {
        domainName = userName.Split(new char[] { '\\', '/' })[0];
        userName = userName.Split(new char[] { '\\', '/' })[1];
    }

    using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName))
        using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName))
            using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name)))
            {
                searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName);
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PropertiesToLoad.Add("cn");

                foreach (SearchResult entry in searcher.FindAll())
                    if (entry.Properties.Contains("cn"))
                        result.Add(entry.Properties["cn"][0].ToString());
            }

    return result;
}

How can I check what version/edition of Visual Studio is installed programmatically?

Run the path in cmd C:\Program Files (x86)\Microsoft Visual Studio\Installer>vswhere.exe

Why would a JavaScript variable start with a dollar sign?

While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.

Reading a text file with SQL Server

What does your text file look like?? Each line a record?

You'll have to check out the BULK INSERT statement - that should look something like:

BULK INSERT dbo.YourTableName
FROM 'D:\directory\YourFileName.csv'
WITH
(
  CODEPAGE = '1252',
  FIELDTERMINATOR = ';',
  CHECK_CONSTRAINTS
) 

Here, in my case, I'm importing a CSV file - but you should be able to import a text file just as well.

From the MSDN docs - here's a sample that hopefully works for a text file with one field per row:

BULK INSERT dbo.temp 
   FROM 'c:\temp\file.txt'
   WITH 
      (
         ROWTERMINATOR ='\n'
      )

Seems to work just fine in my test environment :-)

How to create dispatch queue in Swift 3

Compiled in XCode 8, Swift 3 https://github.com/rpthomas/Jedisware

 @IBAction func tap(_ sender: AnyObject) {

    let thisEmail = "emailaddress.com"
    let thisPassword = "myPassword" 

    DispatchQueue.global(qos: .background).async {

        // Validate user input

        let result = self.validate(thisEmail, password: thisPassword)

        // Go back to the main thread to update the UI
        DispatchQueue.main.async {
            if !result
            {
                self.displayFailureAlert()
            }

        }
    }

}

How is the AND/OR operator represented as in Regular Expressions?

'^(part1|part2|part1,part2)$'

does it work?

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In line 2, there's a std::string involved (name). There are operations defined for char[] + std::string, std::string + char[], etc. "Hello " + name gives a std::string, which is added to " you are ", giving another string, etc.

In line 3, you're saying

char[] + char[] + char[]

and you can't just add arrays to each other.

Extracting text OpenCV

@dhanushka's approach showed the most promise but I wanted to play around in Python so went ahead and translated it for fun:

import cv2
import numpy as np
from cv2 import boundingRect, countNonZero, cvtColor, drawContours, findContours, getStructuringElement, imread, morphologyEx, pyrDown, rectangle, threshold

large = imread(image_path)
# downsample and use it for processing
rgb = pyrDown(large)
# apply grayscale
small = cvtColor(rgb, cv2.COLOR_BGR2GRAY)
# morphological gradient
morph_kernel = getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = morphologyEx(small, cv2.MORPH_GRADIENT, morph_kernel)
# binarize
_, bw = threshold(src=grad, thresh=0, maxval=255, type=cv2.THRESH_BINARY+cv2.THRESH_OTSU)
morph_kernel = getStructuringElement(cv2.MORPH_RECT, (9, 1))
# connect horizontally oriented regions
connected = morphologyEx(bw, cv2.MORPH_CLOSE, morph_kernel)
mask = np.zeros(bw.shape, np.uint8)
# find contours
im2, contours, hierarchy = findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# filter contours
for idx in range(0, len(hierarchy[0])):
    rect = x, y, rect_width, rect_height = boundingRect(contours[idx])
    # fill the contour
    mask = drawContours(mask, contours, idx, (255, 255, 2555), cv2.FILLED)
    # ratio of non-zero pixels in the filled region
    r = float(countNonZero(mask)) / (rect_width * rect_height)
    if r > 0.45 and rect_height > 8 and rect_width > 8:
        rgb = rectangle(rgb, (x, y+rect_height), (x+rect_width, y), (0,255,0),3)

Now to display the image:

from PIL import Image
Image.fromarray(rgb).show()

Not the most Pythonic of scripts but I tried to resemble the original C++ code as closely as possible for readers to follow.

It works almost as well as the original. I'll be happy to read suggestions how it could be improved/fixed to resemble the original results fully.

enter image description here

enter image description here

enter image description here

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How do I set the selected item in a comboBox to match my string using C#?

If the items in your ComboBox are strings, you can try:

comboBox1.SelectedItem = "test1";

setAttribute('display','none') not working

display is not an attribute - it's a CSS property. You need to access the style object for this:

document.getElementById('classRight').style.display = 'none';

How to list only the file names that changed between two commits?

To supplement @artfulrobot's answer, if you want to show changed files between two branches:

git diff --name-status mybranch..myotherbranch

Be careful on precedence. If you place the newer branch first then it would show files as deleted rather than added.

Adding a grep can refine things further:

git diff --name-status mybranch..myotherbranch | grep "A\t"

That will then show only files added in myotherbranch.

AngularJS : When to use service instead of factory

The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.

To put it simply each one of these providers is a specialized version of the other, in this order: provider > factory > value / constant / service.

So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.

This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.

AngularJS providers, factories, services, etc are all the same thing
(source: simplygoodcode.com)

For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

Run reg command in cmd (bat file)?

If memory serves correct, the reg add command will NOT create the entire directory path if it does not exist. Meaning that if any of the parent registry keys do not exist then they must be created manually one by one. It is really annoying, I know! Example:

@echo off
reg add "HKCU\Software\Policies"
reg add "HKCU\Software\Policies\Microsoft"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel" /v HomePage /t REG_DWORD /d 1 /f
pause

How to format a string as a telephone number in C#

Here is another way of doing it.

public string formatPhoneNumber(string _phoneNum)
{
    string phoneNum = _phoneNum;
    if (phoneNum == null)
        phoneNum = "";
    phoneNum = phoneNum.PadRight(10 - phoneNum.Length);
    phoneNum = phoneNum.Insert(0, "(").Insert(4,") ").Insert(9,"-");
    return phoneNum;
}

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Split value from one field to two

Unfortunately MySQL does not feature a split string function. However you can create a user defined function for this, such as the one described in the following article:

With that function:

DELIMITER $$

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255) DETERMINISTIC
BEGIN 
    RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');
END$$

DELIMITER ;

you would be able to build your query as follows:

SELECT SPLIT_STR(membername, ' ', 1) as memberfirst,
       SPLIT_STR(membername, ' ', 2) as memberlast
FROM   users;

If you prefer not to use a user defined function and you do not mind the query to be a bit more verbose, you can also do the following:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(membername, ' ', 1), ' ', -1) as memberfirst,
       SUBSTRING_INDEX(SUBSTRING_INDEX(membername, ' ', 2), ' ', -1) as memberlast
FROM   users;

Using OR operator in a jquery if statement

Update: using .indexOf() to detect if stat value is one of arr elements

Pure JavaScript

_x000D_
_x000D_
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
    var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
_x000D_
_x000D_

Multi-line string with extra space (preserved indentation)

it will work if you put it as below:

AA='first line
\nsecond line 
\nthird line'
echo $AA
output:
first line
second line
third line

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

Yahoo Finance API

Here's a simple scraper I created in c# to get streaming quote data printed out to a console. It should be easily converted to java. Based on the following post:

http://blog.underdog-projects.net/2009/02/bringing-the-yahoo-finance-stream-to-the-shell/

Not too fancy (i.e. no regex etc), just a fast & dirty solution.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace WebDataAddin
{
    public class YahooConstants
    {
        public const string AskPrice = "a00";
        public const string BidPrice = "b00";
        public const string DayRangeLow = "g00";
        public const string DayRangeHigh = "h00";
        public const string MarketCap = "j10";
        public const string Volume = "v00";
        public const string AskSize = "a50";
        public const string BidSize = "b60";
        public const string EcnBid = "b30";
        public const string EcnBidSize = "o50";
        public const string EcnExtHrBid = "z03";
        public const string EcnExtHrBidSize = "z04";
        public const string EcnAsk = "b20";
        public const string EcnAskSize = "o40";
        public const string EcnExtHrAsk = "z05";
        public const string EcnExtHrAskSize = "z07";
        public const string EcnDayHigh = "h01";
        public const string EcnDayLow = "g01";
        public const string EcnExtHrDayHigh = "h02";
        public const string EcnExtHrDayLow = "g11";
        public const string LastTradeTimeUnixEpochformat = "t10";
        public const string EcnQuoteLastTime = "t50";
        public const string EcnExtHourTime = "t51";
        public const string RtQuoteLastTime = "t53";
        public const string RtExtHourQuoteLastTime = "t54";
        public const string LastTrade = "l10";
        public const string EcnQuoteLastValue = "l90";
        public const string EcnExtHourPrice = "l91";
        public const string RtQuoteLastValue = "l84";
        public const string RtExtHourQuoteLastValue = "l86";
        public const string QuoteChangeAbsolute = "c10";
        public const string EcnQuoteAfterHourChangeAbsolute = "c81";
        public const string EcnQuoteChangeAbsolute = "c60";
        public const string EcnExtHourChange1 = "z02";
        public const string EcnExtHourChange2 = "z08";
        public const string RtQuoteChangeAbsolute = "c63";
        public const string RtExtHourQuoteAfterHourChangeAbsolute = "c85";
        public const string RtExtHourQuoteChangeAbsolute = "c64";
        public const string QuoteChangePercent = "p20";
        public const string EcnQuoteAfterHourChangePercent = "c82";
        public const string EcnQuoteChangePercent = "p40";
        public const string EcnExtHourPercentChange1 = "p41";
        public const string EcnExtHourPercentChange2 = "z09";
        public const string RtQuoteChangePercent = "p43";
        public const string RtExtHourQuoteAfterHourChangePercent = "c86";
        public const string RtExtHourQuoteChangePercent = "p44";

        public static readonly IDictionary<string, string> CodeMap = typeof(YahooConstants).GetFields().
            Where(field => field.FieldType == typeof(string)).
            ToDictionary(field => ((string)field.GetValue(null)).ToUpper(), field => field.Name);
    }

    public static class StringBuilderExtensions
    {
        public static bool HasPrefix(this StringBuilder builder, string prefix)
        {
            return ContainsAtIndex(builder, prefix, 0);
        }

        public static bool HasSuffix(this StringBuilder builder, string suffix)
        {
            return ContainsAtIndex(builder, suffix, builder.Length - suffix.Length);
        }

        private static bool ContainsAtIndex(this StringBuilder builder, string str, int index)
        {
            if (builder != null && !string.IsNullOrEmpty(str) && index >= 0
                && builder.Length >= str.Length + index)
            {
                return !str.Where((t, i) => builder[index + i] != t).Any();
            }
            return false;
        }
    }

    public class WebDataAddin
    {
        public const string ScriptStart = "<script>";
        public const string ScriptEnd = "</script>";

        public const string MessageStart = "try{parent.yfs_";
        public const string MessageEnd = ");}catch(e){}";

        public const string DataMessage = "u1f(";
        public const string InfoMessage = "mktmcb(";


        protected static T ParseJson<T>(string json)
        {
            // parse json - max acceptable value retrieved from 
            //http://forums.asp.net/t/1343461.aspx
            var deserializer = new JavaScriptSerializer { MaxJsonLength = 2147483647 };
            return deserializer.Deserialize<T>(json);
        }

        public static void Main()
        {
            const string symbols = "GBPUSD=X,SPY,MSFT,BAC,QQQ,GOOG";
            // these are constants in the YahooConstants enum above
            const string attrs = "b00,b60,a00,a50";
            const string url = "http://streamerapi.finance.yahoo.com/streamer/1.0?s={0}&k={1}&r=0&callback=parent.yfs_u1f&mktmcb=parent.yfs_mktmcb&gencallback=parent.yfs_gencb&region=US&lang=en-US&localize=0&mu=1";

            var req = WebRequest.Create(string.Format(url, symbols, attrs));
            req.Proxy.Credentials = CredentialCache.DefaultCredentials;
            var missingCodes = new HashSet<string>();
            var response = req.GetResponse();
            if(response != null)
            {
                var stream = response.GetResponseStream();
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var builder = new StringBuilder();
                        var initialPayloadReceived = false;
                        while (!reader.EndOfStream)
                        {
                            var c = (char)reader.Read();
                            builder.Append(c);
                            if(!initialPayloadReceived)
                            {
                                if (builder.HasSuffix(ScriptStart))
                                {
                                    // chop off the first part, and re-append the
                                    // script tag (this is all we care about)
                                    builder.Clear();
                                    builder.Append(ScriptStart);
                                    initialPayloadReceived = true;
                                }
                            }
                            else
                            {
                                // check if we have a fully formed message
                                // (check suffix first to avoid re-checking 
                                // the prefix over and over)
                                if (builder.HasSuffix(ScriptEnd) &&
                                    builder.HasPrefix(ScriptStart))
                                {
                                    var chop = ScriptStart.Length + MessageStart.Length;
                                    var javascript = builder.ToString(chop,
                                        builder.Length - ScriptEnd.Length - MessageEnd.Length - chop);

                                    if (javascript.StartsWith(DataMessage))
                                    {
                                        var json = ParseJson<Dictionary<string, object>>(
                                            javascript.Substring(DataMessage.Length));

                                        // parse out the data. key should be the symbol

                                        foreach(var symbol in json)
                                        {
                                            Console.WriteLine("Symbol: {0}", symbol.Key);
                                            var symbolData = (Dictionary<string, object>) symbol.Value;
                                            foreach(var dataAttr in symbolData)
                                            {
                                                var codeKey = dataAttr.Key.ToUpper();
                                                if (YahooConstants.CodeMap.ContainsKey(codeKey))
                                                {
                                                    Console.WriteLine("\t{0}: {1}", YahooConstants.
                                                        CodeMap[codeKey], dataAttr.Value);
                                                } else
                                                {
                                                    missingCodes.Add(codeKey);
                                                    Console.WriteLine("\t{0}: {1} (Warning! No Code Mapping Found)", 
                                                        codeKey, dataAttr.Value);
                                                }
                                            }
                                            Console.WriteLine();
                                        }

                                    } else if(javascript.StartsWith(InfoMessage))
                                    {
                                        var json = ParseJson<Dictionary<string, object>>(
                                            javascript.Substring(InfoMessage.Length));

                                        foreach (var dataAttr in json)
                                        {
                                            Console.WriteLine("\t{0}: {1}", dataAttr.Key, dataAttr.Value);
                                        }
                                        Console.WriteLine();
                                    } else
                                    {
                                        throw new Exception("Cannot recognize the message type");
                                    }
                                    builder.Clear();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

How to launch html using Chrome at "--allow-file-access-from-files" mode?

As of this writing, in OS X, it will usually look like this

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

If you are a freak like me, and put your apps in ~/Applications, then it will be

"/Users/yougohere/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --allow-file-access-from-files

If neither of those are working, then type chrome://version in your Chrome address bar, and it will tell you what "command line" invocation you should be using. Just add --allow-file-access-from-files to that.

Bound method error

The syntax problem is shadowing method and variable names. In the current version sort_word_list() is a method, and sorted_word_list is a variable, whereas num_words is both. Also, list.sort() modifies the list and replaces it with a sorted version; the sorted(list) function actually returns a new list.

But I suspect this indicates a design problem. What's the point of calls like

test.parser()
test.sort_word_list()
test.num_words()

which don't do anything? You should probably just have the methods figure out whether the appropriate counting and/or sorting has been done, and, if appropriate, do the count or sort and otherwise just return something.

E.G.,

def sort_word_list(self):
   if self.sorted_word_list is not None:
      self.sorted_word_list = sorted(self.word_list)
   return self.sorted_word_list

(Alternately, you could use properties.)

How to get package name from anywhere?

For those who are using Gradle, as @Billda mentioned, you can get the package name via:

BuildConfig.APPLICATION_ID

This gives you the package name declared in your app gradle:

android {
    defaultConfig {
        applicationId "com.domain.www"
    }
}

If you are interested to get the package name used by your java classes (which sometimes is different than applicationId), you can use

BuildConfig.class.getPackage().toString()

If you are confused which one to use, read here:

Note: The application ID used to be directly tied to your code's package name; so some Android APIs use the term "package name" in their method names and parameter names, but this is actually your application ID. For example, the Context.getPackageName() method returns your application ID. There's no need to ever share your code's true package name outside your app code.

How to convert a string from uppercase to lowercase in Bash?

I'm on Ubuntu 14.04, with Bash version 4.3.11. However, I still don't have the fun built in string manipulation ${y,,}

This is what I used in my script to force capitalization:

CAPITALIZED=`echo "${y}" | tr '[a-z]' '[A-Z]'`

How do I get the resource id of an image if I know its name?

You can use this function to get a Resource ID:

public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
    try {
        return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        throw new RuntimeException("Error getting Resource ID.", e)
    } 
}


So if you want to get a Drawable Resource ID, you can call the method like this:

getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());

(or from a fragment):

getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());


For a String Resource ID you can call it like this:

getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());

etc...


Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.

Read this

C# Listbox Item Double Click Event

I know this question is quite old, but I was looking for a solution to this problem too. The accepted solution is for WinForms not WPF which I think many who come here are looking for.

For anyone looking for a WPF solution, here is a great approach (via Oskar's answer here):

private void myListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DependencyObject obj = (DependencyObject)e.OriginalSource;

    while (obj != null && obj != myListBox)
    {
        if (obj.GetType() == typeof(ListBoxItem))
        {
             // Do something
             break;
         }
         obj = VisualTreeHelper.GetParent(obj);
    }
}

Basically, you walk up the VisualTree until you've either found a parent item that is a ListBoxItem, or you ascend up to the actual ListBox (and therefore did not click a ListBoxItem).

Is there a Python caching library?

Look at bda.cache http://pypi.python.org/pypi/bda.cache - uses ZCA and is tested with zope and bfg.

Explicitly select items from a list or tuple

Another possible solution:

sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
   a=[L[i]]
   sek=sek+a
print (sek)

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Self-Signed Certificate Authorities pip / conda

After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:

NEVER disable all SSL verification!

This creates a bad security culture. Don't be that person.

tl;dr

pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify

# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt

But where do we get ca-bundle.crt?


Get an up to date CA Bundle

cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox

https://curl.haxx.se/docs/caextract.html

I recommend you open up this cacert.pem file in a text editor as we will need to add our self-signed CA to this file.

Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:

----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----

https://support.ssl.com/Knowledgebase/Article/View/19/0/der-vs-crt-vs-cer-vs-pem-certificates-and-how-to-convert-them


Getting our Self Signed Certificate

Below are a few options on how to get our self signed certificate:

  • Via OpenSSL CLI
  • Via Browser
  • Via Python Scripting

Get our Self-Signed Certificate by OpenSSL CLI

https://unix.stackexchange.com/questions/451207/how-to-trust-self-signed-certificate-in-curl-command-line/468360#468360

echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem

Get our Self-Signed Certificate Authority via Browser

Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.

Copy the contents of this exported file and paste it at the end of your cacerts.pem file.

For consistency rename this file cacerts.pem --> ca-bundle.crt and place it somewhere easy like:

# Windows
%USERPROFILE%\certs\ca-bundle.crt

# or *nix
$HOME/certs/cabundle.crt

Get our Self-Signed Certificate Authority via Python

Thanks to all the brilliant answers in:

How to get response SSL certificate from requests in python?

I have put together the following to attempt to take it a step further.

https://github.com/neozenith/get-ca-py


Finally

Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.

pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt

OR

pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt

THEN

pip config list
conda config --show ssl_verify

# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'

References

File Upload with Angular Material

Another hacked solution, though might be a little cleaner by implementing a Proxy button:

HTML:

<input id="fileInput" type="file">
<md-button class="md-raised" ng-click="upload()">
  <label>AwesomeButtonName</label>
</md-button>

JS:

app.controller('NiceCtrl', function ( $scope) {
  $scope.upload = function () {
    angular.element(document.querySelector('#fileInput')).click();
  };
};

How do I detect IE 8 with jQuery?

It is documented in jQuery API Documentation. Check for Internet Explorer with $.browser.msie and then check its version with $.browser.version.

UPDATE: $.browser removed in jQuery 1.9

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

USB Debugging option greyed out

You have to enable USB debugging before plugging your device in to the computer. Unplug device then try to enable USB debugging. This should work. If so, you can then plug it back into the computer and it should work

How to create a dynamic array of integers

Since C++11, there's a safe alternative to new[] and delete[] which is zero-overhead unlike std::vector:

std::unique_ptr<int[]> array(new int[size]);

In C++14:

auto array = std::make_unique<int[]>(size);

Both of the above rely on the same header file, #include <memory>

Recursive search and replace in text files on Mac and Linux

If you are using a zsh terminal you're able to use wildcard magic:

sed -i "" "s/search/high-replace/g" *.txt

Function pointer as a member of a C struct

You can use also "void*" (void pointer) to send an address to the function.

typedef struct pstring_t {
    char * chars;
    int(*length)(void*);
} PString;

int length(void* self) {
    return strlen(((PString*)self)->chars);
}

PString initializeString() {
    PString str;
    str.length = &length;
    return str;
}

int main()
{
    PString p = initializeString();

    p.chars = "Hello";

    printf("Length: %i\n", p.length(&p));

    return 0;
}

Output:

Length: 5

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

Why can't I use switch statement on a String?

For years we've been using a(n open source) preprocessor for this.

//#switch(target)
case "foo": code;
//#end

Preprocessed files are named Foo.jpp and get processed into Foo.java with an ant script.

Advantage is it is processed into Java that runs on 1.0 (although typically we only supported back to 1.4). Also it was far easier to do this (lots of string switches) compared to fudging it with enums or other workarounds - code was a lot easier to read, maintain, and understand. IIRC (can't provide statistics or technical reasoning at this point) it was also faster than the natural Java equivalents.

Disadvantages are you aren't editing Java so it's a bit more workflow (edit, process, compile/test) plus an IDE will link back to the Java which is a little convoluted (the switch becomes a series of if/else logic steps) and the switch case order is not maintained.

I wouldn't recommend it for 1.7+ but it's useful if you want to program Java that targets earlier JVMs (since Joe public rarely has the latest installed).

You can get it from SVN or browse the code online. You'll need EBuild to build it as-is.

How to specify the actual x axis values to plot as x axis ticks in R

In case of plotting time series, the command ts.plot requires a different argument than xaxt="n"

require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Goto processes in mysql.

So can see there is task still working.

Kill the particular process or wait until process complete.

Structure padding and packing

Padding and packing are just two aspects of the same thing:

  • packing or alignment is the size to which each member is rounded off
  • padding is the extra space added to match the alignment

In mystruct_A, assuming a default alignment of 4, each member is aligned on a multiple of 4 bytes. Since the size of char is 1, the padding for a and c is 4 - 1 = 3 bytes while no padding is required for int b which is already 4 bytes. It works the same way for mystruct_B.

Can you target an elements parent element using event.target?

I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.

Otherwise parentNode might be what you're looking for.

link to currentTarget
link to parentNode

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

If you are getting this message from a Maven built war change the scope of the JDBC driver to provided, and put a copy of it in the lib directory. Like this:

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.18</version>
  <!-- put a copy in /usr/share/tomcat7/lib -->
  <scope>provided</scope>
</dependency>

int to hex string

Try C# string interpolation introduced in C# 6:

var id = 100;
var hexid = $"0x{id:X}";

hexid value:

"0x64"

Convert command line arguments into an array in Bash

Actually the list of parameters could be accessed with $1 $2 ... etc.
Which is exactly equivalent to:

${!i}

So, the list of parameters could be changed with set,
and ${!i} is the correct way to access them:

$ set -- aa bb cc dd 55 ff gg hh ii jjj kkk lll
$ for ((i=0;i<=$#;i++)); do echo "$#" "$i" "${!i}"; done
12 1 aa
12 2 bb
12 3 cc
12 4 dd
12 5 55
12 6 ff
12 7 gg
12 8 hh
12 9 ii
12 10 jjj
12 11 kkk
12 12 lll

For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given:

if [ "$#" -eq 0 ]; then
    set -- defaultarg1 defaultarg2
fi

which translates to this even simpler expression:

[ "$#" == "0" ] && set -- defaultarg1 defaultarg2

Execute PHP function with onclick

Try this it will work fine.

<script>
function echoHello(){
 alert("<?PHP hello(); ?>");
 }
</script>

<?PHP
FUNCTION hello(){
 echo "Call php function on onclick event.";
 }

?>

<button onclick="echoHello()">Say Hello</button>

Double precision - decimal places

IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.

An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.

Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.

Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.

Determine a string's encoding in C#

The SimpleHelpers.FileEncoding Nuget package wraps a C# port of the Mozilla Universal Charset Detector into a dead-simple API:

var encoding = FileEncoding.DetectFileEncoding(txtFile);

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Using two values for one switch case statement

With the integration of JEP 325: Switch Expressions (Preview) in JDK-12 early access builds, one can now make use of the new form of the switch label as :-

case text1, text4 -> {
     //blah
} 

or to rephrase the demo from one of the answers, something like :-

public class RephraseDemo {

    public static void main(String[] args) {
        int month = 9;
        int year = 2018;
        int numDays = 0;

        switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 ->{
                numDays = 31;
            }
            case 4, 6, 9, 11 ->{
                numDays = 30;
            }
            case 2 ->{
                if (((year % 4 == 0) &&
                        !(year % 100 == 0))
                        || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
            }
            default ->{
                System.out.println("Invalid month.");

            }
        }
        System.out.println("Number of Days = " + numDays);
    }
}

Here is how you can give it a try - Compile a JDK12 preview feature with Maven

How to make links in a TextView clickable?

This question is very old but none answered the obvious one. This code is taken from one of my hobby projects:

package com.stackoverflow.java.android;

import android.content.Context;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

public class HyperlinkTextView extends AppCompatTextView {
    public HyperlinkTextView(Context context) {
        super(context);
    }

    public HyperlinkTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HyperlinkTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Set default movement method to {@link LinkMovementMethod}
     * @return Link movement method as the default movement method
     */
    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return LinkMovementMethod.getInstance();
    }
}

Now, simply using com.stackoverflow.java.android.HyperlinkTextView instead of TextView in your layout files will solve your problem.

Generate random 5 characters string

function CaracteresAleatorios( $Tamanno, $Opciones) {
    $Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
    $Tamanno = empty($Tamanno) ? 16 : $Tamanno;
    $Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    $Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
    $CantidadCaracteres=strlen($Caracteres)-1;
    $CaracteresAleatorios='';
    for ($k = 0; $k < $Tamanno; $k++) {
        $CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
    }
    return $CaracteresAleatorios;
}

Node.js: How to read a stream into a buffer?

I just want to post my solution. Previous answers was pretty helpful for my research. I use length-stream to get the size of the stream, but the problem here is that the callback is fired near the end of the stream, so i also use stream-cache to cache the stream and pipe it to res object once i know the content-length. In case on an error,

var StreamCache = require('stream-cache');
var lengthStream = require('length-stream');

var _streamFile = function(res , stream , cb){
    var cache = new StreamCache();

    var lstream = lengthStream(function(length) {
        res.header("Content-Length", length);
        cache.pipe(res);
    });

    stream.on('error', function(err){
        return cb(err);
    });

    stream.on('end', function(){
        return cb(null , true);
    });

    return stream.pipe(lstream).pipe(cache);
}

Interface vs Abstract Class (general OO)

From Coding Perspective

An Interface can replace an Abstract Class if the Abstract Class has only abstract methods. Otherwise changing Abstract class to interface means that you will be losing out on code re-usability which Inheritance provides.

From Design Perspective

Keep it as an Abstract Class if it's an "Is a" relationship and you need a subset or all of the functionality. Keep it as Interface if it's a "Should Do" relationship.

Decide what you need: just the policy enforcement, or code re-usability AND policy.

C# Sort and OrderBy comparison

No, they aren't the same algorithm. For starters, the LINQ OrderBy is documented as stable (i.e. if two items have the same Name, they'll appear in their original order).

It also depends on whether you buffer the query vs iterate it several times (LINQ-to-Objects, unless you buffer the result, will re-order per foreach).

For the OrderBy query, I would also be tempted to use:

OrderBy(n => n.Name, StringComparer.{yourchoice}IgnoreCase);

(for {yourchoice} one of CurrentCulture, Ordinal or InvariantCulture).

List<T>.Sort

This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

Enumerable.OrderBy

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key. sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

MVC Calling a view from a different controller

To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.

public class CommentsController : Controller
{
    public ActionResult Index()
    { 
        return View("../Articles/Index", model );
    }
}

and

public class ArticlesController : Controller
{
    public ActionResult Index()
    { 
        return View();
    }
}

Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.

test if display = none

You can use the following code to test if display is equivalent to none:

if ($(element).css('display') === 'none' ){
    // do the stuff
}

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

The best way is as described in the following blog http://ali-reynolds.com/2013/06/29/hide-cells-in-static-table-view/

Design your static table view as normal in interface builder – complete with all potentially hidden cells. But there is one thing you must do for every potential cell that you want to hide – check the “Clip subviews” property of the cell, otherwise the content of the cell doesn’t disappear when you try and hide it (by shrinking it’s height – more later).

SO – you have a switch in a cell and the switch is supposed to hide and show some static cells. Hook it up to an IBAction and in there do this:

[self.tableView beginUpdates];
[self.tableView endUpdates];

That gives you nice animations for the cells appearing and disappearing. Now implement the following table view delegate method:

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) { // This is the cell to hide - change as you need
    // Show or hide cell
        if (self.mySwitch.on) {
            return 44; // Show the cell - adjust the height as you need
        } else {
            return 0; // Hide the cell
        }
   }
   return 44;
}

And that’s it. Flip the switch and the cell hides and reappears with a nice, smooth animation.

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Here is the function example trim generic type of array object

const trimArrayObject = <T>(items: T[]) => {

  items.forEach(function (o) {

    for (let [key, value] of Object.entries(o)) {

      const keyName = <keyof typeof o>key;

      if (Array.isArray(value)) {

        trimArrayObject(value);

      } else if (typeof o[keyName] === "string") {

        o[keyName] = value.trim();

      }

    }

  });

};

How to show all privileges from a user in oracle?

You can use below code to get all the privileges list from all users.

select * from dba_sys_privs 

Spring Boot application.properties value not populating

Actually, For me below works fine.

@Component
public class MyBean {

   public static String prop;

   @Value("${some.prop}")
   public void setProp(String prop) {
      this.prop= prop;
   }

   public MyBean() {

   }

   @PostConstruct
   public void init() {
      System.out.println("================== " + prop + "================== ");
   }

}

Now whereever i want, just invoke

MyBean.prop

it will return value.

The type arguments for method cannot be inferred from the usage

For those who are wondering why this works in Java but not C#, consider what happens if some doof wrote this class:

public class Trololol : ISignatur<bool>, ISignatur<int>{
    Type ISignatur<bool>.Type => typeof(bool);
    Type ISignatur<int>.Type => typeof(int);
}

How is the compiler supposed to resolve var access = service.Get(new Trololol())? Both int and bool are valid.

The reason this implicit resolution works in Java likely has to do with Erasure and how Java will throw a fit if you try to implement an interface with two or more different type arguments. Such a class is simply not allowed in Java, but is just fine in C#.

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

NodeJS - What does "socket hang up" actually mean?

I do both web (node) and Android development, and open Android Studio device simulator and docker together, both of them use port 8601, it complained socket hang up error, after close Android Studio device simulator and it works well in node side. Don’t use Android Studio device simulator and docker together.

Deleting an object in C++

Isn't this the normal way to free the memory associated with an object?

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

As an example of automatic resource management:

void test()
{
    std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

This may or may not exactly answer the question, but I ran into this issue (and question) when I had changed my account to have a new database I had created as my "default database". Then I deleted that database and wanted to test my creation script, from scratch. I logged off SSMS and was going to go back in, but was denied -- cannot log into default database was the error. D'oh!

What I did was, on the login dialog for SSMS, go to Options, Connection Properties, then type master on the "Connect to database" combobox. Click Connect. Got me in. From there you can run the command to:

ALTER LOGIN [DOMAIN\useracct] WITH DEFAULT_DATABASE=[master]
GO

How to drop all stored procedures at once in SQL Server database?

To get drop statements for all stored procedures in a database SELECT 'DROP PROCEDURE' + ' ' + F.NAME + ';' FROM SYS.objects AS F where type='P'

Check whether an input string contains a number in javascript

This is what you need.

      var hasNumber = /\d/;   
      hasNumber.test("ABC33SDF");  //true
      hasNumber.test("ABCSDF");  //false 

Redirect to specified URL on PHP script completion?

If "SOMETHING DONE" doesn't invovle any output via echo/print/etc, then:

<?php
   // SOMETHING DONE

   header('Location: http://stackoverflow.com');
?>

Need to find element in selenium by css

By.cssSelector(".ban") or By.cssSelector(".hot") or By.cssSelector(".ban.hot") should all select it unless there is another element that has those classes.

In CSS, .name means find an element that has a class with name. .foo.bar.baz means to find an element that has all of those classes (in the same element).

However, each of those selectors will select only the first element that matches it on the page. If you need something more specific, please post the HTML of the other elements that have those classes.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

React passing parameter via onclick event using ES6 syntax

Use the value attribute of the button element to pass the id, as

<button onClick={this.handleRemove} value={id}>Remove</button>

and then in handleRemove, read the value from event as:

handleRemove(event) {
...
 remove(event.target.value);
...
}

This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.

Get current domain

Everybody is using the parse_url function, but sometimes user may pass the argumet in different format.

So as to fix that, I have created the function. Check this out:

function fixDomainName($url='')
{
    $strToLower = strtolower(trim($url));
    $httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
    $httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
    $wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
    $explodeToArray = explode('/', $wwwPregReplace);
    $finalDomainName = trim($explodeToArray[0]);
    return $finalDomainName;
}

Just pass the URL and get the domain.

For example,

echo fixDomainName('https://stackoverflow.com');

will return the result will be

stackoverflow.com

And in some situation:

echo fixDomainName('stackoverflow.com/questions/id/slug');

And it will also return stackoverflow.com.