Programs & Examples On #Aspects

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

No converter found capable of converting from type to type

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

Researching this topic myself and having read the answers I recommend using the path.py library since it provides a context manager for changing the current working directory.

You then have something like

import path
if path.Path('../lib').isdir():
    with path.Path('..'):
        import lib

Although, you might just omit the isdir statement.

Here I'll add print statements to make it easy to follow what's happening

import path
import pandas

print(path.Path.getcwd())
print(path.Path('../lib').isdir())
if path.Path('../lib').isdir():
    with path.Path('..'):
        print(path.Path.getcwd())
        import lib
        print('Success!')
print(path.Path.getcwd())

which outputs in this example (where lib is at /home/jovyan/shared/notebooks/by-team/data-vis/demos/lib):

/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
/home/jovyan/shared/notebooks/by-team/data-vis/demos
/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart

Since the solution uses a context manager, you are guaranteed to go back to your previous working directory, no matter what state your kernel was in before the cell and no matter what exceptions are thrown by importing your library code.

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

command/usr/bin/codesign failed with exit code 1- code sign error

Open the project into the Xcode.
Select project.app file and right click on it, select “show in finder” option.
Open terminal and go to the project.app file path.

Type the following to commands one by one:

xattr -lr project.app
xattr -cr project.app

Open the project and run.

Spring Boot - Cannot determine embedded database driver class for database type NONE

If you really need "spring-boot-starter-data-jpa" as your project dependency and at the same time you don't want to allow your app to access any database, you can simply exclude auto-configuration classes

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Overall:You persist entity that is violating database rules like as saving entity that has varchar field over 250 chars ,something like that.

In my case it was a squishy problem with TestEntityManager ,because it use HSQL database /in memory database/ and it persist the user but when you try to find it ,it drops the same exception :/

@RunWith(SpringRunner.class)
@ContextConfiguration(classes= Application.class)
@DataJpaTest
@ActiveProfiles("test")
public class UserServicesTests {

@Autowired
private TestEntityManager testEntityManager;

@Autowired
private UserRepository userRepository;

@Test
public void oops() {
    User user = new User();
    user.setUsername("Toshko");
    //EMAIL IS REQUIRED:
    //user.setEmail("OPS");
    this.testEntityManager.persist(user);

    //HERE COMES TE EXCEPTION BECAUSE THE EMAIL FIELD IN TE DATABASE IS REQUIRED :
    this.userRepository.findUserByUsername("Toshko");

    System.out.println();
}
}

Spring Data JPA - "No Property Found for Type" Exception

If you are using ENUM like MessageStatus, you may need a converter. Just add this class:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * Convert ENUM type in JPA.
 */
@Converter(autoApply = true)
public class MessageStatusConverter implements AttributeConverter<MessageStatus, Integer> {
  @Override
  public Integer convertToDatabaseColumn(MessageStatus messageStatus) {
    return messageStatus.getValue();
  }

  @Override
  public MessageStatus convertToEntityAttribute(Integer i) {
    return MessageStatus.valueOf(i);
  }
}

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

Transaction marked as rollback only: How do I find the cause

I finally understood the problem:

methodA() {
    methodB()
}

@Transactional(noRollbackFor = Exception.class)
methodB() {
    ...
    try {
        methodC()
    } catch (...) {...}
    log("OK");
}

@Transactional
methodC() {
    throw new ...();
}

What happens is that even though the methodB has the right annotation, the methodC does not. When the exception is thrown, the second @Transactional marks the first transaction as Rollback only anyway.

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I found this blog post which cleared up a few things. To quote the most relevant bit:

Mixed Active Content is now blocked by default in Firefox 23!

What is Mixed Content?
When a user visits a page served over HTTP, their connection is open for eavesdropping and man-in-the-middle (MITM) attacks. When a user visits a page served over HTTPS, their connection with the web server is authenticated and encrypted with SSL and hence safeguarded from eavesdroppers and MITM attacks.

However, if an HTTPS page includes HTTP content, the HTTP portion can be read or modified by attackers, even though the main page is served over HTTPS. When an HTTPS page has HTTP content, we call that content “mixed”. The webpage that the user is visiting is only partially encrypted, since some of the content is retrieved unencrypted over HTTP. The Mixed Content Blocker blocks certain HTTP requests on HTTPS pages.

The resolution, in my case, was to simply ensure the jquery includes were as follows (note the removal of the protocol):

<link rel="stylesheet" href="//code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css" type="text/css">
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"></script>

Note that the temporary 'fix' is to click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page', although this is not recommended for obvious reasons.

UPDATE: This link from the Firefox (Mozilla) support pages is also useful in explaining what constitutes mixed content and, as given in the above paragraph, does actually provide details of how to display the page regardless:

Most websites will continue to work normally without any action on your part.

If you need to allow the mixed content to be displayed, you can do that easily:

Click the shield icon Mixed Content Shield in the address bar and choose Disable Protection on This Page from the dropdown menu.

The icon in the address bar will change to an orange warning triangle Warning Identity Icon to remind you that insecure content is being displayed.

To revert the previous action (re-block mixed content), just reload the page.

How can I pair socks from a pile efficiently?

Pick up a first sock and place it on a table. Now pick another sock; if it matches the first picked, place it on top of the first. If not, place it on the table a small distance from the first. Pick a third sock; if it matches either of the previous two, place it on top of them or else place it a small distance from the third. Repeat until you have picked up all the socks.

Eclipse Workspaces: What for and why?

Basically the scope of workspace(s) is divided in two points.

First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.

And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.

Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!

deleted object would be re-saved by cascade (remove deleted object from associations)

I encountered this exception message as well. For me the problem was different. I wanted to delete a parent.

In one transaction:

  • First I called up the parent from the database.
  • Then I called a child element from a collection in the parent.
  • Then I referenced one field in the child (id)
  • Then I deleted the parent.
  • Then I called commit.
  • I got the "deleted object would be resaved" error.

It turns out that I had to do two separate transactions. I committed after referencing the field in the child. Then started a new commit for the delete.

There was no need to delete the child elements or empty the collections in the parent (assuming orphanRemoval = true.). In fact, this didn't work.

In sum, this error appears if you have a reference to a field in a child object when that object is being deleted.

What are advantages of Artificial Neural Networks over Support Vector Machines?

Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.

One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.

Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.

EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.

How to add multiple jar files in classpath in linux

The classpath is the place(s) where the java compiler (command: javac) and the JVM (command:java) look in order to find classes which your application reference. What does it mean for an application to reference another class ? In simple words it means to use that class somewhere in its code:

Example:

public class MyClass{
    private AnotherClass referenceToAnotherClass;
    .....
}

When you try to compile this (javac) the compiler will need the AnotherClass class. The same when you try to run your application: the JVM will need the AnotherClass class. In order to to find this class the javac and the JVM look in a particular (set of) place(s). Those places are specified by the classpath which on linux is a colon separated list of directories (directories where the javac/JVM should look in order to locate the AnotherClass when they need it).

So in order to compile your class and then to run it, you should make sure that the classpath contains the directory containing the AnotherClass class. Then you invoke it like this:

javac -classpath "dir1;dir2;path/to/AnotherClass;...;dirN" MyClass.java //to compile it
java -classpath "dir1;dir2;path/to/AnotherClass;...;dirN" MyClass //to run it

Usually classes come in the form of "bundles" called jar files/libraries. In this case you have to make sure that the jar containing the AnotherClass class is on your classpaht:

javac -classpath "dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" MyClass.java //to compile it
java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" MyClass //to run it

In the examples above you can see how to compile a class (MyClass.java) located in the working directory and then run the compiled class (Note the "." at the begining of the classpath which stands for current directory). This directory has to be added to the classpath too. Otherwise, the JVM won't be able to find it.

If you have your class in a jar file, as you specified in the question, then you have to make sure that jar is in the classpath too , together with the rest of the needed directories.

Example:

java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar...;dirN" MyClass //to run it

or more general (assuming some package hierarchy):

java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar...;dirN" package.subpackage.MyClass //to run it

In order to avoid setting the classpath everytime you want to run an application you can define an environment variable called CLASSPATH.

In linux, in command prompt:

export CLASSPATH="dir1;dir2;path/to/jar/containing/AnotherClass;...;dirN" 

or edit the ~/.bashrc and add this line somewhere at the end;

However, the class path is subject to frequent changes so, you might want to have the classpath set to a core set of dirs, which you need frequently and then extends the classpath each time you need for that session only. Like this:

export CLASSPATH=$CLASSPATH:"new directories according to your current needs" 

Auto height div with overflow and scroll when needed

_x000D_
_x000D_
$(document).ready(function() {
//Fix dropdown-menu box size upto 2 items but above 2 items scroll the menu box
    $("#dropdown").click(function() {
        var maxHeight = 301;
        if ($(".dropdown-menu").height() > maxHeight) { 
            maxHeight = 302;
            $(".dropdown-menu").height(maxHeight);
            $(".dropdown-menu").css({'overflow-y':'scroll'});
        } else {
            $(".dropdown-menu").height();
            $(".dropdown-menu").css({'overflow-y':'hidden'});
        }
    });
});
_x000D_
_x000D_
_x000D_

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

Just in case someone checked this thread and had the same issue as mine...

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I'm using NHibernate, I receive same error, during creating an object...

I was passing the key manually, and also specified a GUID generator in mapping, so hibernate generate same exact error for me, so once I removed the GUID, and left the field empty, everything went just fine.

this answer may not help you, but will help someone like me, who just your thread becasue of same error

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I followed the GUI hint to finding any connector, and then I found AspectJ Integrator from SpringSource Team. After installation, it was settled.

Why does modern Perl avoid UTF-8 by default?

?:

  1. Set your PERL_UNICODE envariable to AS. This makes all Perl scripts decode @ARGV as UTF-8 strings, and sets the encoding of all three of stdin, stdout, and stderr to UTF-8. Both these are global effects, not lexical ones.

  2. At the top of your source file (program, module, library, dohickey), prominently assert that you are running perl version 5.12 or better via:

    use v5.12;  # minimal for unicode string feature
    use v5.14;  # optimal for unicode string feature
    
  3. Enable warnings, since the previous declaration only enables strictures and features, not warnings. I also suggest promoting Unicode warnings into exceptions, so use both these lines, not just one of them. Note however that under v5.14, the utf8 warning class comprises three other subwarnings which can all be separately enabled: nonchar, surrogate, and non_unicode. These you may wish to exert greater control over.

    use warnings;
    use warnings qw( FATAL utf8 );
    
  4. Declare that this source unit is encoded as UTF-8. Although once upon a time this pragma did other things, it now serves this one singular purpose alone and no other:

    use utf8;
    
  5. Declare that anything that opens a filehandle within this lexical scope but not elsewhere is to assume that that stream is encoded in UTF-8 unless you tell it otherwise. That way you do not affect other module’s or other program’s code.

    use open qw( :encoding(UTF-8) :std );
    
  6. Enable named characters via \N{CHARNAME}.

    use charnames qw( :full :short );
    
  7. If you have a DATA handle, you must explicitly set its encoding. If you want this to be UTF-8, then say:

    binmode(DATA, ":encoding(UTF-8)");
    

There is of course no end of other matters with which you may eventually find yourself concerned, but these will suffice to approximate the state goal to “make everything just work with UTF-8”, albeit for a somewhat weakened sense of those terms.

One other pragma, although it is not Unicode related, is:

      use autodie;

It is strongly recommended.


? ?


My own boilerplate these days tends to look like this:

use 5.014;

use utf8;
use strict;
use autodie;
use warnings; 
use warnings    qw< FATAL  utf8     >;
use open        qw< :std  :utf8     >;
use charnames   qw< :full >;
use feature     qw< unicode_strings >;

use File::Basename      qw< basename >;
use Carp                qw< carp croak confess cluck >;
use Encode              qw< encode decode >;
use Unicode::Normalize  qw< NFD NFC >;

END { close STDOUT }

if (grep /\P{ASCII}/ => @ARGV) { 
   @ARGV = map { decode("UTF-8", $_) } @ARGV;
}

$0 = basename($0);  # shorter messages
$| = 1;

binmode(DATA, ":utf8");

# give a full stack dump on any untrapped exceptions
local $SIG{__DIE__} = sub {
    confess "Uncaught exception: @_" unless $^S;
};

# now promote run-time warnings into stack-dumped
#   exceptions *unless* we're in an try block, in
#   which case just cluck the stack dump instead
local $SIG{__WARN__} = sub {
    if ($^S) { cluck   "Trapped warning: @_" } 
    else     { confess "Deadly warning: @_"  }
};

while (<>)  {
    chomp;
    $_ = NFD($_);
    ...
} continue {
    say NFC($_);
}

__END__


Saying that “Perl should [somehow!] enable Unicode by default” doesn’t even start to begin to think about getting around to saying enough to be even marginally useful in some sort of rare and isolated case. Unicode is much much more than just a larger character repertoire; it’s also how those characters all interact in many, many ways.

Even the simple-minded minimal measures that (some) people seem to think they want are guaranteed to miserably break millions of lines of code, code that has no chance to “upgrade” to your spiffy new Brave New World modernity.

It is way way way more complicated than people pretend. I’ve thought about this a huge, whole lot over the past few years. I would love to be shown that I am wrong. But I don’t think I am. Unicode is fundamentally more complex than the model that you would like to impose on it, and there is complexity here that you can never sweep under the carpet. If you try, you’ll break either your own code or somebody else’s. At some point, you simply have to break down and learn what Unicode is about. You cannot pretend it is something it is not.

goes out of its way to make Unicode easy, far more than anything else I’ve ever used. If you think this is bad, try something else for a while. Then come back to : either you will have returned to a better world, or else you will bring knowledge of the same with you so that we can make use of your new knowledge to make better at these things.


?


At a minimum, here are some things that would appear to be required for to “enable Unicode by default”, as you put it:

  1. All source code should be in UTF-8 by default. You can get that with use utf8 or export PERL5OPTS=-Mutf8.

  2. The DATA handle should be UTF-8. You will have to do this on a per-package basis, as in binmode(DATA, ":encoding(UTF-8)").

  3. Program arguments to scripts should be understood to be UTF-8 by default. export PERL_UNICODE=A, or perl -CA, or export PERL5OPTS=-CA.

  4. The standard input, output, and error streams should default to UTF-8. export PERL_UNICODE=S for all of them, or I, O, and/or E for just some of them. This is like perl -CS.

  5. Any other handles opened by should be considered UTF-8 unless declared otherwise; export PERL_UNICODE=D or with i and o for particular ones of these; export PERL5OPTS=-CD would work. That makes -CSAD for all of them.

  6. Cover both bases plus all the streams you open with export PERL5OPTS=-Mopen=:utf8,:std. See uniquote.

  7. You don’t want to miss UTF-8 encoding errors. Try export PERL5OPTS=-Mwarnings=FATAL,utf8. And make sure your input streams are always binmoded to :encoding(UTF-8), not just to :utf8.

  8. Code points between 128–255 should be understood by to be the corresponding Unicode code points, not just unpropertied binary values. use feature "unicode_strings" or export PERL5OPTS=-Mfeature=unicode_strings. That will make uc("\xDF") eq "SS" and "\xE9" =~ /\w/. A simple export PERL5OPTS=-Mv5.12 or better will also get that.

  9. Named Unicode characters are not by default enabled, so add export PERL5OPTS=-Mcharnames=:full,:short,latin,greek or some such. See uninames and tcgrep.

  10. You almost always need access to the functions from the standard Unicode::Normalize module various types of decompositions. export PERL5OPTS=-MUnicode::Normalize=NFD,NFKD,NFC,NFKD, and then always run incoming stuff through NFD and outbound stuff from NFC. There’s no I/O layer for these yet that I’m aware of, but see nfc, nfd, nfkd, and nfkc.

  11. String comparisons in using eq, ne, lc, cmp, sort, &c&cc are always wrong. So instead of @a = sort @b, you need @a = Unicode::Collate->new->sort(@b). Might as well add that to your export PERL5OPTS=-MUnicode::Collate. You can cache the key for binary comparisons.

  12. built-ins like printf and write do the wrong thing with Unicode data. You need to use the Unicode::GCString module for the former, and both that and also the Unicode::LineBreak module as well for the latter. See uwc and unifmt.

  13. If you want them to count as integers, then you are going to have to run your \d+ captures through the Unicode::UCD::num function because ’s built-in atoi(3) isn’t currently clever enough.

  14. You are going to have filesystem issues on filesystems. Some filesystems silently enforce a conversion to NFC; others silently enforce a conversion to NFD. And others do something else still. Some even ignore the matter altogether, which leads to even greater problems. So you have to do your own NFC/NFD handling to keep sane.

  15. All your code involving a-z or A-Z and such MUST BE CHANGED, including m//, s///, and tr///. It’s should stand out as a screaming red flag that your code is broken. But it is not clear how it must change. Getting the right properties, and understanding their casefolds, is harder than you might think. I use unichars and uniprops every single day.

  16. Code that uses \p{Lu} is almost as wrong as code that uses [A-Za-z]. You need to use \p{Upper} instead, and know the reason why. Yes, \p{Lowercase} and \p{Lower} are different from \p{Ll} and \p{Lowercase_Letter}.

  17. Code that uses [a-zA-Z] is even worse. And it can’t use \pL or \p{Letter}; it needs to use \p{Alphabetic}. Not all alphabetics are letters, you know!

  18. If you are looking for variables with /[\$\@\%]\w+/, then you have a problem. You need to look for /[\$\@\%]\p{IDS}\p{IDC}*/, and even that isn’t thinking about the punctuation variables or package variables.

  19. If you are checking for whitespace, then you should choose between \h and \v, depending. And you should never use \s, since it DOES NOT MEAN [\h\v], contrary to popular belief.

  20. If you are using \n for a line boundary, or even \r\n, then you are doing it wrong. You have to use \R, which is not the same!

  21. If you don’t know when and whether to call Unicode::Stringprep, then you had better learn.

  22. Case-insensitive comparisons need to check for whether two things are the same letters no matter their diacritics and such. The easiest way to do that is with the standard Unicode::Collate module. Unicode::Collate->new(level => 1)->cmp($a, $b). There are also eq methods and such, and you should probably learn about the match and substr methods, too. These are have distinct advantages over the built-ins.

  23. Sometimes that’s still not enough, and you need the Unicode::Collate::Locale module instead, as in Unicode::Collate::Locale->new(locale => "de__phonebook", level => 1)->cmp($a, $b) instead. Consider that Unicode::Collate::->new(level => 1)->eq("d", "ð") is true, but Unicode::Collate::Locale->new(locale=>"is",level => 1)->eq("d", " ð") is false. Similarly, "ae" and "æ" are eq if you don’t use locales, or if you use the English one, but they are different in the Icelandic locale. Now what? It’s tough, I tell you. You can play with ucsort to test some of these things out.

  24. Consider how to match the pattern CVCV (consonsant, vowel, consonant, vowel) in the string “niño”. Its NFD form — which you had darned well better have remembered to put it in — becomes “nin\x{303}o”. Now what are you going to do? Even pretending that a vowel is [aeiou] (which is wrong, by the way), you won’t be able to do something like (?=[aeiou])\X) either, because even in NFD a code point like ‘ø’ does not decompose! However, it will test equal to an ‘o’ using the UCA comparison I just showed you. You can’t rely on NFD, you have to rely on UCA.



And that’s not all. There are a million broken assumptions that people make about Unicode. Until they understand these things, their code will be broken.

  1. Code that assumes it can open a text file without specifying the encoding is broken.

  2. Code that assumes the default encoding is some sort of native platform encoding is broken.

  3. Code that assumes that web pages in Japanese or Chinese take up less space in UTF-16 than in UTF-8 is wrong.

  4. Code that assumes Perl uses UTF-8 internally is wrong.

  5. Code that assumes that encoding errors will always raise an exception is wrong.

  6. Code that assumes Perl code points are limited to 0x10_FFFF is wrong.

  7. Code that assumes you can set $/ to something that will work with any valid line separator is wrong.

  8. Code that assumes roundtrip equality on casefolding, like lc(uc($s)) eq $s or uc(lc($s)) eq $s, is completely broken and wrong. Consider that the uc("s") and uc("?") are both "S", but lc("S") cannot possibly return both of those.

  9. Code that assumes every lowercase code point has a distinct uppercase one, or vice versa, is broken. For example, "ª" is a lowercase letter with no uppercase; whereas both "?" and "?" are letters, but they are not lowercase letters; however, they are both lowercase code points without corresponding uppercase versions. Got that? They are not \p{Lowercase_Letter}, despite being both \p{Letter} and \p{Lowercase}.

  10. Code that assumes changing the case doesn’t change the length of the string is broken.

  11. Code that assumes there are only two cases is broken. There’s also titlecase.

  12. Code that assumes only letters have case is broken. Beyond just letters, it turns out that numbers, symbols, and even marks have case. In fact, changing the case can even make something change its main general category, like a \p{Mark} turning into a \p{Letter}. It can also make it switch from one script to another.

  13. Code that assumes that case is never locale-dependent is broken.

  14. Code that assumes Unicode gives a fig about POSIX locales is broken.

  15. Code that assumes you can remove diacritics to get at base ASCII letters is evil, still, broken, brain-damaged, wrong, and justification for capital punishment.

  16. Code that assumes that diacritics \p{Diacritic} and marks \p{Mark} are the same thing is broken.

  17. Code that assumes \p{GC=Dash_Punctuation} covers as much as \p{Dash} is broken.

  18. Code that assumes dash, hyphens, and minuses are the same thing as each other, or that there is only one of each, is broken and wrong.

  19. Code that assumes every code point takes up no more than one print column is broken.

  20. Code that assumes that all \p{Mark} characters take up zero print columns is broken.

  21. Code that assumes that characters which look alike are alike is broken.

  22. Code that assumes that characters which do not look alike are not alike is broken.

  23. Code that assumes there is a limit to the number of code points in a row that just one \X can match is wrong.

  24. Code that assumes \X can never start with a \p{Mark} character is wrong.

  25. Code that assumes that \X can never hold two non-\p{Mark} characters is wrong.

  26. Code that assumes that it cannot use "\x{FFFF}" is wrong.

  27. Code that assumes a non-BMP code point that requires two UTF-16 (surrogate) code units will encode to two separate UTF-8 characters, one per code unit, is wrong. It doesn’t: it encodes to single code point.

  28. Code that transcodes from UTF-16 or UTF-32 with leading BOMs into UTF-8 is broken if it puts a BOM at the start of the resulting UTF-8. This is so stupid the engineer should have their eyelids removed.

  29. Code that assumes the CESU-8 is a valid UTF encoding is wrong. Likewise, code that thinks encoding U+0000 as "\xC0\x80" is UTF-8 is broken and wrong. These guys also deserve the eyelid treatment.

  30. Code that assumes characters like > always points to the right and < always points to the left are wrong — because they in fact do not.

  31. Code that assumes if you first output character X and then character Y, that those will show up as XY is wrong. Sometimes they don’t.

  32. Code that assumes that ASCII is good enough for writing English properly is stupid, shortsighted, illiterate, broken, evil, and wrong. Off with their heads! If that seems too extreme, we can compromise: henceforth they may type only with their big toe from one foot. (The rest will be duct taped.)

  33. Code that assumes that all \p{Math} code points are visible characters is wrong.

  34. Code that assumes \w contains only letters, digits, and underscores is wrong.

  35. Code that assumes that ^ and ~ are punctuation marks is wrong.

  36. Code that assumes that ü has an umlaut is wrong.

  37. Code that believes things like ? contain any letters in them is wrong.

  38. Code that believes \p{InLatin} is the same as \p{Latin} is heinously broken.

  39. Code that believe that \p{InLatin} is almost ever useful is almost certainly wrong.

  40. Code that believes that given $FIRST_LETTER as the first letter in some alphabet and $LAST_LETTER as the last letter in that same alphabet, that [${FIRST_LETTER}-${LAST_LETTER}] has any meaning whatsoever is almost always complete broken and wrong and meaningless.

  41. Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong.

  42. Code that tries to reduce Unicode to ASCII is not merely wrong, its perpetrator should never be allowed to work in programming again. Period. I’m not even positive they should even be allowed to see again, since it obviously hasn’t done them much good so far.

  43. Code that believes there’s some way to pretend textfile encodings don’t exist is broken and dangerous. Might as well poke the other eye out, too.

  44. Code that converts unknown characters to ? is broken, stupid, braindead, and runs contrary to the standard recommendation, which says NOT TO DO THAT! RTFM for why not.

  45. Code that believes it can reliably guess the encoding of an unmarked textfile is guilty of a fatal mélange of hubris and naïveté that only a lightning bolt from Zeus will fix.

  46. Code that believes you can use printf widths to pad and justify Unicode data is broken and wrong.

  47. Code that believes once you successfully create a file by a given name, that when you run ls or readdir on its enclosing directory, you’ll actually find that file with the name you created it under is buggy, broken, and wrong. Stop being surprised by this!

  48. Code that believes UTF-16 is a fixed-width encoding is stupid, broken, and wrong. Revoke their programming licence.

  49. Code that treats code points from one plane one whit differently than those from any other plane is ipso facto broken and wrong. Go back to school.

  50. Code that believes that stuff like /s/i can only match "S" or "s" is broken and wrong. You’d be surprised.

  51. Code that uses \PM\pM* to find grapheme clusters instead of using \X is broken and wrong.

  52. People who want to go back to the ASCII world should be whole-heartedly encouraged to do so, and in honor of their glorious upgrade they should be provided gratis with a pre-electric manual typewriter for all their data-entry needs. Messages sent to them should be sent via an ??????s telegraph at 40 characters per line and hand-delivered by a courier. STOP.



I don’t know how much more “default Unicode in ” you can get than what I’ve written. Well, yes I do: you should be using Unicode::Collate and Unicode::LineBreak, too. And probably more.

As you see, there are far too many Unicode things that you really do have to worry about for there to ever exist any such thing as “default to Unicode”.

What you’re going to discover, just as we did back in 5.8, that it is simply impossible to impose all these things on code that hasn’t been designed right from the beginning to account for them. Your well-meaning selfishness just broke the entire world.

And even once you do, there are still critical issues that require a great deal of thought to get right. There is no switch you can flip. Nothing but brain, and I mean real brain, will suffice here. There’s a heck of a lot of stuff you have to learn. Modulo the retreat to the manual typewriter, you simply cannot hope to sneak by in ignorance. This is the 21?? century, and you cannot wish Unicode away by willful ignorance.

You have to learn it. Period. It will never be so easy that “everything just works,” because that will guarantee that a lot of things don’t work — which invalidates the assumption that there can ever be a way to “make it all work.”

You may be able to get a few reasonable defaults for a very few and very limited operations, but not without thinking about things a whole lot more than I think you have.

As just one example, canonical ordering is going to cause some real headaches. "\x{F5}" ‘õ’, "o\x{303}" ‘õ’, "o\x{303}\x{304}" ‘?’, and "o\x{304}\x{303}" ‘o~’ should all match ‘õ’, but how in the world are you going to do that? This is harder than it looks, but it’s something you need to account for.

If there’s one thing I know about Perl, it is what its Unicode bits do and do not do, and this thing I promise you: “ _?_?_?_?_?_ _?_s_ _?_?_ _U_?_?_?_?_?_?_ _?_?_?_?_?_ _?_?_?_?_?_?_ _ ”

You cannot just change some defaults and get smooth sailing. It’s true that I run with PERL_UNICODE set to "SA", but that’s all, and even that is mostly for command-line stuff. For real work, I go through all the many steps outlined above, and I do it very, ** very** carefully.


¡?dl?? ???? ?do? pu? ???p ???u ? ???? ???nl poo?

Maven2: Missing artifact but jars are in place

After not much success with any of the answers available here so far.

My solution:

I downloaded the jar file manually and then installed the dependency by using Apache Maven install:install-file plugin, see more details here

A Full Example:

<dependency>
     <groupId>commons-net</groupId>
     <artifactId>commons-net</artifactId>
     <version>3.4</version>
</dependency>
  1. Download jar file from here

  2. Install it by using the following command:

mvn -X install:install-file " -DgroupId=commons-net" "-DartifactId=commons-net" "-Dversion=3.4" "-Dpackaging=jar" "-Dfile={your_full_downloads_path}/commons-net-3.4.jar"

  1. Click on the project and select Maven->Update Project

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Have you tried using the !important flag on the style? !important allows you to decide which style will win out. Also note !important will override inline styles as well.

#example p {
    color: blue !important;
}
...
#example p {
    color: red;
}

Another couple suggestions:

Add a span inside of the current. The inner most will win out. Although this could get pretty ugly.

<span class="style21">
<span style="position:absolute;top:432px;left:422px; color:Red" >relating to</span>
</span>

jQuery is also an option. The jQuery library will inject the style attribute in the targeted element.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript" ></script>
    <script type="text/javascript">

        $(document).ready(function() {
            $("span").css("color", "#ff0000");
        });

    </script>

Hope this helps. CSS can be pretty frustrating at times.

Singletons vs. Application Context in Android?

From the proverbial horse's mouth...

When developing your app, you may find it necessary to share data, context or services globally across your app. For example, if your app has session data, such as the currently logged-in user, you will likely want to expose this information. In Android, the pattern for solving this problem is to have your android.app.Application instance own all global data, and then treat your Application instance as a singleton with static accessors to the various data and services.

When writing an Android app, you're guaranteed to only have one instance of the android.app.Application class, and so it's safe (and recommended by Google Android team) to treat it as a singleton. That is, you can safely add a static getInstance() method to your Application implementation. Like so:

public class AndroidApplication extends Application {

    private static AndroidApplication sInstance;

    public static AndroidApplication getInstance(){
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }
}

Default visibility for C# classes and members (fields, methods, etc.)?

All of the information you are looking for can be found here and here (thanks Reed Copsey):

From the first link:

Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.

...

The access level for class members and struct members, including nested classes and structs, is private by default.

...

interfaces default to internal access.

...

Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.


From the second link:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.

And for nested types:

Members of    Default member accessibility
----------    ----------------------------
enum          public
class         private
interface     public
struct        private

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This happened to me once by accident when I was assigning specific IDs to some objects (testing) and then I was trying to save them in the database. The problem was that in the database there was an specific policy for setting up the IDs of the objects. Just do not assign an ID if you have a policy at Hibernate level.

Daylight saving time and time zone best practices

You need to know about the Olson tz database, which is available from ftp://elsie.nci.nih.gov/pub http://iana.org/time-zones/. It is updated multiple times per year to deal with the often last-minute changes in when (and whether) to switch between winter and summer (standard and daylight saving) time in different countries around the world. In 2009, the last release was 2009s; in 2010, it was 2010n; in 2011, it was 2011n; at the end of May 2012, the release was 2012c. Note that there is a set of code to manage the data and the actual time zone data itself, in two separate archives (tzcode20xxy.tar.gz and tzdata20xxy.tar.gz). Both code and data are in the public domain.

This is the source of time zone names such as America/Los_Angeles (and synonyms such as US/Pacific).

If you need to keep track of different zones, then you need the Olson database. As others have advised, you also want to store the data in a fixed format — UTC is normally the one chosen — along with a record of the time zone in which the data was generated. You may want to distinguish between the offset from UTC at the time and the time zone name; that can make a difference later. Also, knowing that it is currently 2010-03-28T23:47:00-07:00 (US/Pacific) may or may not help you with interpreting the value 2010-11-15T12:30 — which is presumably specified in PST (Pacific Standard Time) rather than PDT (Pacific Daylight Saving Time).

The standard C library interfaces are not dreadfully helpful with this sort of stuff.


The Olson data has moved, in part because A D Olson will be retiring soon, and in part because there was a (now dismissed) law suit against the maintainers for copyright infringement. The time zone database is now managed under the auspices of IANA, the Internet Assigned Numbers Authority, and there's a link on the front page to 'Time Zone Database'. The discussion mailing list is now [email protected]; the announcement list is [email protected].

String was not recognized as a valid DateTime " format dd/MM/yyyy"

Use DateTime.ParseExact.

this.Text="22/11/2009";

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

Encountered this error while using maven-shade-plugin, the solution was including:

META-INF/spring.schemas

and

META-INF/spring.handlers

transformers in the maven-shade-plugin when building...

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>shade</goal>
                </goals>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>
                    </transformers>
                </configuration>
            </execution>
        </executions>
    </plugin>

(Credits: Idea to avoid that spring.handlers/spring.schemas get overwritten when merging multiple spring dependencies in a single jar)

Setting up an MS-Access DB for multi-user access

Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:

  1. No Locks
  2. All Records
  3. Edited Record

You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.

Transactions shouldn't be a problem if you use them correctly.

Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.

See other answers for Oracle comparison.

When is assembly faster than C?

Short answer? Sometimes.

Technically every abstraction has a cost and a programming language is an abstraction for how the CPU works. C however is very close. Years ago I remember laughing out loud when I logged onto my UNIX account and got the following fortune message (when such things were popular):

The C Programming Language -- A language which combines the flexibility of assembly language with the power of assembly language.

It's funny because it's true: C is like portable assembly language.

It's worth noting that assembly language just runs however you write it. There is however a compiler in between C and the assembly language it generates and that is extremely important because how fast your C code is has an awful lot to do with how good your compiler is.

When gcc came on the scene one of the things that made it so popular was that it was often so much better than the C compilers that shipped with many commercial UNIX flavours. Not only was it ANSI C (none of this K&R C rubbish), was more robust and typically produced better (faster) code. Not always but often.

I tell you all this because there is no blanket rule about the speed of C and assembler because there is no objective standard for C.

Likewise, assembler varies a lot depending on what processor you're running, your system spec, what instruction set you're using and so on. Historically there have been two CPU architecture families: CISC and RISC. The biggest player in CISC was and still is the Intel x86 architecture (and instruction set). RISC dominated the UNIX world (MIPS6000, Alpha, Sparc and so on). CISC won the battle for the hearts and minds.

Anyway, the popular wisdom when I was a younger developer was that hand-written x86 could often be much faster than C because the way the architecture worked, it had a complexity that benefitted from a human doing it. RISC on the other hand seemed designed for compilers so noone (I knew) wrote say Sparc assembler. I'm sure such people existed but no doubt they've both gone insane and been institutionalized by now.

Instruction sets are an important point even in the same family of processors. Certain Intel processors have extensions like SSE through SSE4. AMD had their own SIMD instructions. The benefit of a programming language like C was someone could write their library so it was optimized for whichever processor you were running on. That was hard work in assembler.

There are still optimizations you can make in assembler that no compiler could make and a well written assembler algoirthm will be as fast or faster than it's C equivalent. The bigger question is: is it worth it?

Ultimately though assembler was a product of its time and was more popular at a time when CPU cycles were expensive. Nowadays a CPU that costs $5-10 to manufacture (Intel Atom) can do pretty much anything anyone could want. The only real reason to write assembler these days is for low level things like some parts of an operating system (even so the vast majority of the Linux kernel is written in C), device drivers, possibly embedded devices (although C tends to dominate there too) and so on. Or just for kicks (which is somewhat masochistic).

How to customize the background/border colors of a grouped table view cell?

Thanks for this super helpful post. In case anyone out there (like me!) wants to just have a completely empty cell background in lieu of customizing it through images/text/other content in IB and cannot figure out how the hell to get rid of the dumb border/padding/background even though you set it to clear in IB... here's the code I used that did the trick!


- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {

    static NSString *cellId = @"cellId";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellId];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"EditTableViewCell" owner:self options:nil];
        cell = cellIBOutlet;
        self.cellIBOutlet = nil;
    }

    cell.backgroundView = [[[UIView alloc] initWithFrame: CGRectZero] autorelease];
    [cell.backgroundView setNeedsDisplay];

    ... any other cell customizations ...

    return cell;
}

Hopefully that'll help someone else! Seems to work like a charm.

Best way to access a control on another form in Windows Forms?

I would handle this in the parent form. You can notify the other form that it needs to modify itself through an event.

Create instance of generic type in Java?

You'll need some kind of abstract factory of one sort or another to pass the buck to:

interface Factory<E> {
    E create();
}

class SomeContainer<E> {
    private final Factory<E> factory;
    SomeContainer(Factory<E> factory) {
        this.factory = factory;
    }
    E createContents() {
        return factory.create();
    }
}

How to iterate over array of objects in Handlebars?

I meant in the template() call..

You just need to pass the results as an object. So instead of calling

var html = template(data);

do

var html = template({apidata: data});

and use {{#each apidata}} in your template code

demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if code that crashed)

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

How to call a function after delay in Kotlin?

You have to import the following two libraries:

import java.util.*
import kotlin.concurrent.schedule

and after that use it in this way:

Timer().schedule(10000){
    //do something
}

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

How to open local file on Jupyter?

To start Jupyter Notebook in Windows:

  • open a Windows cmd (win + R and return cmd)
  • change directory to the desired file path (cd file-path)
  • give command jupyter notebook

You can further navigate from the UI of Jupyter notebook after you launch it (if you are not directly launching the right file.)
OR you can directly drag and drop the file to the cmd, to open the file.

C:\Users\kushalatreya>jupyter notebook "C:\Users\kushalatreya\Downloads\Material\PythonCourseFolder\PythonCourse-DataTypes.ipynb"

When to use <span> instead <p>?

A practical explanation: By default, <p> </p> will add line breaks before and after the enclosed text (so it creates a paragraph). <span> does not do this, that is why it is called inline.

How to vertically center a <span> inside a div?

To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.

What is a "web service" in plain English?

Web services are almost like normal a web page. The difference is that they are formatted to make it very easy for a program to pull data from the page, to the point of probably not using any HTML. They generally also are more reliable as to the consistency of the format, may use a different formal process to define the content such soap or raw xml, and there is often also a descriptor document that formally defines the structure for the data.

In Perl, how can I read an entire file into a string?

You could simply create a sub-routine:

#Get File Contents
sub gfc
{
    open FC, @_[0];
    join '', <FC>;
}

How to add item to the beginning of List<T>?

Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

Counting inversions in an array

In Java Brute force algorithm works faster than piggy backed merge sort algorithm this is because of run time optimization done by Java Dynamic compiler.

For Brute force loop rolling optimization will result in much better results.

Concatenating strings in C, which method is more efficient?

sprintf() is designed to handle far more than just strings, strcat() is specialist. But I suspect that you are sweating the small stuff. C strings are fundamentally inefficient in ways that make the differences between these two proposed methods insignificant. Read "Back to Basics" by Joel Spolsky for the gory details.

This is an instance where C++ generally performs better than C. For heavy weight string handling using std::string is likely to be more efficient and certainly safer.

[edit]

[2nd edit]Corrected code (too many iterations in C string implementation), timings, and conclusion change accordingly

I was surprised at Andrew Bainbridge's comment that std::string was slower, but he did not post complete code for this test case. I modified his (automating the timing) and added a std::string test. The test was on VC++ 2008 (native code) with default "Release" options (i.e. optimised), Athlon dual core, 2.6GHz. Results:

C string handling = 0.023000 seconds
sprintf           = 0.313000 seconds
std::string       = 0.500000 seconds

So here strcat() is faster by far (your milage may vary depending on compiler and options), despite the inherent inefficiency of the C string convention, and supports my original suggestion that sprintf() carries a lot of baggage not required for this purpose. It remains by far the least readable and safe however, so when performance is not critical, has little merit IMO.

I also tested a std::stringstream implementation, which was far slower again, but for complex string formatting still has merit.

Corrected code follows:

#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>

void a(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
    {
        strcpy(both, first);
        strcat(both, " ");
        strcat(both, second);
    }
}

void b(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
        sprintf(both, "%s %s", first, second);
}

void c(char *first, char *second, char *both)
{
    std::string first_s(first) ;
    std::string second_s(second) ;
    std::string both_s(second) ;

    for (int i = 0; i != 1000000; i++)
        both_s = first_s + " " + second_s ;
}

int main(void)
{
    char* first= "First";
    char* second = "Second";
    char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
    clock_t start ;

    start = clock() ;
    a(first, second, both);
    printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    b(first, second, both);
    printf( "sprintf           = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    c(first, second, both);
    printf( "std::string       = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    return 0;
}

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

What's NSLocalizedString equivalent in Swift?

In addition to great extension written here if you are lazy to find and replace old NSLocalizedString you can open find & replace in Xcode and in the find section you can write NSLocalizedString\(\(".*"\), comment: ""\) then in the replace section you need to write $1.localized to change all NSLocalizedString with "blabla".localized in your project.

UIView bottom border?

Or, the most performance-friendly way is to overload drawRect, simply like that:

@interface TPActionSheetButton : UIButton

@property (assign) BOOL drawsTopLine;
@property (assign) BOOL drawsBottomLine;
@property (assign) BOOL drawsRightLine;
@property (assign) BOOL drawsLeftLine;
@property (strong, nonatomic) UIColor * lineColor;

@end

@implementation TPActionSheetButton

- (void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(ctx, 0.5f * [[UIScreen mainScreen] scale]);
    CGFloat red, green, blue, alpha;
    [self.lineColor getRed:&red green:&green blue:&blue alpha:&alpha];
    CGContextSetRGBStrokeColor(ctx, red, green, blue, alpha);

    if(self.drawsTopLine) {
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));
        CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMinY(rect));
        CGContextStrokePath(ctx);
    }
    if(self.drawsBottomLine) {
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));
        CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
        CGContextStrokePath(ctx);
    }
    if(self.drawsLeftLine) {
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMinY(rect));
        CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect));
        CGContextStrokePath(ctx);
    }
    if(self.drawsRightLine) {
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMinY(rect));
        CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
        CGContextStrokePath(ctx);
    }

    [super drawRect:rect];
}

@end

Improve INSERT-per-second performance of SQLite

Avoid sqlite3_clear_bindings(stmt).

The code in the test sets the bindings every time through which should be enough.

The C API intro from the SQLite docs says:

Prior to calling sqlite3_step() for the first time or immediately after sqlite3_reset(), the application can invoke the sqlite3_bind() interfaces to attach values to the parameters. Each call to sqlite3_bind() overrides prior bindings on the same parameter

There is nothing in the docs for sqlite3_clear_bindings saying you must call it in addition to simply setting the bindings.

More detail: Avoid_sqlite3_clear_bindings()

how to make div click-able?

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

Using ADB to capture the screen

Using some of the knowledge from this and a couple of other posts, I found the method that worked the best for me was to:

adb shell 'stty raw; screencap -p'

I have posted a very simple Python script on GitHub that essentially mirrors the screen of a device connected over ADB:

https://github.com/baitisj/android_screen_mirror

Static methods - How to call a method from another method?

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

If you will place your definitions in this order then the code will be compiled

class Ball;

class Player {
public:
    void doSomething(Ball& ball);
private:
};

class Ball {
public:
    Player& PlayerB;
    float ballPosX = 800;
private:

};

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

int main()
{
}

The definition of function doSomething requires the complete definition of class Ball because it access its data member.

In your code example module Player.cpp has no access to the definition of class Ball so the compiler issues an error.

Flutter command not found

For those using a Z-shell resource (.zshrc), navigate to your home directory and open .zprofile, copy and paste this: export PATH=[PATH_TO_FLUTTER_DIRECTORY]/flutter/bin:$PATH

"A referral was returned from the server" exception when accessing AD from C#

Had the same issue and managed to resolve it.

In my case, I had an AD group in the current logon domain with members (users) from a sub domain. The server that I was running the code on could not access the domain controller of the sub domain (the server had never needed to access the sub domain before).

I struggled for a while as my desktop PC could access the domain so everything looked OK in the MMC plugin (Active Directory Users & Computers).

Hope that helps someone else.

difference between iframe, embed and object elements

<iframe>

The iframe element represents a nested browsing context. HTML 5 standard - "The <iframe> element"

Primarily used to include resources from other domains or subdomains but can be used to include content from the same domain as well. The <iframe>'s strength is that the embedded code is 'live' and can communicate with the parent document.

<embed>

Standardised in HTML 5, before that it was a non standard tag, which admittedly was implemented by all major browsers. Behaviour prior to HTML 5 can vary ...

The embed element provides an integration point for an external (typically non-HTML) application or interactive content. (HTML 5 standard - "The <embed> element")

Used to embed content for browser plugins. Exceptions to this is SVG and HTML that are handled differently according to the standard.

The details of what can and can not be done with the embedded content is up to the browser plugin in question. But for SVG you can access the embedded SVG document from the parent with something like:

svg = document.getElementById("parent_id").getSVGDocument();

From inside an embedded SVG or HTML document you can reach the parent with:

parent = window.parent.document;

For embedded HTML there is no way to get at the embedded document from the parent (that I have found).

<object>

The <object> element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. (HTML 5 standard - "The <object> element")

Conclusion

Unless you are embedding SVG or something static you are probably best of using <iframe>. To include SVG use <embed> (if I remember correctly <object> won't let you script†). Honestly I don't know why you would use <object> unless for older browsers or flash (that I don't work with).

† As pointed out in the comments below; scripts in <object> will run but the parent and child contexts can't communicate directly. With <embed> you can get the context of the child from the parent and vice versa. This means they you can use scripts in the parent to manipulate the child etc. That part is not possible with <object> or <iframe> where you would have to set up some other mechanism instead, such as the JavaScript postMessage API.

sum two columns in R

You can use a for loop:

for (i in 1:nrow(df)) {
   df$col3[i] <- df$col1[i] + df$col2[i]
}

How to detect tableView cell touched or clicked in swift

Inherit the tableview delegate and datasource. Implement delegates what you need.

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

And Finally implement this delegate

     func tableView(_ tableView: UITableView, didSelectRowAt  
     indexPath: IndexPath) {
     print("row selected : \(indexPath.row)")
  }

How to reload/refresh an element(image) in jQuery

with one line with no worries about hardcoding the image src into the javascript (thanks to jeerose for the ideas:

$("#myimg").attr("src", $("#myimg").attr("src")+"?timestamp=" + new Date().getTime());

c# - How to get sum of the values from List?

You can use LINQ for this

var list = new List<int>();
var sum = list.Sum();

and for a List of strings like Roy Dictus said you have to convert

list.Sum(str => Convert.ToInt32(str));

Python: json.loads returns items prefixing with 'u'

The u prefix means that those strings are unicode rather than 8-bit strings. The best way to not show the u prefix is to switch to Python 3, where strings are unicode by default. If that's not an option, the str constructor will convert from unicode to 8-bit, so simply loop recursively over the result and convert unicode to str. However, it is probably best just to leave the strings as unicode.

Which programming language for cloud computing?

This is always fascinating. I am not a cloud developer, but based on my research there is nothing significantly different than what many of us have been doing off and on for decades. The server is platform specific. If you want to write platform agnostic code for your server that is fine, but unnecessary based on whoever your cloud server provider is. I think the biggest difference I've seen so far is the concept of providing a large set of services for the front end client to process. the front end, I'm assuming is predominantly web or web app development. As most browsers can handle LAMP vs Microsoft stack well enough, then you are still back to whatever your flavor of the month is. The only difference I truly am seeing from what I did 20 years ago in a highly distributed network environment are higher level protocol (HTTP vs. TCP/UDP). Maybe I am wrong and would welcome the education, but then again I've been doing this a long time and still have not seen anything I would consider revolutionary or significantly different, though languages like Java, C#, Python, Ruby, etc are significantly simpler to program in which is a mixed bag as the bar is lowered for those are are not familiar with writing optimized code. PAAS and SAAS to me seem to be some of the keys in the new technology, but been doing some of this to off and on for 20 years :)

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

If Else If In a Sql Server Function

If yes_ans > no_ans and yes_ans > na_ans  

You're using column names in a statement (outside of a query). If you want variables, you must declare and assign them.

Make child div stretch across width of page

Since position: absolute; and viewport width were no options in my special case, there is another quick solution to solve the problem. The only condition is, that overflow in x-direction is not necessary for your website.

You can define negative margins for your element:

#help_panel {
    margin-left: -9999px;
    margin-right: -9999px;
}

But since we get overflow doing this, we have to avoid overflow in x-direction globally e.g. for body:

body {
    overflow-x: hidden;
}

You can set padding to choose the size of your content.

Note that this solution does not bring 100% width for content, but it is helpful in cases where you need e.g. a background color which has full width with a content still depending on container.

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

Best solution: Goto jboss-as-7.1.1.Final\standalone\deployments folder and delete all existing files....

Run again your problem will be solved

How can I use a for each loop on an array?

A for each loop structure is more designed around the collection object. A For..Each loop requires a variant type or object. Since your "element" variable is being typed as a variant your "do_something" function will need to accept a variant type, or you can modify your loop to something like this:

Public Sub Example()

    Dim sArray(4) As String
    Dim i As Long

    For i = LBound(sArray) To UBound(sArray)
        do_something sArray(i)
    Next i

End Sub

Excel formula to remove space between words in a cell

Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.

find files by extension, *.html under a folder in nodejs

Install

you can install this package walk-sync by

yarn add walk-sync

Usage

const walkSync = require("walk-sync");
const paths = walkSync("./project1/src", {globs: ["**/*.html"]});
console.log(paths);   //all html file path array

Understanding The Modulus Operator %

(This explanation is only for positive numbers since it depends on the language otherwise)

Definition

The Modulus is the remainder of the euclidean division of one number by another. % is called the modulo operation.

For instance, 9 divided by 4 equals 2 but it remains 1. Here, 9 / 4 = 2 and 9 % 4 = 1.

Euclidean Division

In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5).

Calculation

The modulo operation can be calculated using this equation:

a % b = a - floor(a / b) * b
  • floor(a / b) represents the number of times you can divide a by b
  • floor(a / b) * b is the amount that was successfully shared entirely
  • The total (a) minus what was shared equals the remainder of the division

Applied to the last example, this gives:

5 % 7 = 5 - floor(5 / 7) * 7 = 5

Modular Arithmetic

That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7) because it exists k in Z such that 7k - 2 = 5.

You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7 is 3.

How to process POST data in Node.js?

you can extract post parameter without using express.

1: nmp install multiparty

2: import multiparty . as var multiparty = require('multiparty');

3: `

if(req.method ==='POST'){
   var form = new multiparty.Form();
   form.parse(req, function(err, fields, files) {
      console.log(fields['userfile1'][0]);
    });
    }

4: and HTML FORM IS .

<form method=POST enctype=multipart/form-data>
<input type=text name=userfile1><br>
<input type=submit>
</form>

I hope this will work for you. Thanks.

How to print the ld(linker) search path

Mac version: $ ld -v 2, don't know how to get detailed paths. output

Library search paths:
    /usr/lib
    /usr/local/lib
Framework search paths:
    /Library/Frameworks/
    /System/Library/Frameworks/

What is the best way to modify a list in a 'foreach' loop?

LINQ is very effective for juggling with collections.

Your types and structure are unclear to me, but I will try to fit your example to the best of my ability.

From your code it appears that, for each item, you are adding to that item everything from its own 'Enumerable' property. This is very simple:

foreach (var item in Enumerable)
{
    item = item.AddRange(item.Enumerable));
}

As a more general example, let's say we want to iterate a collection and remove items where a certain condition is true. Avoiding foreach, using LINQ:

myCollection = myCollection.Where(item => item.ShouldBeKept);

Add an item based on each existing item? No problem:

myCollection = myCollection.Concat(myCollection.Select(item => new Item(item.SomeProp)));

How to determine the Boost version on a system?

Depending on how you have installed boost and what OS you are running you could also try the following:

dpkg -s libboost-dev | grep 'Version'

How to write a UTF-8 file with Java?

Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:

try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
    // do stuff
}

C# ASP.NET MVC Return to Previous Page

Here is just another option you couold apply for ASP NET MVC.

Normally you shoud use BaseController class for each Controller class.

So inside of it's constructor method do following.

public class BaseController : Controller
{
        public BaseController()
        {
            // get the previous url and store it with view model
            ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
        }
}

And now in ANY view you can do like

<button class="btn btn-success mr-auto" onclick="  window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>

Enjoy!

Case insensitive string as HashMap key

I like using ICU4J’s CaseInsensitiveString wrap of the Map key because it takes care of the hash\equals and issue and it works for unicode\i18n.

HashMap<CaseInsensitiveString, String> caseInsensitiveMap = new HashMap<>();
caseInsensitiveMap.put("tschüß", "bye");
caseInsensitiveMap.containsKey("TSCHÜSS"); # true

How do I see if Wi-Fi is connected on Android?

Try out this method.

public boolean isInternetConnected() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    boolean ret = true;
    if (conMgr != null) {
        NetworkInfo i = conMgr.getActiveNetworkInfo();

        if (i != null) {
            if (!i.isConnected()) {
                ret = false;
            }

            if (!i.isAvailable()) {
                ret = false;
            }
        }

        if (i == null)
            ret = false;
    } else
        ret = false;
    return ret;
}

This method will help to find internet connection available or not.

How to pattern match using regular expression in Scala?

You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.

val Pattern = "([a-cA-C])".r
word.firstLetter match {
   case Pattern(c) => c bound to capture group here
   case _ =>
}

How can I schedule a job to run a SQL query daily?

I made an animated GIF of the steps in the accepted answer. This is from MSSQL Server 2012

Schedule SQL Job

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

Create directory if it does not exist

The following code snippet helps you to create a complete path.

Function GenerateFolder($path) {
    $global:foldPath = $null
    foreach($foldername in $path.split("\")) {
        $global:foldPath += ($foldername+"\")
        if (!(Test-Path $global:foldPath)){
            New-Item -ItemType Directory -Path $global:foldPath
            # Write-Host "$global:foldPath Folder Created Successfully"
        }
    }
}

The above function split the path you passed to the function and will check each folder whether it exists or not. If it does not exist it will create the respective folder until the target/final folder created.

To call the function, use below statement:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"

Getting a union of two arrays in JavaScript

With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:

_x000D_
_x000D_
var a = [34, 35, 45, 48, 49];_x000D_
var b = [48, 55];_x000D_
var union = [...new Set([...a, ...b])];_x000D_
console.log(union);
_x000D_
_x000D_
_x000D_

Little explanation about this line: [...a, ...b] concatenates two arrays, you can use a.concat(b) as well. new Set() create a set out of it and thus your union. And the last [...x] converts it back to an array.

How to install JSON.NET using NuGet?

You can do this a couple of ways.

Via the "Solution Explorer"

  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type "json.net"
  4. Click "Install" and you're done.

Via the "Package Manager Console"

  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
    Install-Package Newtonsoft.Json

For more info on how to use the "Package Manager Console" check out the nuget docs.

Add horizontal scrollbar to html table

//Representation of table
<div class="search-table-outter">
<table class="table table-responsive search-table inner">
</table>
</div>

//Css to make Horizontal Dropdown

<style>

    .search-table{table-layout: auto; margin:40px auto 0px auto; }
    .search-table, td, th {
        border-collapse: collapse;
    }
th{padding:20px 7px; font-size:15px; color:#444;}
td{padding:5px 10px; height:35px;}
    .search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }


</style>

jquery append external html file into my page

Use html instead of append:

$.get("banner.html", function(data){
    $(this).children("div:first").html(data);
});

How to remove default chrome style for select Input?

use simple code for remove default browser style for outline

input { outline: none; }

Git SSH error: "Connect to host: Bad file number"

If SSH is blocked over 22

just update your origin to https

git remote set-url origin https://github.com/ACCOUNT_NAME/REPO_NAME.git

verify that changes were made

git remote -v

How to get value of checked item from CheckedListBox?

Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
     DataRowView castedItem = itemChecked as DataRowView;
     string comapnyName = castedItem["CompanyName"];
     int? id = castedItem["ID"];
}

Last segment of URL in jquery

You can do this with simple paths (w/0) querystrings etc.

Granted probably overly complex and probably not performant, but I wanted to use reduce for the fun of it.

  "/foo/bar/"
    .split(path.sep)
    .filter(x => x !== "")
    .reduce((_, part, i, arr) => {
      if (i == arr.length - 1) return part;
    }, "");
  1. Split the string on path separators.
  2. Filter out empty string path parts (this could happen with trailing slash in path).
  3. Reduce the array of path parts to the last one.

How to change XAMPP apache server port?

Have you tried to access your page by typing "http://localhost:8012" (after restarting the apache)?

AngularJS resource promise

If you're looking to get promise in resource call, you should use

Regions.query().$q.then(function(){ .... })

Update : the promise syntax is changed in current versions which reads

Regions.query().$promise.then(function(){ ..... })

Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.

Manually adding a Userscript to Google Chrome

Share and install userscript with one-click

To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js filename to get on-click installation when you click on Raw and get this page:

Installation page

How to do this ?

  1. Name your gist <filename>.user.js, write your code and click on "Create".
    Make file on gist

  2. In the gist page, click on Raw to get installation page (first screen).
    Raw button

  3. Check the code and install it.

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

Total size of the contents of all the files in a directory

This may help:

ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'

The above command will sum total all the files leaving the directories size.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I've experimented the exact same error. My problem was that the SetUp method I had created was declared as static.

If using eclipse, one could get a good description by clicking above the error and then checking the Failure trace window, just below... That's how I found the real problem!

How do I convert a long to a string in C++?

int main()
{
    long mylong = 123456789;
    string mystring;
    stringstream mystream;
    mystream << mylong;
    mystring = mystream.str();
    cout << mystring << "\n";
    return 0;
}

How to install pandas from pip on windows cmd?

Since both pip nor python commands are not installed along Python in Windows, you will need to use the Windows alternative py, which is included by default when you installed Python. Then you have the option to specify a general or specific version number after the py command.

C:\> py      -m pip install pandas  %= one of Python on the system =%
C:\> py -2   -m pip install pandas  %= one of Python 2 on the system =%
C:\> py -2.7 -m pip install pandas  %= only for Python 2.7 =%
C:\> py -3   -m pip install pandas  %= one of Python 3 on the system =%
C:\> py -3.6 -m pip install pandas  %= only for Python 3.6 =%

Alternatively, in order to get pip to work without py -m part, you will need to add pip to the PATH environment variable.

C:\> setx PATH "%PATH%;C:\<path\to\python\folder>\Scripts"

Now you can run the following command as expected.

C:\> pip install pandas

Troubleshooting:


Problem:

connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Solution:

This is caused by your SSL certificate is unable to verify the host server. You can add pypi.python.org to the trusted host or specify an alternative SSL certificate. For more information, please see this post. (Thanks to Anuj Varshney for suggesting this)

C:\> py -m pip install --trusted-host pypi.python.org pip pandas

Problem:

PermissionError: [WinError 5] Access is denied

Solution:

This is a caused by when you don't permission to modify the Python site-package folders. You can avoid this with one of the following methods:

  • Run Windows Command Prompt as administrator (thanks to DataGirl's suggestion) by:

    1. Windows-Key + R to open run
    2. type in cmd.exe in the search box
    3. CTRL + SHIFT + ENTER
    4. An alternative method for step 1-3 would be to manually locate cmd.exe, right click, then click Run as Administrator.
  • Run pip in user mode by adding --user option when installing with pip. Which typically install the package to the local %APPDATA% Python folder.

C:\> py -m pip install --user pandas
C:\> py -m venv c:\path\to\new\venv
C:\> <path\to\the\new\venv>\Scripts\activate.bat

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I recommended an experimental new attribute CSS I tested on latest browser and it's good:

image-rendering: optimizeSpeed;             /*                     */
image-rendering: -moz-crisp-edges;          /* Firefox             */
image-rendering: -o-crisp-edges;            /* Opera               */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast;         /* CSS3 Proposed       */
-ms-interpolation-mode: nearest-neighbor;   /* IE8+                */

With this the browser will know the algorithm for rendering

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

The easiest is

as @greggo pointed out

string="mystring";
string[:-1]

How do I get a list of all the duplicate items using pandas in python?

sort("ID") does not seem to be working now, seems deprecated as per sort doc, so use sort_values("ID") instead to sort after duplicate filter, as following:

df[df.ID.duplicated(keep=False)].sort_values("ID")

Explicitly select items from a list or tuple

What about this:

from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')

Aligning a float:left div to center?

try it like this:

  <div id="divContainer">
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <br class="clear" />
    </div>

    <style type="text/css">
    #divContainer { margin: 0 auto; width: 800px; }
    .divImageHolder { float:left; }
    .clear { clear:both; }
    </style>

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

How to get the cursor to change to the hand when hovering a <button> tag

All u need is just use one of the attribute of CSS , which is---->

cursor:pointer

just use this property in css , no matter its inline or internal or external

for example(for inline css)

<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>

source of historical stock data

THIS ANSWER IS NO LONGER ACCURATE AS THE YAHOO FEED HAS CEASED TO EXIST

Using Yahoo's CSV approach above you can also get historical data! You can reverse engineer the following example:

http://ichart.finance.yahoo.com/table.csv?s=YHOO&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv

Essentially:

sn = TICKER
a = fromMonth-1
b = fromDay (two digits)
c = fromYear
d = toMonth-1
e = toDay (two digits)
f = toYear
g = d for day, m for month, y for yearly

The complete list of parameters:

a   Ask
a2  Average Daily Volume
a5  Ask Size
b   Bid
b2  Ask (Real-time)
b3  Bid (Real-time)
b4  Book Value
b6  Bid Size
c   Change & Percent Change
c1  Change
c3  Commission
c6  Change (Real-time)
c8  After Hours Change (Real-time)
d   Dividend/Share
d1  Last Trade Date
d2  Trade Date
e   Earnings/Share
e1  Error Indication (returned for symbol changed / invalid)
e7  EPS Estimate Current Year
e8  EPS Estimate Next Year
e9  EPS Estimate Next Quarter
f6  Float Shares
g   Day's Low
h   Day's High
j   52-week Low
k   52-week High
g1  Holdings Gain Percent
g3  Annualized Gain
g4  Holdings Gain
g5  Holdings Gain Percent (Real-time)
g6  Holdings Gain (Real-time)
i   More Info
i5  Order Book (Real-time)
j1  Market Capitalization
j3  Market Cap (Real-time)
j4  EBITDA
j5  Change From 52-week Low
j6  Percent Change From 52-week Low
k1  Last Trade (Real-time) With Time
k2  Change Percent (Real-time)
k3  Last Trade Size
k4  Change From 52-week High
k5  Percent Change From 52-week High
l   Last Trade (With Time)
l1  Last Trade (Price Only)
l2  High Limit
l3  Low Limit
m   Day's Range
m2  Day's Range (Real-time)
m3  50-day Moving Average
m4  200-day Moving Average
m5  Change From 200-day Moving Average
m6  Percent Change From 200-day Moving Average
m7  Change From 50-day Moving Average
m8  Percent Change From 50-day Moving Average
n   Name
n4  Notes
o   Open
p   Previous Close
p1  Price Paid
p2  Change in Percent
p5  Price/Sales
p6  Price/Book
q   Ex-Dividend Date
r   P/E Ratio
r1  Dividend Pay Date
r2  P/E Ratio (Real-time)
r5  PEG Ratio
r6  Price/EPS Estimate Current Year
r7  Price/EPS Estimate Next Year
s   Symbol
s1  Shares Owned
s7  Short Ratio
t1  Last Trade Time
t6  Trade Links
t7  Ticker Trend
t8  1 yr Target Price
v   Volume
v1  Holdings Value
v7  Holdings Value (Real-time)
w   52-week Range
w1  Day's Value Change
w4  Day's Value Change (Real-time)
x   Stock Exchange
y   Dividend Yield

Determine file creation date in Java

As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.

On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;

public class TestFA {
  static void getAttributes(String pathStr) throws IOException {
    Path p = Paths.get(pathStr);
    BasicFileAttributes view
       = Files.getFileAttributeView(p, BasicFileAttributeView.class)
              .readAttributes();
    System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
  }
  public static void main(String[] args) throws IOException {
    for (String s : args) {
        getAttributes(s);
    }
  }
}

Check an integer value is Null in c#

Several things:

Age is not an integer - it is a nullable integer type. They are not the same. See the documentation for Nullable<T> on MSDN for details.

?? is the null coalesce operator, not the ternary operator (actually called the conditional operator).

To check if a nullable type has a value use HasValue, or check directly against null:

if(Age.HasValue)
{
   // Yay, it does!
}

if(Age == null)
{
   // It is null :(
}

Align DIV's to bottom or baseline

Use the CSS display values of table and table-cell:

HTML

<html>
<body>

  <div class="valign bottom">
    <div>

      <div>my bottom aligned div 1</div>
      <div>my bottom aligned div 2</div>
      <div>my bottom aligned div 3</div>

    </div>
  </div>

</body>
</html>

CSS

html,body {
    width: 100%;
    height: 100%;
}
.valign {
    display: table;
    width: 100%;
    height: 100%;
}
.valign > div {
    display: table-cell;
    width: 100%;
    height: 100%;
}
.valign.bottom > div {
    vertical-align: bottom;
}

I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit

The demo also has an example how to vertically center align using the same technique.

EOL conversion in notepad ++

That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".

screenshot of the option for even quicker finding (or different language versions)

You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.

Jenkins: Can comments be added to a Jenkinsfile?

Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc to process your Jenkinsfile (s).

First, groovydoc chokes on files without extensions with the wonderful error

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
    at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
    at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
    ... 6 more

... and second, as far as I can tell Javadoc-style commments at the start of a groovy script are ignored. So even if you copy/rename your Jenkinsfile to Jenkinsfile.groovy, you won't get much useful output.

I want to be able to use a

/**
 * Document my Jenkinsfile's overall purpose here
 */

comment at the start of my Jenkinsfile. No such luck (yet).

groovydoc will process classes and methods defined in your Jenkinsfile if you pass -private to the command, though.

How do I escape a reserved word in Oracle?

you have to rename the column to an other name because TABLE is reserved by Oracle.

You can see all reserved words of Oracle in the oracle view V$RESERVED_WORDS.

How do I delete a Git branch locally and remotely?

I added the following aliases to my .gitconfig file. This allows me to delete branches with or without specifying the branch name. Branch name is defaulted to the current branch if no argument is passed in.

[alias]
    branch-name = rev-parse --abbrev-ref HEAD     

    rm-remote-branch = !"f() { branch=${1-$(git branch-name)}; git push origin :$branch; }; f"
    rm-local-branch = !"f() { branch=${1-$(git branch-name)}; git checkout master; git branch -d $branch; }; f"
    rm-branch-fully = !"f() { branch=${1-$(git branch-name)}; git rm-local-branch $branch; git rm-remote-branch $branch; }; f"

XML Schema How to Restrict Attribute by Enumeration

New answer to old question

None of the existing answers to this old question address the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD. The fix is to use xs:simpleContent first. Details follow...


Your XML,

<price currency="euros">20000.00</price>

will be valid against either of the following corrected XSDs:

Locally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Globally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="currencyType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="pounds" />
      <xs:enumeration value="euros" />
      <xs:enumeration value="dollars" />
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency" type="currencyType"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Notes

  • As commented by @Paul, these do change the content type of price from xs:string to xs:decimal, but this is not strictly necessary and was not the real problem.
  • As answered by @user998692, you could separate out the definition of currency, and you could change to xs:decimal, but this too was not the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD; xs:simpleContent is needed first.

A related matter (that wasn't asked but may have confused other answers):

How could price be restricted given that it has an attribute?

In this case, a separate, global definition of priceType would be needed; it is not possible to do this with only local type definitions.

How to restrict element content when element has attribute

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="priceType">  
    <xs:restriction base="xs:decimal">  
      <xs:minInclusive value="0.00"/>  
      <xs:maxInclusive value="99999.99"/>  
    </xs:restriction>  
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="priceType">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

How do you align left / right a div without using float?

you could use things like display: inline-block but I think you would need to set up another div to move it over, if there is nothing going to the left of the button you could use margins to move it into place.

Alternatively but not a good solution, you could position tags; put the encompassing div as position: relative and then the div of the button as position: absolute; right: 0, but like I said this is probably not the best solution

HTML

<div class="parent">
  <div>Left Div</div>
  <div class="right">Right Div</div>
</div>

CSS

.parent {
  position: relative;
}
.right {
    position: absolute;
    right: 0;
}

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

I wrote this a few years ago (run it with administrator rights):

<#
.SYNOPSIS
    Change the registry key in order that double-clicking on a file with .PS1 extension
    start its execution with PowerShell.
.DESCRIPTION
    This operation bring (partly) .PS1 files to the level of .VBS as far as execution
    through Explorer.exe is concern.
    This operation is not advised by Microsoft.
.NOTES
    File Name   : ModifyExplorer.ps1
    Author      : J.P. Blanc - [email protected]
    Prerequisite: PowerShell V2 on Vista and later versions.
    Copyright 2010 - Jean Paul Blanc/Silogix
.LINK
    Script posted on:
    http://www.silogix.fr
.EXAMPLE
    PS C:\silogix> Set-PowAsDefault -On
    Call Powershell for .PS1 files.
    Done!
.EXAMPLE
    PS C:\silogix> Set-PowAsDefault
    Tries to go back
    Done!
#>
function Set-PowAsDefault
{
  [CmdletBinding()]
  Param
  (
    [Parameter(mandatory=$false, ValueFromPipeline=$false)]
    [Alias("Active")]
    [switch]
    [bool]$On
  )

  begin
  {
    if ($On.IsPresent)
    {
      Write-Host "Call PowerShell for .PS1 files."
    }
    else
    {
      Write-Host "Try to go back."
    }
  }

  Process
  {
    # Text Menu
    [string]$TexteMenu = "Go inside PowerShell"

    # Text of the program to create
    [string] $TexteCommande = "%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command ""&'%1'"""

    # Key to create
    [String] $clefAModifier = "HKLM:\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\Open\Command"

    try
    {
      $oldCmdKey = $null
      $oldCmdKey = Get-Item $clefAModifier -ErrorAction SilentlyContinue
      $oldCmdValue = $oldCmdKey.getvalue("")

      if ($oldCmdValue -ne $null)
      {
        if ($On.IsPresent)
        {
          $slxOldValue = $null
          $slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
          if ($slxOldValue -eq $null)
          {
            New-ItemProperty $clefAModifier -Name "slxOldValue" -Value $oldCmdValue  -PropertyType "String" | Out-Null
            New-ItemProperty $clefAModifier -Name "(default)" -Value $TexteCommande  -PropertyType "ExpandString" | Out-Null
            Write-Host "Done !"
          }
          else
          {
            Write-Host "Already done!"
          }
        }
        else
        {
          $slxOldValue = $null
          $slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
          if ($slxOldValue -ne $null)
          {
            New-ItemProperty $clefAModifier -Name "(default)" -Value $slxOldValue."slxOldValue"  -PropertyType "String" | Out-Null
            Remove-ItemProperty $clefAModifier -Name "slxOldValue"
            Write-Host "Done!"
          }
          else
          {
            Write-Host "No former value!"
          }
        }
      }
    }
    catch
    {
      $_.exception.message
    }
  }
  end {}
}

Check that a input to UITextField is numeric only

I wanted a text field that only allowed integers. Here's what I ended up with (using info from here and elsewhere):

Create integer number formatter (in UIApplicationDelegate so it can be reused):

@property (nonatomic, retain) NSNumberFormatter *integerNumberFormatter;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Create and configure an NSNumberFormatter for integers
    integerNumberFormatter = [[NSNumberFormatter alloc] init];
    [integerNumberFormatter setMaximumFractionDigits:0];

    return YES;
}

Use filter in UITextFieldDelegate:

@interface MyTableViewController : UITableViewController <UITextFieldDelegate> {
    ictAppDelegate *appDelegate;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Make sure the proposed string is a number
    NSNumberFormatter *inf = [appDelegate integerNumberFormatter];
    NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSNumber *proposedNumber = [inf numberFromString:proposedString];
    if (proposedNumber) {
        // Make sure the proposed number is an integer
        NSString *integerString = [inf stringFromNumber:proposedNumber];
        if ([integerString isEqualToString:proposedString]) {
            // proposed string is an integer
            return YES;
        }
    }

    // Warn the user we're rejecting the change
    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
    return NO;
}

What are some examples of commonly used practices for naming git branches?

My personal preference is to delete the branch name after I’m done with a topic branch.

Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.

The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.

That makes the output of git branch more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.

Batch file script to zip files

I know its too late but if you still wanna try

for /d %%X in (*) do (for /d %%a in (%%X) do ( "C:\Program Files\7-Zip\7z.exe" a -tzip "%%X.zip" ".\%%a\" ))

here * is the current folder. for more options try this link

Difference between Return and Break statements

No offence, but none of the other answers (so far) has it quite right.

break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block.

return is used the terminate a method (and possibly return a value).

A return within any loop or block will of course also immediately terminate that loop/block.

C# Sort and OrderBy comparison

Why not measure it:

class Program
{
    class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, true);
        }
    }

    class Person
    {
        public Person(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
    }

    static void Main()
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person("P005", "Janson"));
        persons.Add(new Person("P002", "Aravind"));
        persons.Add(new Person("P007", "Kazhal"));

        Sort(persons);
        OrderBy(persons);

        const int COUNT = 1000000;
        Stopwatch watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            Sort(persons);
        }
        watch.Stop();
        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            OrderBy(persons);
        }
        watch.Stop();
        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
    }

    static void Sort(List<Person> list)
    {
        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
    }

    static void OrderBy(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
    }
}

On my computer when compiled in Release mode this program prints:

Sort: 1162ms
OrderBy: 1269ms

UPDATE:

As suggested by @Stefan here are the results of sorting a big list fewer times:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}

Sort(persons);
OrderBy(persons);

const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);

Prints:

Sort: 8965ms
OrderBy: 8460ms

In this scenario it looks like OrderBy performs better.


UPDATE2:

And using random names:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}

Where:

private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
    var sb = new StringBuilder(size);
    int start = (lowerCase) ? 97 : 65;
    for (int i = 0; i < size; i++)
    {
        sb.Append((char)(26 * randomSeed.NextDouble() + start));
    }
    return sb.ToString();
}

Yields:

Sort: 8968ms
OrderBy: 8728ms

Still OrderBy is faster

How to add calendar events in Android?

Try this ,

   Calendar beginTime = Calendar.getInstance();
    beginTime.set(yearInt, monthInt - 1, dayInt, 7, 30);



    ContentValues l_event = new ContentValues();
    l_event.put("calendar_id", CalIds[0]);
    l_event.put("title", "event");
    l_event.put("description",  "This is test event");
    l_event.put("eventLocation", "School");
    l_event.put("dtstart", beginTime.getTimeInMillis());
    l_event.put("dtend", beginTime.getTimeInMillis());
    l_event.put("allDay", 0);
    l_event.put("rrule", "FREQ=YEARLY");
    // status: 0~ tentative; 1~ confirmed; 2~ canceled
    // l_event.put("eventStatus", 1);

    l_event.put("eventTimezone", "India");
    Uri l_eventUri;
    if (Build.VERSION.SDK_INT >= 8) {
        l_eventUri = Uri.parse("content://com.android.calendar/events");
    } else {
        l_eventUri = Uri.parse("content://calendar/events");
    }
    Uri l_uri = MainActivity.this.getContentResolver()
            .insert(l_eventUri, l_event);

Cannot use object of type stdClass as array?

Use the second parameter of json_decode to make it return an array:

$result = json_decode($data, true);

Converting LastLogon to DateTime format

DateTime.FromFileTime should do the trick:

PS C:\> [datetime]::FromFileTime(129948127853609000)

Monday, October 15, 2012 3:13:05 PM

Then depending on how you want to format it, check out standard and custom datetime format strings.

PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('d MMMM')
15 October
PS C:\> [datetime]::FromFileTime(129948127853609000).ToString('g')
10/15/2012 3:13 PM

If you want to integrate this into your one-liner, change your select statement to this:

... | Select Name, manager, @{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}} | ...

Safe Area of Xcode 9

enter image description here

  • Earlier in iOS 7.0–11.0 <Deprecated> UIKit uses the topLayoutGuide & bottomLayoutGuide which is UIView property
  • iOS11+ uses safeAreaLayoutGuide which is also UIView property

  • Enable Safe Area Layout Guide check box from file inspector.

  • Safe areas help you place your views within the visible portion of the overall interface.

  • In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.

  • safeAreaLayoutGuide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor viewss.
  • Use safe areas as an aid to laying out your content like UIButton etc.

  • When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.

  • Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.

  • The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones

  • Height of home indicator container is 34 points.

  • Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.

enter image description here

You can set constraints with respective of self.view.safeAreaLayoutGuide as-

ObjC:

  self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
    UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
    [self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
    [self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
    [self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
    [self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;

Swift:

   demoView.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
            demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
        } else {
            NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
        }

enter image description here

enter image description here

enter image description here

How to sort a NSArray alphabetically?

The simplest approach is, to provide a sort selector (Apple's documentation for details)

Objective-C

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Swift

let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:")
let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor])

Apple provides several selectors for alphabetic sorting:

  • compare:
  • caseInsensitiveCompare:
  • localizedCompare:
  • localizedCaseInsensitiveCompare:
  • localizedStandardCompare:

Swift

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
students.sort()
print(students)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

Reference

HtmlSpecialChars equivalent in Javascript?

String.prototype.escapeHTML = function() {
        return this.replace(/&/g, "&amp;")
                   .replace(/</g, "&lt;")
                   .replace(/>/g, "&gt;")
                   .replace(/"/g, "&quot;")
                   .replace(/'/g, "&#039;");
    }

sample :

var toto = "test<br>";
alert(toto.escapeHTML());

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

jQuery disable/enable submit button

take look at this snippet from my project

 $("input[type="submit"]", "#letter-form").on("click",
        function(e) {
             e.preventDefault();


$.post($("#letter-form").attr('action'), $("#letter-form").serialize(),
                 function(response) {// your response from form submit
                    if (response.result === 'Redirect') {
                        window.location = response.url;
                    } else {
                        Message(response.saveChangesResult, response.operation, response.data);
                    }
});
$(this).attr('disabled', 'disabled'); //this is what you want

so just disabled the button after your operation executed

$(this).attr('disabled', 'disabled');

How to replace captured groups only?

A little improvement to Matthew's answer could be a lookahead instead of the last capturing group:

.replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!");

Or you could split on the decimal and join with your new id like this:

.split(/\d+/).join("!NEW_ID!");

Example/Benchmark here: https://codepen.io/jogai/full/oyNXBX

get client time zone from browser

I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):

var ClientTZ = {
    UTCoffset:  0,          // Browser time offset from UTC in minutes
    UTCoffsetT: '+0000S',   // Browser time offset from UTC in '±hhmmD' form
    hasDST:     false,      // Browser time observes DST

    // Determine browser's timezone and DST
    getBrowserTZ: function () {
        var self = ClientTZ;

        // Determine UTC time offset
        var now = new Date();
        var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0);    // Jan
        var diff1 = -date1.getTimezoneOffset();
        self.UTCoffset = diff1;

        // Determine DST use
        var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0);    // Jun
        var diff2 = -date2.getTimezoneOffset();
        if (diff1 != diff2) {
            self.hasDST = true;
            if (diff1 - diff2 >= 0)
                self.UTCoffset = diff2;     // East of GMT
        }

        // Convert UTC offset to ±hhmmD form
        diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
        var hr = Math.floor(diff2);
        var min = diff2 - hr;
        diff2 = hr * 100 + min * 60;
        self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');

        return self.UTCoffset;
    }
};

// Onload
ClientTZ.getBrowserTZ();

Upon loading, the ClientTZ.getBrowserTZ() function is executed, which sets:

  • ClientTZ.UTCoffset to the browser time offset from UTC in minutes (e.g., CST is -360 minutes, which is -6.0 hours from UTC);
  • ClientTZ.UTCoffsetT to the offset in the form '±hhmmD' (e.g., '-0600D'), where the suffix is D for DST and S for standard (non-DST);
  • ClientTZ.hasDST (to true or false).

The ClientTZ.UTCoffset is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).

The intent behind ClientTZ.UTCoffsetT is to use it as a key into a table of timezones (not provided here), such as for a drop-down <select> list.

Should I use past or present tense in git commit messages?

Your project should almost always use the past tense. In any case, the project should always use the same tense for consistency and clarity.

I understand some of the other arguments arguing to use the present tense, but they usually don't apply. The following bullet points are common arguments for writing in the present tense, and my response.

  • Writing in the present tense tells someone what applying the commit will do, rather than what you did.

This is the most correct reason one would want to use the present tense, but only with the right style of project. This manner of thinking considers all commits as optional improvements or features, and you are free to decide which commits to keep and which to reject in your particular repository.

This argument works if you are dealing with a truly distributed project. If you are dealing with a distributed project, you are probably working on an open source project. And it is probably a very large project if it is really distributed. In fact, it's probably either the Linux kernel or Git. Since Linux is likely what caused Git to spread and gain in popularity, it's easy to understand why people would consider its style the authority. Yes, the style makes sense with those two projects. Or, in general, it works with large, open source, distributed projects.

That being said, most projects in source control do not work like this. It is usually incorrect for most repositories. It's a modern way of thinking about a commits: Subversion (SVN) and CVS repositories could barely support this style of repository check-ins. Usually an integration branch handled filtering bad check-ins, but those generally weren't considered "optional" or "nice-to-have features".

In most scenarios, when you are making commits to a source repository, you are writing a journal entry which describes what changed with this update, to make it easier for others in the future to understand why a change was made. It generally isn't an optional change - other people in the project are required to either merge or rebase on it. You don't write a diary entry such as "Dear diary, today I meet a boy and he says hello to me.", but instead you write "I met a boy and he said hello to me."

Finally, for such non-distributed projects, 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository.

  • Consistency. That's how it is in many projects (including git itself). Also git tools that generate commits (like git merge or git revert) do it.

No, I guarantee you that the majority of projects ever logged in a version control system have had their history in the past tense (I don't have references, but it's probably right, considering the present tense argument is new since Git). "Revision" messages or commit messages in the present tense only started making sense in truly distributed projects - see the first point above.

  • People not only read history to know "what happened to this codebase", but also to answer questions like "what happens when I cherry-pick this commit", or "what kind of new things will happen to my code base because of these commits I may or may not merge in the future".

See the first point. 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository. 99.99% beats 0.01%.

  • It's usually shorter

I've never seen a good argument that says use improper tense/grammar because it's shorter. You'll probably only save 3 characters on average for a standard 50 character message. That being said, the present tense on average will probably be a few characters shorter.

  • You can name commits more consistently with titles of tickets in your issue/feature tracker (which don't use past tense, although sometimes future)

Tickets are written as either something that is currently happening (e.g. the app is showing the wrong behavior when I click this button), or something that needs to be done in the future (e.g. the text will need a review by the editor).

History (i.e. commit messages) is written as something that was done in the past (e.g. the problem was fixed).

Windows equivalent of linux cksum command

Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/

Check whether a value exists in JSON object

Below function can be used to check for a value in any level in a JSON

function _isContains(json, value) {
    let contains = false;
    Object.keys(json).some(key => {
        contains = typeof json[key] === 'object' ? _isContains(json[key], value) : json[key] === value;
         return contains;
    });
    return contains;
 }

then to check if JSON contains the value

_isContains(JSONObject, "dog")

See this fiddle: https://jsfiddle.net/ponmudi/uykaacLw/

Most of the answers mentioned here compares by 'name' key. But no need to care about the key, can just checks if JSON contains the given value. So that the function can be used to find any value irrespective of the key.

Setting dynamic scope variables in AngularJs - scope.<some_string>

The solution I have found is to use $parse.

"Converts Angular expression into a function."

If anyone has a better one please add a new answer to the question!

Here is the example:

var the_string = 'life.meaning';

// Get the model
var model = $parse(the_string);

// Assigns a value to it
model.assign($scope, 42);

// Apply it to the scope
// $scope.$apply(); <- According to comments, this is no longer needed

console.log($scope.life.meaning);  // logs 42

Change remote repository credentials (authentication) on Intellij IDEA 14

I needed to change my user name and password in Intellij Did it by

preferences -> version control -> GitHub

There you can change user name and password.

iFrame Height Auto (CSS)

hjpotter92

Add this to your section:

<script>
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

And change your iframe to this:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

It is posted Here

It does however use javascript, but it is simple and easy to use code that will fix your problem.

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

How do I insert datetime value into a SQLite database?

Read This: 1.2 Date and Time Datatype best data type to store date and time is:

TEXT best format is: yyyy-MM-dd HH:mm:ss

Then read this page; this is best explain about date and time in SQLite. I hope this help you

How can I read user input from the console?

a = double.Parse(Console.ReadLine());

Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.

Edit:

To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.

If you'd like to perform some sort of error checking, simply do this:

if ( double.TryParse(Console.ReadLine(), out a) ) {
  Console.Writeline("Sonuç "+ a * Math.PI;); 
}
else {
  Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}

Thanks to Öyvind and abatischev for helping me refine my answer.

Getting a list of files in a directory with a glob

You need to roll your own method to eliminate the files you don't want.

This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.

Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).

This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.

#import "Foundation/Foundation.h"
#import "RegexKit/RegexKit.h"

@interface MTFileMatcher : NSObject 
{
}
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease];
    [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]];

    [pool drain];
    return 0;
}

@implementation MTFileMatcher
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
{
    NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex];
    NSEnumerator* itr = [filesAtPath objectEnumerator];
    NSString* obj;
    while (obj = [itr nextObject])
    {
        NSLog(obj);
    }
}
@end

Numbering rows within groups in a data frame

Here is a small improvement trick that allows sort 'val' inside the groups:

# 1. Data set
set.seed(100)
df <- data.frame(
  cat = c(rep("aaa", 5), rep("ccc", 5), rep("bbb", 5)), 
  val = runif(15))             

# 2. 'dplyr' approach
df %>% 
  arrange(cat, val) %>% 
  group_by(cat) %>% 
  mutate(id = row_number())

How do I display the value of a Django form field in a template?

I wanted to display the value of a formset field. I concluded this solution, which should work for normal forms too:

{% if form.email.data %} {{ form.email.data }}
{% else %} {{ form.initial.email }} 
{% endif %}

The above solutions didn't worked very well for me, and I doubt they would work in case of prefixed forms (such as wizards and formsets). The solutions using {{ form.data.email }} can't work, because it is a dictionary lookup, and with prefixed forms your field name would look something like '1-email' (wizard and prefixed form) or 'form-1-email' (formset), and the minus sign (-) are not allowed in dotted template lookup expressions.

{{form.field_name.value}} is Django 1.3+ only.

Swift Open Link in Safari

Swift 5

if let url = URL(string: "https://www.google.com") {
    UIApplication.shared.open(url)
}

How do I get class name in PHP?

<?php
namespace CMS;
class Model {
  const _class = __CLASS__;
}

echo Model::_class; // will return 'CMS\Model'

for older than PHP 5.5

How to delete all files and folders in a directory?

The following example shows how you can do that. It first creates some directories and a file and then removes them via Directory.Delete(topPath, true);:

    static void Main(string[] args)
    {
        string topPath = @"C:\NewDirectory";
        string subPath = @"C:\NewDirectory\NewSubDirectory";

        try
        {
            Directory.CreateDirectory(subPath);

            using (StreamWriter writer = File.CreateText(subPath + @"\example.txt"))
            {
                writer.WriteLine("content added");
            }

            Directory.Delete(topPath, true);

            bool directoryExists = Directory.Exists(topPath);

            Console.WriteLine("top-level directory exists: " + directoryExists);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.Message);
        }
    }

It is taken from https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx.

Write string to text file and ensure it always overwrites the existing content.

Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.

How to use the IEqualityComparer

Just code, with implementation of GetHashCode and NULL validation:

public class Class_reglementComparer : IEqualityComparer<Class_reglement>
{
    public bool Equals(Class_reglement x, Class_reglement y)
    {
        if (x is null || y is null))
            return false;

        return x.Numf == y.Numf;
    }

    public int GetHashCode(Class_reglement product)
    {
        //Check whether the object is null 
        if (product is null) return 0;

        //Get hash code for the Numf field if it is not null. 
        int hashNumf = product.hashNumf == null ? 0 : product.hashNumf.GetHashCode();

        return hashNumf;
    }
}

Example: list of Class_reglement distinct by Numf

List<Class_reglement> items = items.Distinct(new Class_reglementComparer());

scp with port number specified

I'm using different ports then standard and copy files between files like this:

scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine

This is only for occasional use, if it repeats itself based on a schedule you should use rsync and cron job to do it.

How to push elements in JSON from javascript array

If you want to stick with the way you're populating the values array, you can then assign this array like so:

BODY.values = values;

after the loop.

It should look like this:

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY.values = values;
alert(BODY);

JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

INNER JOIN ON vs WHERE clause

Applying conditional statements in ON / WHERE

Here I have explained the logical query processing steps.


Reference: Inside Microsoft® SQL Server™ 2005 T-SQL Querying
Publisher: Microsoft Press
Pub Date: March 07, 2006
Print ISBN-10: 0-7356-2313-9
Print ISBN-13: 978-0-7356-2313-2
Pages: 640

Inside Microsoft® SQL Server™ 2005 T-SQL Querying

(8)  SELECT (9) DISTINCT (11) TOP <top_specification> <select_list>
(1)  FROM <left_table>
(3)       <join_type> JOIN <right_table>
(2)       ON <join_condition>
(4)  WHERE <where_condition>
(5)  GROUP BY <group_by_list>
(6)  WITH {CUBE | ROLLUP}
(7)  HAVING <having_condition>
(10) ORDER BY <order_by_list>

The first noticeable aspect of SQL that is different than other programming languages is the order in which the code is processed. In most programming languages, the code is processed in the order in which it is written. In SQL, the first clause that is processed is the FROM clause, while the SELECT clause, which appears first, is processed almost last.

Each step generates a virtual table that is used as the input to the following step. These virtual tables are not available to the caller (client application or outer query). Only the table generated by the final step is returned to the caller. If a certain clause is not specified in a query, the corresponding step is simply skipped.

Brief Description of Logical Query Processing Phases

Don't worry too much if the description of the steps doesn't seem to make much sense for now. These are provided as a reference. Sections that come after the scenario example will cover the steps in much more detail.

  1. FROM: A Cartesian product (cross join) is performed between the first two tables in the FROM clause, and as a result, virtual table VT1 is generated.

  2. ON: The ON filter is applied to VT1. Only rows for which the <join_condition> is TRUE are inserted to VT2.

  3. OUTER (join): If an OUTER JOIN is specified (as opposed to a CROSS JOIN or an INNER JOIN), rows from the preserved table or tables for which a match was not found are added to the rows from VT2 as outer rows, generating VT3. If more than two tables appear in the FROM clause, steps 1 through 3 are applied repeatedly between the result of the last join and the next table in the FROM clause until all tables are processed.

  4. WHERE: The WHERE filter is applied to VT3. Only rows for which the <where_condition> is TRUE are inserted to VT4.

  5. GROUP BY: The rows from VT4 are arranged in groups based on the column list specified in the GROUP BY clause. VT5 is generated.

  6. CUBE | ROLLUP: Supergroups (groups of groups) are added to the rows from VT5, generating VT6.

  7. HAVING: The HAVING filter is applied to VT6. Only groups for which the <having_condition> is TRUE are inserted to VT7.

  8. SELECT: The SELECT list is processed, generating VT8.

  9. DISTINCT: Duplicate rows are removed from VT8. VT9 is generated.

  10. ORDER BY: The rows from VT9 are sorted according to the column list specified in the ORDER BY clause. A cursor is generated (VC10).

  11. TOP: The specified number or percentage of rows is selected from the beginning of VC10. Table VT11 is generated and returned to the caller.



Therefore, (INNER JOIN) ON will filter the data (the data count of VT will be reduced here itself) before applying the WHERE clause. The subsequent join conditions will be executed with filtered data which improves performance. After that, only the WHERE condition will apply filter conditions.

(Applying conditional statements in ON / WHERE will not make much difference in few cases. This depends on how many tables you have joined and the number of rows available in each join tables)

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

Convert Text to Uppercase while typing in Text box

I use to do this thing (Code Behind) ASP.NET using VB.NET:

1) Turn AutoPostBack = True in properties of said Textbox

2) Code for Textbox (Event : TextChanged) Me.TextBox1.Text = Me.TextBox1.Text.ToUpper

3) Observation After entering the string variables in TextBox1, when user leaves TextBox1, AutoPostBack fires the code when Text was changed during "TextChanged" event.

Get domain name from given url

try this one : java.net.URL;
JOptionPane.showMessageDialog(null, getDomainName(new URL("https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains")));

public String getDomainName(URL url){
String strDomain;
String[] strhost = url.getHost().split(Pattern.quote("."));
String[] strTLD = {"com","org","net","int","edu","gov","mil","arpa"};

if(Arrays.asList(strTLD).indexOf(strhost[strhost.length-1])>=0)
    strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else if(strhost.length>2)
    strDomain = strhost[strhost.length-3]+"."+strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else
    strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
return strDomain;}

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If your jar file already has an absolute pathname as shown, it is particularly easy:

cd /where/you/want/it; jar xf /path/to/jarfile.jar

That is, you have the shell executed by Python change directory for you and then run the extraction.

If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar can find it after the change of directory.

The only issues left to worry about are things like blanks in the path names.

How can I get the actual video URL of a YouTube live stream?

You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk

First, get the formats of the video:

?  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
137          mp4        1920x1080  DASH video 4347k , avc1.640028, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k
96           mp4        1080p      HLS , h264, aac  @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam

In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f to pass in the format you would like to watch, and -g to get that stream's URL:

?  ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8

These are your HLS m3u8 playlists, one for each camera associated with the live stream.

Without youtube-dl, your flow might look like this:

Take your video id and make a GET request to the get_video_info endpoint:

HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en

In the response, the hlsvp value will be the link to the m3u8 HLS playlist:

https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8

Get properties and values from unknown object

void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

401 Unauthorized: Access is denied due to invalid credentials

In my case, what made it work was changing the Anonymous User identity from Specific user (IUSR) to Application Pool Identity. Weird enought because other sites are using the specific user IUSR and work fine.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";

    if (controller == "Webmaster")
        cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
    else
        cLayout = "~/Views/Shared/_Layout.cshtml";

    Layout = cLayout;
}

Read Complete Article here "How to Render different Layout in ASP.NET MVC"

Mapping over values in a python dictionary

There is no such function; the easiest way to do this is to use a dict comprehension:

my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

In python 2.7, use the .iteritems() method instead of .items() to save memory. The dict comprehension syntax wasn't introduced until python 2.7.

Note that there is no such method on lists either; you'd have to use a list comprehension or the map() function.

As such, you could use the map() function for processing your dict as well:

my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))

but that's not that readable, really.

Error: Local workspace file ('angular.json') could not be found

For me, the issue was that I have an angular project folder inside a rails project folder, and I ran all the angular update commands in the rails parent folder rather than the actual angular folder.

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

Google Colab: how to read data from my google drive?

Thanks for the great answers! Fastest way to get a few one-off files to Colab from Google drive: Load the Drive helper and mount

from google.colab import drive

This will prompt for authorization.

drive.mount('/content/drive')

Open the link in a new tab-> you will get a code - copy that back into the prompt you now have access to google drive check:

!ls "/content/drive/My Drive"

then copy file(s) as needed:

!cp "/content/drive/My Drive/xy.py" "xy.py"

confirm that files were copied:

!ls

What is the best way to initialize a JavaScript Date to midnight?

In case you already have d3.js as a dependency in your project, or don't mind bringing it in, d3-time (d3.js library is modular as of v4.0.0) has got Intervals.

They might prove useful when setting dates to "default" values, e.g. midnight, 0.00 seconds, the first of the month, etc.

var d = new Date(); // Wed Aug 02 2017 15:01:07 GMT+0200 (CEST)
d3.timeHour(d) // Wed Aug 02 2017 00:00:00 GMT+0200 (CEST)
d3.timeMonth(d) // Tue Aug 01 2017 00:00:00 GMT+0200 (CEST)

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

How to run Spyder in virtual environment?

The above answers are correct but I calling spyder within my virtualenv would still use my PATH to look up the version of spyder in my default anaconda env. I found this answer which gave the following workaround:

source activate my_env            # activate your target env with spyder installed
conda info -e                     # look up the directory of your conda env
find /path/to/my/env -name spyder # search for the spyder executable in your env
/path/to/my/env/then/to/spyder    # run that executable directly

I chose this over modifying PATH or adding a link to the executable at a higher priority in PATH since I felt this was less likely to break other programs. However, I did add an alias to the executable in ~/.bash_aliases.

Display animated GIF in iOS

FLAnimatedImage is a performant open source animated GIF engine for iOS:

  • Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers
  • Honors variable frame delays
  • Behaves gracefully under memory pressure
  • Eliminates delays or blocking during the first playback loop
  • Interprets the frame delays of fast GIFs the same way modern browsers do

It's a well-tested component that I wrote to power all GIFs in Flipboard.

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

LINKS ARE TRICKY

Consider the tricks that <a href> knows by default but javascript linking won't do for you. On a decent website, anything that wants to behave as a link should implement these features one way or another. Namely:

  • Ctrl+Click: opens link in new tab
    You can simulate this by using a window.open() with no position/size argument
  • Shift+Click: opens link in new window
    You can simulate this by window.open() with size and/or position specified
  • Alt+Click: download target
    People rarely use this one, but if you insist to simulate it, you'll need to write a special script on server side that responds with the proper download headers.

EASY WAY OUT

Now if you don't want to simulate all that behaviour, I suggest to use <a href> and style it like a button, since the button itself is roughly a shape and a hover effect. I think if it's not semantically important to only have "the button and nothing else", <a href> is the way of the samurai. And if you worry about semantics and readability, you can also replace the button element when your document is ready(). It's clear and safe.

What are the minimum margins most printers can handle?

As a general rule of thumb, I use 1 cm margins when producing pdfs. I work in the geospatial industry and produce pdf maps that reference a specific geographic scale. Therefore, I do not have the option to 'fit document to printable area,' because this would make the reference scale inaccurate. You must also realize that when you fit to printable area, you are fitting your already existing margins inside the printer margins, so you end up with double margins. Make your margins the right size and your documents will print perfectly. Many modern printers can print with margins less than 3 mm, so 1 cm as a general rule should be sufficient. However, if it is a high profile job, get the specs of the printer you will be printing with and ensure that your margins are adequate. All you need is the brand and model number and you can find spec sheets through a google search.

How to pass a single object[] to a params object[]

new[] { (object) 0, (object) null, (object) false }

How to Update a Component without refreshing full page - Angular

To refresh the component at regular intervals I found this the best method. In the ngOnInit method setTimeOut function

ngOnInit(): void {
  setTimeout(() => { this.ngOnInit() }, 1000 * 10)
}
//10 is the number of seconds

Uploading images using Node.js, Express, and Mongoose

Again if you don't want to use bodyParser, the following works:

var express = require('express');
var http = require('http');
var app = express();

app.use(express.static('./public'));


app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.multipart({
        uploadDir: './uploads',
        keepExtensions: true
    }));
});


app.use(app.router);

app.get('/upload', function(req, res){
    // Render page with upload form
    res.render('upload');
});

app.post('/upload', function(req, res){
    // Returns json of uploaded file
    res.json(req.files);
});

http.createServer(app).listen(3000, function() {
    console.log('App started');
});

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

How to run a PowerShell script

If you are on PowerShell 2.0, use PowerShell.exe's -File parameter to invoke a script from another environment, like cmd.exe. For example:

Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

JavaScript equivalent to printf/String.Format

I'm surprised no one used reduce, this is a native concise and powerful JavaScript function.

ES6 (EcmaScript2015)

_x000D_
_x000D_
String.prototype.format = function() {_x000D_
  return [...arguments].reduce((p,c) => p.replace(/%s/,c), this);_x000D_
};_x000D_
_x000D_
console.log('Is that a %s or a %s?... No, it\'s %s!'.format('plane', 'bird', 'SOman'));
_x000D_
_x000D_
_x000D_

< ES6

function interpolate(theString, argumentArray) {
    var regex = /%s/;
    var _r=function(p,c){return p.replace(regex,c);}
    return argumentArray.reduce(_r, theString);
}

interpolate("%s, %s and %s", ["Me", "myself", "I"]); // "Me, myself and I"

How it works:

reduce applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

_x000D_
_x000D_
var _r= function(p,c){return p.replace(/%s/,c)};_x000D_
_x000D_
console.log(_x000D_
  ["a", "b", "c"].reduce(_r, "[%s], [%s] and [%s]") + '\n',_x000D_
  [1, 2, 3].reduce(_r, "%s+%s=%s") + '\n',_x000D_
  ["cool", 1337, "stuff"].reduce(_r, "%s %s %s")_x000D_
);
_x000D_
_x000D_
_x000D_

WPF Binding StringFormat Short Date String

Be aware of the single quotes for the string format. This doesn't work:

    Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"

while this does:

    Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"

StringIO in Python3

when i write import StringIO it says there is no such module.

From What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

.


A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):

try:
    from StringIO import StringIO ## for Python 2
except ImportError:
    from io import StringIO ## for Python 3

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

SQL query, if value is null then return 1

SELECT 
    ISNULL(currate.currentrate, 1)  
FROM ...

is less verbose than the winning answer and does the same thing

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

Namespace for [DataContract]

In visual studio for .Net 4.0 framework,

  1. Try to add new reference to project.
  2. On .Net Tab, Search System.Runtime.Serialization.
  3. Now, you can use using System.Runtime.Serialization. And the error will not be shown.

How do I drop a foreign key constraint only if it exists in sql server?

Declare @FKeyRemoveQuery NVarchar(max)

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))

BEGIN
    SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']'   
    FROM sys.foreign_keys
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')

    EXECUTE Sp_executesql @FKeyRemoveQuery 

END

Can PHP cURL retrieve response headers AND body in a single request?

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

$parts = explode("\r\n\r\nHTTP/", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = explode("\r\n\r\n", $parts, 2);

Works with HTTP/1.1 100 Continue before other headers.

If you need work with buggy servers which sends only LF instead of CRLF as line breaks you can use preg_split as follows:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);

$parts = preg_split("@\r?\n\r?\nHTTP/@u", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = preg_split("@\r?\n\r?\n@u", $parts, 2);

How to set user environment variables in Windows Server 2008 R2 as a normal user?

Under "Start" enter "environment" in the search field. That will list the option to change the system variables directly in the start menu.

What does status=canceled for a resource mean in Chrome Developer Tools?

For my case, I had an anchor with click event like

<a href="" onclick="somemethod($index, hour, $event)">

Inside click event I had some network call, Chrome cancelling the request. The anchor has href with "" means, it reloads the page and the same time it has click event with network call that gets cancelled. Whenever i replace the href with void like

<a href="javascript:void(0)" onclick="somemethod($index, hour, $event)">

The problem went away!

Making a UITableView scroll when text field is selected

Solution for Swift 3-4 with animations and keyboard frame changing:

First, create a Bool:

// MARK: - Private Properties
private var isKeyboardShowing = false

Secondly, add Observers to the System Keyboard Notifications:

// MARK: - Overriding ViewController Life Cycle Methods
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: .UIKeyboardWillChangeFrame, object: nil)
}

Thirdly, prepare the animation function:

func adjustTableViewInsets(keyboardHeight: CGFloat, duration: NSNumber, curve: NSNumber){
    var extraHeight: CGFloat = 0
    if keyboardHeight > 0 {
        extraHeight = 20
        isKeyboardShowing = true
    } else {
        isKeyboardShowing = false
    }

    let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight + extraHeight, right: 0)
    func animateFunc() {
        //refresh constraints
        //self.view.layoutSubviews()
        tableView.contentInset = contentInset
    }

    UIView.animate(withDuration: TimeInterval(duration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(curve))], animations: animateFunc, completion: nil)
}

Then add the target/action methods (called by the observers):

// MARK: - Target/Selector Actions
func keyboardWillShow(notification: NSNotification) {
    if !isKeyboardShowing {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height

            let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
            let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
    let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
    adjustTableViewInsets(keyboardHeight: 0, duration: duration, curve: curve)
}

func keyboardWillChangeFrame(notification: NSNotification) {
    if isKeyboardShowing {
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber

        if let newKeyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = newKeyboardSize.height
            adjustTableViewInsets(keyboardHeight: keyboardHeight, duration: duration, curve: curve)
        }
    }
}

Lastly, don't forget to remove observers in deinit or in viewWillDisappear:

deinit {
    NotificationCenter.default.removeObserver(self)
}

Google Maps V3 marker with label

Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.

You can now create your label marker like this:

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(result.latitude, result.longitude), 
  icon: markerIcon,
  label: {
    text: 'A'
  }
});

If you would like to see the 1 character restriction removed, please vote for this issue.

Update October 2016:

This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

Nginx: Permission denied for nginx on Ubuntu

I faced similar issue while restarting Nginx and found it to be a cause of SeLinux. Be sure to give a try after either disabling SeLinux or temporarily setting it to Permissive mode using below command:

setenforce 0

I hope it helps :)

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

In c++ what does a tilde "~" before a function name signify?

It's the destructor, it destroys the instance, frees up memory, etc. etc.

Here's a description from ibm.com:

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

See https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/rzarg/cplr380.htm

Converting String To Float in C#

The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.

How do I convert NSMutableArray to NSArray?

NSArray *array = mutableArray;

This [mutableArray copy] antipattern is all over sample code. Stop doing so for throwaway mutable arrays that are transient and get deallocated at the end of the current scope.

There is no way the runtime could optimize out the wasteful copying of a mutable array that is just about to go out of scope, decrefed to 0 and deallocated for good.

How do I dump an object's fields to the console?

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

Replace a string in a file with nodejs

You can also use the 'sed' function that's part of ShellJS ...

 $ npm install [-g] shelljs


 require('shelljs/global');
 sed('-i', 'search_pattern', 'replace_pattern', file);

Visit ShellJs.org for more examples.

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

How to convert int to float in python?

You can just multiply 1.0

>>> 1.0*144/314
0.4585987261146497

Spring application context external properties?

<context:property-placeholder location="file:/apps/tomcat/ath/ath_conf/pcr.application.properties" />

This works for me. Local development machine path is C:\apps\tomcat\ath\ath_conf and in server /apps/tomcat/ath/ath_conf

Both works for me

Gradient borders

border-image-slice will extend a CSS border-image gradient

This (as I understand it) prevents the default slicing of the "image" into sections - without it, nothing appears if the border is on one side only, and if it's around the entire element four tiny gradients appear in each corner.

  border-bottom: 6px solid transparent;
  border-image: linear-gradient(to right, red , yellow);
  border-image-slice: 1;

How do you use a variable in a regular expression?

"ABABAB".replace(/B/g, "A");

As always: don't use regex unless you have to. For a simple string replace, the idiom is:

'ABABAB'.split('B').join('A')

Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.

Why is there no tuple comprehension in Python?

Since Python 3.5, you can also use splat * unpacking syntax to unpack a generator expresion:

*(x for x in range(10)),

ASP.NET MVC: Custom Validation by DataAnnotation

Background:

Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

public class EmployeeModel 
{
    [Required]
    [UniqueEmailAddress]
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}
}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
{
    private IEmployeeRepository _employeeRepository;
    [Inject]
    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository; }
        set
        {
            _employeeRepository = value;
        }
    }
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
    {
        var model = (EmployeeModel)validationContext.ObjectInstance;
        if(model.Field1 == null){
            return new ValidationResult("Field1 is null");
        }
        if(model.Field2 == null){
            return new ValidationResult("Field2 is null");
        }
        if(model.Field3 == null){
            return new ValidationResult("Field3 is null");
        }
        return ValidationResult.Success;
    }
}

Hope this helps. Cheers !

References

How can I create an editable dropdownlist in HTML?

I am not sure there is a way to do it automatically without javascript.

What you need is something which runs on the browser side to submit your form back to the server when they user makes a selection - hence, javascript.

Also, ensure you have an alternate means (i.e. a submit button) for those who have javascript turned off.

A good example: Combo-Box Viewer

I had even a more sophisticated combo-box yesterday, with this dhtmlxCombo , using ajax to retrieve pertinent values amongst large quantity of data.

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Restart pods when configmap updates in Kubernetes?

You can update a metadata annotation that is not relevant for your deployment. it will trigger a rolling-update

for example:

    spec:
      template:
        metadata:
          annotations:
            configmap-version: 1

Convert hex string to int in Python

int(hexstring, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa", 16)
10

Uncaught TypeError: Cannot set property 'onclick' of null

Wrap code in

window.onload = function(){ 
    // your code 
};

How can I stop .gitignore from appearing in the list of untracked files?

If you've already checked in .gitignore and you want to ignore modifications to it, check out this answer:

Try using this command:

git update-index --assume-unchanged FILENAME_TO_IGNORE

To reverse it (if you ever want to commit changes to it), use:

git update-index --no-assume-unchanged

UPDATE:

Here's how to list 'assume unchanged' files under current directory:

git ls-files -v | grep -E "^[a-z]"

As the -v option will use lowercase letters for 'assume unchanged' files.

Parameterize an SQL IN clause

For SQL Server 2008, you can use a table valued parameter. It's a bit of work, but it is arguably cleaner than my other method.

First, you have to create a type

CREATE TYPE dbo.TagNamesTableType AS TABLE ( Name nvarchar(50) )

Then, your ADO.NET code looks like this:

string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
cmd.CommandText = "SELECT Tags.* FROM Tags JOIN @tagNames as P ON Tags.Name = P.Name";

// value must be IEnumerable<SqlDataRecord>
cmd.Parameters.AddWithValue("@tagNames", tags.AsSqlDataRecord("Name")).SqlDbType = SqlDbType.Structured;
cmd.Parameters["@tagNames"].TypeName = "dbo.TagNamesTableType";

// Extension method for converting IEnumerable<string> to IEnumerable<SqlDataRecord>
public static IEnumerable<SqlDataRecord> AsSqlDataRecord(this IEnumerable<string> values, string columnName) {
    if (values == null || !values.Any()) return null; // Annoying, but SqlClient wants null instead of 0 rows
    var firstRecord = values.First();
    var metadata= new SqlMetaData(columnName, SqlDbType.NVarChar, 50); //50 as per SQL Type
    return values.Select(v => 
    {
       var r = new SqlDataRecord(metadata);
       r.SetValues(v);
       return r;
    });
}

Update As Per @Doug

Please try to avoid var metadata = SqlMetaData.InferFromValue(firstRecord, columnName);

It's set first value length, so if first value is 3 characters then its set max length 3 and other records will truncated if more then 3 characters.

So, please try to use: var metadata= new SqlMetaData(columnName, SqlDbType.NVarChar, maxLen);

Note: -1 for max length.

How to fix "Referenced assembly does not have a strong name" error?

I have written a tool to automatically strong-name sign assemblies including ones you do not have the source code for or projects that have been abandoned. It uses many of the techniques described in the answers in a simple way without any of the flaws or drawbacks of existing tools or dated instructions.

http://brutaldev.com/post/2013/10/18/NET-Assembly-Strong-Name-Signer

Hope this helps out anyone that need to sign a third party assembly without having to jump through hoops to get there.

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I'm using Mojave with rbenv, this solution works for me:

$ vi ~/.bash_profile

Add this line into the file:

if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

Difference between static, auto, global and local variable in the context of c and c++

First of all i say that you should google this as it is defined in detail in many places

Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.

Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.

/* Demonstrating Global variables  */
    #include <stdio.h>
    int add_numbers( void );                /* ANSI function prototype */

    /* These are global variables and can be accessed by functions from this point on */
    int  value1, value2, value3;

    int add_numbers( void )
    {
        auto int result;
        result = value1 + value2 + value3;
        return result;
    }

    main()
    {
        auto int result;
        value1 = 10;
        value2 = 20;
        value3 = 30;        
        result = add_numbers();
        printf("The sum of %d + %d + %d is %d\n",
            value1, value2, value3, final_result);
    }


    Sample Program Output
    The sum of 10 + 20 + 30 is 60

The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.

#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );

static int n2;      /* n2 is known from this point onwards */

void no_access( void )
{
    n1 = 10;        /* illegal, n1 not yet known */
    n2 = 5;         /* valid */
}

static int n1;      /* n1 is known from this point onwards */

void all_access( void )
{
    n1 = 10;        /* valid */
    n2 = 3;         /* valid */
}

Static:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list

AUTO:
C, C++

(Called automatic variables.)

All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]

Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.

In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

Postgres manually alter sequence

Use select setval('payments_id_seq', 21, true);

setval contains 3 parameters:

  • 1st parameter is sequence_name
  • 2nd parameter is Next nextval
  • 3rd parameter is optional.

The use of true or false in 3rd parameter of setval is as follows:

SELECT setval('payments_id_seq', 21);           // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true);     // Same as above 
SELECT setval('payments_id_seq', 21, false);    // Next nextval will return 21

The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:

SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;

where table_name is the name of the table, id is the primary key of the table

How to force file download with PHP

You can stream download too which will consume significantly less resource. example:

$readableStream = fopen('test.zip', 'rb');
$writableStream = fopen('php://output', 'wb');

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip"');
stream_copy_to_stream($readableStream, $writableStream);
ob_flush();
flush();

In the above example, I am downloading a test.zip (which was actually the android studio zip on my local machine). php://output is a write-only stream (generally used by echo or print). after that, you just need to set the required headers and call stream_copy_to_stream(source, destination). stream_copy_to_stream() method acts as a pipe which takes the input from the source stream (read stream) and pipes it to the destination stream (write stream) and it also avoid the issue of allowed memory exhausted so you can actually download files that are bigger than your PHP memory_limit.

How do you set the startup page for debugging in an ASP.NET MVC application?

If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.

If you want to start at a different controller action see Mark's answer.

Determine if char is a num or letter

If (theChar >= '0' && theChar <='9') it's a digit. You get the idea.

Parse large JSON file in Nodejs

I realize that you want to avoid reading the whole JSON file into memory if possible, however if you have the memory available it may not be a bad idea performance-wise. Using node.js's require() on a json file loads the data into memory really fast.

I ran two tests to see what the performance looked like on printing out an attribute from each feature from a 81MB geojson file.

In the 1st test, I read the entire geojson file into memory using var data = require('./geo.json'). That took 3330 milliseconds and then printing out an attribute from each feature took 804 milliseconds for a grand total of 4134 milliseconds. However, it appeared that node.js was using 411MB of memory.

In the second test, I used @arcseldon's answer with JSONStream + event-stream. I modified the JSONPath query to select only what I needed. This time the memory never went higher than 82MB, however, the whole thing now took 70 seconds to complete!

What is the Angular equivalent to an AngularJS $watch?

In Angular 2, change detection is automatic... $scope.$watch() and $scope.$digest() R.I.P.

Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section "The Other Stuff").

Here's my understanding of how change detection works:

  • Zone.js "monkey patches the world" -- it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use setTimeout() inside our components rather than something like $timeout... because setTimeout() is monkey patched.
  • Angular builds and maintains a tree of "change detectors". There is one such change detector (class) per component/directive. (You can get access to this object by injecting ChangeDetectorRef.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches() that Angular 1 would set up for {{}} template bindings.
    Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).
  • When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to -- the shared application model/state and/or the component's view state.
  • After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (i.e., if you are not using the onPush change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
    • Lifecycle hooks are called as part of change detection.
      If the component data you want to watch is a primitive input property (String, boolean, number), you can implement ngOnChanges() to be notified of changes.
      If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement ngDoCheck() (see this SO answer for more on this).
      You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's a plunker that violates that. Stateful pipes can also trip you up here.
  • For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.
  • The browser notices the DOM changes and updates the screen.

Other references to learn more:

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.