Programs & Examples On #Robocup

Run a string as a command within a Bash script

your_command_string="..."
output=$(eval "$your_command_string")
echo "$output"

How do I seed a random class to avoid getting duplicate random values

I use this for most situations, keep the seed if there is a need to repeat the sequence

    var seed = (int) DateTime.Now.Ticks;
    var random = new Random(seed);

or

    var random = new Random((int)DateTime.Now.Ticks);

How do I generate random integers within a specific range in Java?

I found this example Generate random numbers :


This example generates random integers in a specific range.

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {

  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }

    log("Done.");
  }

  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }

  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 

An example run of this class :

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.

github changes not staged for commit

I tried everything suggested on whole Stackoverflow. Nothing including -a or -am or anything helped.

If you are the same, do this.

So, the problem is, git thinks some of your subdirectory is sub-project in your root-project. At least, in my case it wasn't like that. It was just regular sub-directory. Not individual project.

Move that regular sub-directory which is not being pushed at some temporary location.

Remove the hidden .git folder from that directory.

cd to the root directory.

git init again.

git add . again.

git commit -m "removed notPushableDirectory temporarily"

git push -f origin master

We will have to force it as the git will see the conflict between remote git and your local structure. Remember, we created this conflict. So, don't worry about forcing it.

Now, it will push that sub-directory as sub-directory and not as sub-module or sub-project inside your root-project.

Apache won't follow symlinks (403 Forbidden)

Yet another subtle pitfall, in case you need AllowOverride All:

Somewhere deep in the fs tree, an old .htaccess having

    Options Indexes

instead of

    Options +Indexes

was all it took to nonchalantly disable the FollowSymLinks set in the server config, and cause a mysterious 403 here.

Best Python IDE on Linux

Probably the new PyCharm from the makers of IntelliJ and ReSharper.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Add and Remove Views in Android Dynamically?

This is my general way:

View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
    parent.removeView(namebar);
}

IntelliJ Organize Imports

navigate to the file where you want to organize imports or just click on the whole package or even click on the project than press CTRL + ALT + O

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

One of the things not covered by anybody so far, to help you think about the problem further, is what format should a long take when it is cast to a string.

Just have a look at a spreedsheet program (like Calc/Excel). Do you want it rounded to the nearest million, with brackets if it's negative, always to show the sign.... Is the number realy a representation of something else, should you show it in Oractal or Hex instead?

The answers so far have given you some default output, but perhaps not the right ones.

error MSB6006: "cmd.exe" exited with code 1

Navigate from Error List Tab to the Visual Studios Output folder by one of the following:

  • Select tab Output in standard VS view at the bottom
  • Click in Menubar View > Output or Ctrl+Alt+O

where Show output from <build> should be selected.

You can find out more by analyzing the output logs.


In my case it was an error in the Cmake step, see below. It could be in any build step, as described in the other answers.

> -- Build Type is debug 
> CMake Error in CMakeLists.txt:
>     A logical block opening on the line
>     <path_to_file:line_number>    
>     is not closed.

How can I scale an image in a CSS sprite

Here's what I did to do this. Keep in mind it won't work on IE8 and below.

#element {
  width:100%;
  height:50px;
  background:url(/path/to/image.png);
  background-position:140.112201963534% 973.333333333333%;
}

The background image's width will scale down as the parent of #element scales down. You can do the same with its height, too, if you convert height to a percentage. The only tricky bit are figuring out the percentages for background-position.

The first percentage is the width of the targeted area of the sprite when at normal width divided by the sprite's total width, and multiplied by 100.

The second percentage is the height of the targeted area of the sprite before being scaled divided by the sprite's total height, and multiplied by 100.

The wording on those two equations is a little sloppy, so let me know if you need me to explain it better.

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

How to print strings with line breaks in java

package test2;

public class main {

    public static void main(String[] args) {
        vehical vehical1 = new vehical("civic", "black","2012");
        System.out.println(vehical1.name+"\n"+vehical1.colour+"\n"+vehical1.model);
    }
}

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

identifier:
    identifier-nondigit
    identifier identifier-nondigit
    identifier digit
identifier-nondigit:
    nondigit
    universal-character-name
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :
#endif

You can also use:

#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

How to delete duplicates on a MySQL table?

Here is a simple answer:

delete a from target_table a left JOIN (select max(id_field) as id, field_being_repeated  
    from target_table GROUP BY field_being_repeated) b 
    on a.field_being_repeated = b.field_being_repeated
      and a.id_field = b.id_field
    where b.id_field is null;

Actionbar notification count icon (badge) like Google has

Try looking at the answers to these questions, particularly the second one which has sample code:

How to implement dynamic values on menu item in Android

How to get text on an ActionBar Icon?

From what I see, You'll need to create your own custom ActionView implementation. An alternative might be a custom Drawable. Note that there appears to be no native implementation of a notification count for the Action Bar.

EDIT: The answer you were looking for, with code: Custom Notification View with sample implementation

composer laravel create project

First, you have to locate the project directory in cmd After this fire below command and 'first_laravel_app' is the project name you can replace it with your own project name.

composer create-project laravel/laravel first_laravel_app --prefer-dist

How do I use JDK 7 on Mac OSX?

I know that some may want to smack me for re-opening old post, but if you feel so do it I just hope this may help someone else trying to set JDK 7 on Mac OS (using IntelliJ).

What I did to get this working on my machine is to:

  • followed instructions on Oracle JDK7 Mac OS X Port for general installation
  • in IntelliJ open/create new project so you can add new SDK (File > Project Structure)
  • select Platform Settings > SDKs, press "+" (plus) sign to add new SDK
  • select JSDK and navigate to /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home. Do not get it mistaken with /Users/YOUR_USERNAME/Library/Java/. This will link 4 JARs from "lib" directory (dt.jar, jconsole.jar, sa-jdi.jar and tools.jar)
  • you will need also add JARs from /Library/Java/JavaVirtualMachines/JDK 1.7.0 Developer Preview.jdk/Contents/Home/jre/lib (charsets.jar, jce.jar, JObjC.jar, jsse.jar, management-agent.jar, resources.jar and rt.jar)

How to set a ripple effect on textview or imageview on Android?

If you want the ripple to be bounded to the size of the TextView/ImageView use:

<TextView
android:background="?attr/selectableItemBackground"
android:clickable="true"/>

(I think it looks better)

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

transform object to array with lodash

There are quite a few ways to get the result you are after. Lets break them in categories:

ES6 Values only:

Main method for this is Object.values. But using Object.keys and Array.map you could as well get to the expected result:

Object.values(obj)
Object.keys(obj).map(k => obj[k])

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('Object.values:', Object.values(obj))_x000D_
console.log('Object.keys:', Object.keys(obj).map(k => obj[k]))
_x000D_
_x000D_
_x000D_

ES6 Key & Value:

Using map and ES6 dynamic/computed properties and destructuring you can retain the key and return an object from the map.

Object.keys(obj).map(k => ({[k]: obj[k]}))
Object.entries(obj).map(([k,v]) => ({[k]:v}))

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('Object.keys:', Object.keys(obj).map(k => ({_x000D_
  [k]: obj[k]_x000D_
})))_x000D_
console.log('Object.entries:', Object.entries(obj).map(([k, v]) => ({_x000D_
  [k]: v_x000D_
})))
_x000D_
_x000D_
_x000D_

Lodash Values only:

The method designed for this is _.values however there are "shortcuts" like _.map and the utility method _.toArray which would also return an array containing only the values from the object. You could also _.map though the _.keys and get the values from the object by using the obj[key] notation.

Note: _.map when passed an object would use its baseMap handler which is basically forEach on the object properties.

_.values(obj)
_.map(obj)
_.toArray(obj)
_.map(_.keys(obj), k => obj[k])

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log('values:', _.values(obj))_x000D_
console.log('map:', _.map(obj))_x000D_
console.log('toArray:', _.toArray(obj))_x000D_
console.log('keys:', _.map(_.keys(obj), k => obj[k]))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Lodash Key & Value:

// Outputs an array with [[KEY, VALUE]]
_.entries(obj)
_.toPairs(obj)

// Outputs array with objects containing the keys and values
_.map(_.entries(obj), ([k,v]) => ({[k]:v}))
_.map(_.keys(obj), k => ({[k]: obj[k]}))
_.transform(obj, (r,c,k) => r.push({[k]:c}), [])
_.reduce(obj, (r,c,k) => (r.push({[k]:c}), r), [])

_x000D_
_x000D_
var obj = {_x000D_
  A: {_x000D_
    name: "John"_x000D_
  },_x000D_
  B: {_x000D_
    name: "Ivan"_x000D_
  }_x000D_
}_x000D_
_x000D_
// Outputs an array with [KEY, VALUE]_x000D_
console.log('entries:', _.entries(obj))_x000D_
console.log('toPairs:', _.toPairs(obj))_x000D_
_x000D_
// Outputs array with objects containing the keys and values_x000D_
console.log('entries:', _.map(_.entries(obj), ([k, v]) => ({_x000D_
  [k]: v_x000D_
})))_x000D_
console.log('keys:', _.map(_.keys(obj), k => ({_x000D_
  [k]: obj[k]_x000D_
})))_x000D_
console.log('transform:', _.transform(obj, (r, c, k) => r.push({_x000D_
  [k]: c_x000D_
}), []))_x000D_
console.log('reduce:', _.reduce(obj, (r, c, k) => (r.push({_x000D_
  [k]: c_x000D_
}), r), []))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Note that in the above examples ES6 is used (arrow functions and dynamic properties). You can use lodash _.fromPairs and other methods to compose an object if ES6 is an issue.

JavaScript .replace only replaces first Match

textTitle.replace(/ /g, '%20');

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How to add a response header on nginx when using proxy_pass?

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.

Extract Data from PDF and Add to Worksheet

Since I do not prefer to rely on external libraries and/or other programs, I have extended your solution so that it works. The actual change here is using the GetFromClipboard function instead of Paste which is mainly used to paste a range of cells. Of course, the downside is that the user must not change focus or intervene during the whole process.

Dim pathPDF As String, textPDF As String
Dim openPDF As Object
Dim objPDF As MsForms.DataObject

pathPDF = "C:\some\path\data.pdf"
Set openPDF = CreateObject("Shell.Application")
openPDF.Open (pathPDF)
'TIME TO WAIT BEFORE/AFTER COPY AND PASTE SENDKEYS
Application.Wait Now + TimeValue("00:00:2")
SendKeys "^a"
Application.Wait Now + TimeValue("00:00:2")
SendKeys "^c"
Application.Wait Now + TimeValue("00:00:1")

AppActivate ActiveWorkbook.Windows(1).Caption
objPDF.GetFromClipboard
textPDF = objPDF.GetText(1)
MsgBox textPDF

If you're interested see my project in github.

Handling 'Sequence has no elements' Exception

I had the same issue, i realized i had deleted the default image that was in the folder just update the media missing, on the specific file

What is the best way to calculate a checksum for a file that is on my machine?

Just use win32 Checksum api. MD5 is native in Win32.

Math.random() explanation

If you want to generate a number from 0 to 100, then your code would look like this:

(int)(Math.random() * 101);

To generate a number from 10 to 20 :

(int)(Math.random() * 11 + 10);

In the general case:

(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);

(where lowerbound is inclusive and upperbound exclusive).

The inclusion or exclusion of upperbound depends on your choice. Let's say range = (upperbound - lowerbound) + 1 then upperbound is inclusive, but if range = (upperbound - lowerbound) then upperbound is exclusive.

Example: If I want an integer between 3-5, then if range is (5-3)+1 then 5 is inclusive, but if range is just (5-3) then 5 is exclusive.

Passing arguments to "make run"

Here is my example. Note that I am writing under Windows 7, using mingw32-make.exe that comes with Dev-Cpp. (I have c:\Windows\System32\make.bat, so the command is still called "make".)

clean:
    $(RM) $(OBJ) $(BIN) 
    @echo off
    if "${backup}" NEQ "" ( mkdir ${backup} 2> nul && copy * ${backup} )

Usage for regular cleaning:

make clean

Usage for cleaning and creating a backup in mydir/:

make clean backup=mydir

Create a variable name with "paste" in R?

In my case the symbols I create (Tax1, Tax2, etc.) already had values but I wanted to use a loop and assign the symbols to another variable. So the above two answers gave me a way to accomplish this. This may be helpful in answering your question as the assignment of a value can take place anytime later.

output=NULL
for(i in 1:8){
   Tax=eval(as.symbol(paste("Tax",i,sep="")))
   L_Data1=L_Data_all[which(L_Data_all$Taxon==Tax[1] | L_Data_all$Taxon==Tax[2] | L_Data_all$Taxon==Tax[3] | L_Data_all$Taxon==Tax[4] | L_Data_all$Taxon==Tax[5]),]
   L_Data=L_Data1$Length[which(L_Data1$Station==Plant[1] | L_Data1$Station==Plant[2])]
   h=hist(L_Data,breaks=breaks,plot=FALSE)
   output=cbind(output,h$counts)
}

window.close() doesn't work - Scripts may close only the windows that were opened by it

The below code worked for me :)

window.open('your current page URL', '_self', '');
window.close();

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

What do we mean by Byte array?

From wikipedia:

In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.

So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.

In C# a byte array could look like:

byte[] bytes = { 3, 10, 8, 25 };

The sample above defines an array of 4 elements, where each element can be up to a Byte in length.

What's the difference between "app.render" and "res.render" in express.js?

use app.render in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.

Tomcat Server Error - Port 8080 already in use

To get rid of this error just click on server tab on eclipse . You will get list of servers as below image (In my case it was tomcat 8 only)

enter image description here

Double click on the respective server. You will get screen as shown below :-

enter image description here

Now change Conflicting port number. In my case I changed 8080 to 8081 (highlighted portion). Save it (ctrl+s) and hence you can start your server now.

Creating a new dictionary in Python

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

How do you check if a certain index exists in a table?

A slight deviation from the original question however may prove useful for future people landing here wanting to DROP and CREATE an index, i.e. in a deployment script.

You can bypass the exists check simply by adding the following to your create statement:

CREATE INDEX IX_IndexName
ON dbo.TableName
WITH (DROP_EXISTING = ON);

Read more here: CREATE INDEX (Transact-SQL) - DROP_EXISTING Clause

N.B. As mentioned in the comments, the index must already exist for this clause to work without throwing an error.

How do I detect if a user is already logged in Firebase?

https://firebase.google.com/docs/auth/web/manage-users

You have to add an auth state change observer.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

Taking multiple inputs from user in python

Python and all other imperative programming languages execute one command after another. Therefore, you can just write:

first  = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')

Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:

product = int(first) * int(second)
print('The product of the two is ' + str(product))

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

Animate text change in UILabel

since iOS4 it can be obviously done with blocks:

[UIView animateWithDuration:1.0
                 animations:^{
                     label.alpha = 0.0f;
                     label.text = newText;
                     label.alpha = 1.0f;
                 }];

SQL Developer is returning only the date, not the time. How do I fix this?

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

Create a Maven project in Eclipse complains "Could not resolve archetype"

click windows-> preferences->Maven. uncheck "Offline" check box. This was not able to download archetype which I was using. When I uncheck it, Everything worked smooth.

MVC 4 client side validation not working

you may have already solved this, but I had some luck by changing the order of the jqueryval item in the BundleConfig with App_Start. The client-side validation would not work even on a fresh out-of-the-box MVC 4 internet solution. So I changed the default:

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

to

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/jquery.unobtrusive*"));

and now my client-side validation is working. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)

How do I copy a hash in Ruby?

Alternative way to Deep_Copy that worked for me.

h1 = {:a => 'foo'} 
h2 = Hash[h1.to_a]

This produced a deep_copy since h2 is formed using an array representation of h1 rather than h1's references.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

python modify item in list, save back in list

A common idiom to change every element of a list looks like this:

for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result

This can be rewritten using enumerate() as:

for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result

See enumerate.

Save file to specific folder with curl command

curl doesn't have an option to that (without also specifying the filename), but wget does. The directory can be relative or absolute. Also, the directory will automatically be created if it doesn't exist.

wget -P relative/dir "$url"

wget -P /absolute/dir "$url"

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:

CREATE TABLE #tmp(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(1000);

SET @sql = N'BULK INSERT #tmp ...' + @variables;

EXEC master.sys.sp_executesql @sql;

SELECT * FROM #tmp;

This makes it tougher to maintain (readability) but gets by the scoping issue:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);

BULK INSERT #tmp ...' + @variables + ';

SELECT * FROM #tmp;';

EXEC master.sys.sp_executesql @sql;

EDIT 2011-01-12

In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:

CREATE TABLE #outer(a INT, b INT, c INT);

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SET NOCOUNT ON; 

CREATE TABLE #inner(a INT, b INT, c INT);

BULK INSERT #inner ...' + @variables + ';

SELECT * FROM #inner;';

INSERT #outer EXEC master.sys.sp_executesql @sql;

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

I know it's an old thread I worked with above answer and had to add:

header('Access-Control-Allow-Methods: GET, POST, PUT');

So my header looks like:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

And the problem was fixed.

Converting binary to decimal integer output

There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:

  1. Train an AI algorithm to convert 32-binary number to decimal based.
  2. Predict a decimal representation from 32-binary.

See example and time comparison below:

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np

y = np.random.randint(0, 2**32, size=10_000)

def gen_x(y):
    _x = bin(y)[2:]
    n = 32 - len(_x)
    return [int(sym) for sym in '0'*n + _x]

X = np.array([gen_x(x) for x in y])

model = LinearRegression()
model.fit(X, y)

def convert_bin_to_dec_ai(array):
    return model.predict(array)

y_pred = convert_bin_to_dec_ai(X)

Time comparison:

enter image description here

This AI solution converts numbers almost x10 times faster than conventional way!

Is there a way to make AngularJS load partials in the beginning and not at when needed?

You can pass $state to your controller and then when the page loads and calls the getter in the controller you call $state.go('index') or whatever partial you want to load. Done.

Get column from a two dimensional array

_x000D_
_x000D_
function arrayColumn(arr, n) {_x000D_
  return arr.map(x=> x[n]);_x000D_
}_x000D_
_x000D_
var twoDimensionalArray = [_x000D_
  [1, 2, 3],_x000D_
  [4, 5, 6],_x000D_
  [7, 8, 9]_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 1));
_x000D_
_x000D_
_x000D_

How do I use arrays in C++?

5. Common pitfalls when using arrays.

5.1 Pitfall: Trusting type-unsafe linking.

OK, you’ve been told, or have found out yourself, that globals (namespace scope variables that can be accessed outside the translation unit) are Evil™. But did you know how truly Evil™ they are? Consider the program below, consisting of two files [main.cpp] and [numbers.cpp]:

// [main.cpp]
#include <iostream>

extern int* numbers;

int main()
{
    using namespace std;
    for( int i = 0;  i < 42;  ++i )
    {
        cout << (i > 0? ", " : "") << numbers[i];
    }
    cout << endl;
}

// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

In Windows 7 this compiles and links fine with both MinGW g++ 4.4.1 and Visual C++ 10.0.

Since the types don't match, the program crashes when you run it.

The Windows 7 crash dialog

In-the-formal explanation: the program has Undefined Behavior (UB), and instead of crashing it can therefore just hang, or perhaps do nothing, or it can send threating e-mails to the presidents of the USA, Russia, India, China and Switzerland, and make Nasal Daemons fly out of your nose.

In-practice explanation: in main.cpp the array is treated as a pointer, placed at the same address as the array. For 32-bit executable this means that the first int value in the array, is treated as a pointer. I.e., in main.cpp the numbers variable contains, or appears to contain, (int*)1. This causes the program to access memory down at very bottom of the address space, which is conventionally reserved and trap-causing. Result: you get a crash.

The compilers are fully within their rights to not diagnose this error, because C++11 §3.5/10 says, about the requirement of compatible types for the declarations,

[N3290 §3.5/10]
A violation of this rule on type identity does not require a diagnostic.

The same paragraph details the variation that is allowed:

… declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4).

This allowed variation does not include declaring a name as an array in one translation unit, and as a pointer in another translation unit.

5.2 Pitfall: Doing premature optimization (memset & friends).

Not written yet

5.3 Pitfall: Using the C idiom to get number of elements.

With deep C experience it’s natural to write …

#define N_ITEMS( array )   (sizeof( array )/sizeof( array[0] ))

Since an array decays to pointer to first element where needed, the expression sizeof(a)/sizeof(a[0]) can also be written as sizeof(a)/sizeof(*a). It means the same, and no matter how it’s written it is the C idiom for finding the number elements of array.

Main pitfall: the C idiom is not typesafe. For example, the code …

#include <stdio.h>

#define N_ITEMS( array ) (sizeof( array )/sizeof( *array ))

void display( int const a[7] )
{
    int const   n = N_ITEMS( a );          // Oops.
    printf( "%d elements.\n", n );
}

int main()
{
    int const   moohaha[]   = {1, 2, 3, 4, 5, 6, 7};

    printf( "%d elements, calling display...\n", N_ITEMS( moohaha ) );
    display( moohaha );
}

passes a pointer to N_ITEMS, and therefore most likely produces a wrong result. Compiled as a 32-bit executable in Windows 7 it produces …

7 elements, calling display...
1 elements.

  1. The compiler rewrites int const a[7] to just int const a[].
  2. The compiler rewrites int const a[] to int const* a.
  3. N_ITEMS is therefore invoked with a pointer.
  4. For a 32-bit executable sizeof(array) (size of a pointer) is then 4.
  5. sizeof(*array) is equivalent to sizeof(int), which for a 32-bit executable is also 4.

In order to detect this error at run time you can do …

#include <assert.h>
#include <typeinfo>

#define N_ITEMS( array )       (                               \
    assert((                                                    \
        "N_ITEMS requires an actual array as argument",        \
        typeid( array ) != typeid( &*array )                    \
        )),                                                     \
    sizeof( array )/sizeof( *array )                            \
    )

7 elements, calling display...
Assertion failed: ( "N_ITEMS requires an actual array as argument", typeid( a ) != typeid( &*a ) ), file runtime_detect ion.cpp, line 16

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

The runtime error detection is better than no detection, but it wastes a little processor time, and perhaps much more programmer time. Better with detection at compile time! And if you're happy to not support arrays of local types with C++98, then you can do that:

#include <stddef.h>

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

#define N_ITEMS( array )       n_items( array )

Compiling this definition substituted into the first complete program, with g++, I got …

M:\count> g++ compile_time_detection.cpp
compile_time_detection.cpp: In function 'void display(const int*)':
compile_time_detection.cpp:14: error: no matching function for call to 'n_items(const int*&)'

M:\count> _

How it works: the array is passed by reference to n_items, and so it does not decay to pointer to first element, and the function can just return the number of elements specified by the type.

With C++11 you can use this also for arrays of local type, and it's the type safe C++ idiom for finding the number of elements of an array.

5.4 C++11 & C++14 pitfall: Using a constexpr array size function.

With C++11 and later it's natural, but as you'll see dangerous!, to replace the C++03 function

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

with

using Size = ptrdiff_t;

template< class Type, Size n >
constexpr auto n_items( Type (&)[n] ) -> Size { return n; }

where the significant change is the use of constexpr, which allows this function to produce a compile time constant.

For example, in contrast to the C++03 function, such a compile time constant can be used to declare an array of the same size as another:

// Example 1
void foo()
{
    int const x[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
    constexpr Size n = n_items( x );
    int y[n] = {};
    // Using y here.
}

But consider this code using the constexpr version:

// Example 2
template< class Collection >
void foo( Collection const& c )
{
    constexpr int n = n_items( c );     // Not in C++14!
    // Use c here
}

auto main() -> int
{
    int x[42];
    foo( x );
}

The pitfall: as of July 2015 the above compiles with MinGW-64 5.1.0 with -pedantic-errors, and, testing with the online compilers at gcc.godbolt.org/, also with clang 3.0 and clang 3.2, but not with clang 3.3, 3.4.1, 3.5.0, 3.5.1, 3.6 (rc1) or 3.7 (experimental). And important for the Windows platform, it does not compile with Visual C++ 2015. The reason is a C++11/C++14 statement about use of references in constexpr expressions:

C++11 C++14 $5.19/2 nineth dash

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
        ?

  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
    • it is initialized with a constant expression or
    • it is a non-static data member of an object whose lifetime began within the evaluation of e;

One can always write the more verbose

// Example 3  --  limited

using Size = ptrdiff_t;

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = std::extent< decltype( c ) >::value;
    // Use c here
}

… but this fails when Collection is not a raw array.

To deal with collections that can be non-arrays one needs the overloadability of an n_items function, but also, for compile time use one needs a compile time representation of the array size. And the classic C++03 solution, which works fine also in C++11 and C++14, is to let the function report its result not as a value but via its function result type. For example like this:

// Example 4 - OK (not ideal, but portable and safe)

#include <array>
#include <stddef.h>

using Size = ptrdiff_t;

template< Size n >
struct Size_carrier
{
    char sizer[n];
};

template< class Type, Size n >
auto static_n_items( Type (&)[n] )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

template< class Type, size_t n >        // size_t for g++
auto static_n_items( std::array<Type, n> const& )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

#define STATIC_N_ITEMS( c ) \
    static_cast<Size>( sizeof( static_n_items( c ).sizer ) )

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = STATIC_N_ITEMS( c );
    // Use c here
    (void) c;
}

auto main() -> int
{
    int x[42];
    std::array<int, 43> y;
    foo( x );
    foo( y );
}

About the choice of return type for static_n_items: this code doesn't use std::integral_constant because with std::integral_constant the result is represented directly as a constexpr value, reintroducing the original problem. Instead of a Size_carrier class one can let the function directly return a reference to an array. However, not everybody is familiar with that syntax.

About the naming: part of this solution to the constexpr-invalid-due-to-reference problem is to make the choice of compile time constant explicit.

Hopefully the oops-there-was-a-reference-involved-in-your-constexpr issue will be fixed with C++17, but until then a macro like the STATIC_N_ITEMS above yields portability, e.g. to the clang and Visual C++ compilers, retaining type safety.

Related: macros do not respect scopes, so to avoid name collisions it can be a good idea to use a name prefix, e.g. MYLIB_STATIC_N_ITEMS.

get data from mysql database to use in javascript

To do with javascript you could do something like this:

<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>

Then you can use whatever you want in your javascript to put the text var into the textbox.

How to access the request body when POSTing using Node.js and Express?

You use the following code to log post data:

router.post("/users",function(req,res){
    res.send(JSON.stringify(req.body, null, 4));
});

Android Min SDK Version vs. Target SDK Version

Target sdk is the version you want to target, and min sdk is the minimum one.

How to quit android application programmatically

Write this code in your on backpressed override method

@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

Selecting element by data attribute with jQuery

The construction like this: $('[data-XXX=111]') isn't working in Safari 8.0.

If you set data attribute this way: $('div').data('XXX', 111), it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111).

I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.

Default parameters with C++ constructors

I would go with the default parameters, for this reason: Your example assumes that ctor parameters directly correspond to member variables. But what if that is not the case, and you have to process the parameters before the object is initialize. Having one common ctor would be the best way to go.

Setting timezone in Python

For windows you can use:

Running Windows command prompt commands in python.

import os
os.system('tzutil /s "Central Standard Time"')

In windows command prompt try:

This gives current timezone:

tzutil /g

This gives a list of timezones:

tzutil /l

This will set the timezone:

tzutil /s "Central America Standard Time"

For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

socket connect() vs bind()

Too Long; Don't Read: The difference is whether the source (local) or the destination address/port is being set. In short, bind() set the source and connect() set the destination. Regardless of TCP or UDP.

bind()

bind() set the socket's local (source) address. This is the address where packets are received. Packets sent by the socket carry this as the source address, so the other host will know where to send back its packets.

If receive is not needed the socket source address is useless. Protocols like TCP require receiving enabled in order to send properly, as the destination host send back a confirmation when one or more packets have arrived (i.e. acknowledgement).

connect()

  • TCP has a "connected" state. connect() triggers the TCP code to try to establish a connection to the other side.
  • UDP has no "connected" state. connect() only set a default address to where packets are sent when no address is specified. When connect() is not used, sendto() or sendmsg() must be used containing the destination address.

When connect() or a send function is called, and no address is bound, Linux automatically bind the socket to a random port. For technical details, take a look at inet_autobind() in Linux kernel source code.

Side notes

  • listen() is TCP only.
  • In AF_INET family, the socket's source or destination address (struct sockaddr_in) is composed by an IP address (see IP header), and TCP or UDP port (see TCP and UDP header).

Password masking console application

Mine ignores control characters and handles line wrapping:

public static string ReadLineMasked(char mask = '*')
{
    var sb = new StringBuilder();
    ConsoleKeyInfo keyInfo;
    while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
    {
        if (!char.IsControl(keyInfo.KeyChar))
        {
            sb.Append(keyInfo.KeyChar);
            Console.Write(mask);
        }
        else if (keyInfo.Key == ConsoleKey.Backspace && sb.Length > 0)
        {
            sb.Remove(sb.Length - 1, 1);

            if (Console.CursorLeft == 0)
            {
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                Console.Write(' ');
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
            }
            else Console.Write("\b \b");
        }
    }
    Console.WriteLine();
    return sb.ToString();
}

Android Room - simple select query - Cannot access database on the main thread

You have to execute request in background. A simple way could be using an Executors :

Executors.newSingleThreadExecutor().execute { 
   yourDb.yourDao.yourRequest() //Replace this by your request
}

Simple state machine example in C#?

Some shameless self-promo here, but a while ago I created a library called YieldMachine which allows a limited-complexity state machine to be described in a very clean and simple way. For example, consider a lamp:

state machine of a lamp

Notice that this state machine has 2 triggers and 3 states. In YieldMachine code, we write a single method for all state-related behavior, in which we commit the horrible atrocity of using goto for each state. A trigger becomes a property or field of type Action, decorated with an attribute called Trigger. I've commented the code of the first state and its transitions below; the next states follow the same pattern.

public class Lamp : StateMachine
{
    // Triggers (or events, or actions, whatever) that our
    // state machine understands.
    [Trigger]
    public readonly Action PressSwitch;

    [Trigger]
    public readonly Action GotError;

    // Actual state machine logic
    protected override IEnumerable WalkStates()
    {
    off:                                       
        Console.WriteLine("off.");
        yield return null;

        if (Trigger == PressSwitch) goto on;
        InvalidTrigger();

    on:
        Console.WriteLine("*shiiine!*");
        yield return null;

        if (Trigger == GotError) goto error;
        if (Trigger == PressSwitch) goto off;
        InvalidTrigger();

    error:
        Console.WriteLine("-err-");
        yield return null;

        if (Trigger == PressSwitch) goto off;
        InvalidTrigger();
    }
}

Short and nice, eh!

This state machine is controlled simply by sending triggers to it:

var sm = new Lamp();
sm.PressSwitch(); //go on
sm.PressSwitch(); //go off

sm.PressSwitch(); //go on
sm.GotError();    //get error
sm.PressSwitch(); //go off

Just to clarify, I've added some comments to the first state to help you understand how to use this.

    protected override IEnumerable WalkStates()
    {
    off:                                       // Each goto label is a state

        Console.WriteLine("off.");             // State entry actions

        yield return null;                     // This means "Wait until a 
                                               // trigger is called"

                                               // Ah, we got triggered! 
                                               //   perform state exit actions 
                                               //   (none, in this case)

        if (Trigger == PressSwitch) goto on;   // Transitions go here: 
                                               // depending on the trigger 
                                               // that was called, go to
                                               // the right state

        InvalidTrigger();                      // Throw exception on 
                                               // invalid trigger

        ...

This works because the C# compiler actually created a state machine internally for each method that uses yield return. This construct is usually used to lazily create sequences of data, but in this case we're not actually interested in the returned sequence (which is all nulls anyway), but in the state behaviour that gets created under the hood.

The StateMachine base class does some reflection on construction to assign code to each [Trigger] action, which sets the Trigger member and moves the state machine forward.

But you don't really need to understand the internals to be able to use it.

How to disable mouse right click on a web page?

It's unprofessional, anyway this will work with javascript enabled:

document.oncontextmenu = document.body.oncontextmenu = function() {return false;}

You may also want to show a message to the user before returning false.

However I have to say that this should not be done generally because it limits users options without resolving the issue (in fact the context menu can be very easily enabled again.).

The following article better explains why this should not be done and what other actions can be taken to solve common related issues: http://articles.sitepoint.com/article/dont-disable-right-click

How do I check to see if a value is an integer in MySQL?

This also works:

CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.

for example

SELECT CAST('a123' AS UNSIGNED) // returns 0
SELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0

How to get a Docker container's IP address from the host

The accepted answer covers exactly what to type fairly well, but here's a minor improvement:

docker container inspect \
  --format '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' \
  $container_id_or_name

This uses the docker container inspect instead of the more generic docker inspect since docker is moving to a noun+verb syntax in their commands, and removing ambiguity of what you are inspecting. I've also included a space after the IP address since containers can be on more than one docker network with more than one IP address. That could be swapped out for any other character or string that makes sense to you.


For those that want to know how they can lookup other values, I often use the following to output any docker formatted syntax into json:

docker container inspect --format '{{json .}}' $container_id_or_name | jq .

You may need to install jq for this to work, or you can leave off the trailing command to read the json as a single long line. When viewing this output, you can see each key name and it's parents so you can create your own format strings to output anything you want. The format syntax is implemented with golang's template with some extra docker specific functions included.


Basically, once Docker creates the container, I want to roll my own code deployment and container configuration scripts.

The main reason for my answer is this comment has a huge red flag to me. It indicates that your images do not contain everything needed to run your application, a big anti-pattern when working with containers. With a dozen clients over many years, I've yet to find a real world use case to connect directly to a container by it's internal IP address from the docker host that didn't have a better option. Instead, if there's post-startup configuration in your container that needs to run, this is often done with an entrypoint script.

There is also a red flag that you are bypassing docker's networking model. With docker networking, there are two options. First, when communicating between containers, this is done with a user created network and using docker's built-in DNS to connect to the container by name or network alias rather than by an IP address that would change when the container is recreated. And for communicating from outside of docker to the container, this is done by publishing a port from the docker host to the container, and then connecting to the host on that port rather than to the container directly. If you stick with these two options, you should be able to access your application without ever knowing its internal IP address.

Hide horizontal scrollbar on an iframe?

set scrolling="no" attribute in your iframe.

How to wait for the 'end' of 'resize' event and only then perform an action?

i wrote a litte wrapper function on my own...

onResize  =   function(fn) {
    if(!fn || typeof fn != 'function')
        return 0;

    var args    = Array.prototype.slice.call(arguments, 1);

    onResize.fnArr    = onResize.fnArr || [];
    onResize.fnArr.push([fn, args]);

    onResize.loop   = function() {
        $.each(onResize.fnArr, function(index, fnWithArgs) {
            fnWithArgs[0].apply(undefined, fnWithArgs[1]);
        });
    };

    $(window).on('resize', function(e) {
        window.clearTimeout(onResize.timeout);
        onResize.timeout    = window.setTimeout("onResize.loop();", 300);
    });
};

Here is the usage:

var testFn  = function(arg1, arg2) {
    console.log('[testFn] arg1: '+arg1);
    console.log('[testFn] arg2: '+arg2);
};

// document ready
$(function() {
    onResize(testFn, 'argument1', 'argument2');
});

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

ASP.NET IIS Web.config [Internal Server Error]

Check this in the web.config and change overrideModeDefault from Deny to Allow.

<configSections>
  <sectionGroup name="system.webServer">
    <section name="handlers" overrideModeDefault="Deny" /> 
    <section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Deny" />

You can also manage sections on web server level in your IIS management console from "Feature Delegation".

Embed an External Page Without an Iframe?

Question is good, but the answer is : it depends on that.

If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.

But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.

How can I tell jackson to ignore a property for which I don't have control over the source code?

One other possibility is, if you want to ignore all unknown properties, you can configure the mapper as follows:

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

IE prompts to open or save json result from server

I changed the content-type to "text/html" instead of "application/json" server side before returning the response. Described it in a blog post, where other solutions have also been added:

http://blog.degree.no/2012/09/jquery-json-ie8ie9-treats-response-as-downloadable-file/

How do I check if an element is really visible with JavaScript?

Here is a sample script and test case. Covers positioned elements, visibilty: hidden, display: none. Didn't test z-index, assume it works.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title></title>
    <style type="text/css">
    div {
      width: 200px;
      border: 1px solid red;
    }
    p {
      border: 2px solid green;
    }
    .r {
      border: 1px solid #BB3333;
      background: #EE9999;
      position: relative;
      top: -50px;
      height: 2em;
    }
    .of {
      overflow: hidden;
      height: 2em;
      word-wrap: none; 
    }
    .of p {
      width: 100%;
    }

    .of pre {
      display: inline;
    }
    .iv {
      visibility: hidden;
    }
    .dn {
      display: none;
    }
    </style>
    <script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>
    <script>
      function isVisible(elem){
        if (Element.getStyle(elem, 'visibility') == 'hidden' || Element.getStyle(elem, 'display') == 'none') {
          return false;
        }
        var topx, topy, botx, boty;
        var offset = Element.positionedOffset(elem);
        topx = offset.left;
        topy = offset.top;
        botx = Element.getWidth(elem) + topx;
        boty = Element.getHeight(elem) + topy;
        var v = false;
        for (var x = topx; x <= botx; x++) {
          for(var y = topy; y <= boty; y++) {
            if (document.elementFromPoint(x,y) == elem) {
              // item is visible
              v = true;
              break;
            }
          }
          if (v == true) {
            break;
          }
        }
        return v;
      }

      window.onload=function() {
        var es = Element.descendants('body');
        for (var i = 0; i < es.length; i++ ) {
          if (!isVisible(es[i])) {
            alert(es[i].tagName);
          }
        }
      }
    </script>
  </head>
  <body id='body'>
    <div class="s"><p>This is text</p><p>More text</p></div>
    <div class="r">This is relative</div>
    <div class="of"><p>This is too wide...</p><pre>hidden</pre>
    <div class="iv">This is invisible</div>
    <div class="dn">This is display none</div>
  </body>
</html>

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):

#!/bin/bash

TABLES=$(mdb-tables -1 $1)

MUSER="root"
MPASS="yourpassword"
MDB="$2"

MYSQL=$(which mysql)

for t in $TABLES
do
    $MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done

mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done

To invoke it simply call it like this:

./mdbconvert.sh accessfile.mdb mysqldatabasename

It will import all tables and all data.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

This will get selected value from multi-value select boxes: $("#id option:selected").val()

Anaconda-Navigator - Ubuntu16.04

I am using Ubuntu 16.04. When I installed anaconda I was facing the same problem. I tried this and it resolved my problem.

step 1 : $ conda install -c anaconda anaconda-navigator?

step 2 : $ anaconda-navigator

Hope it will help.

How to create a directory if it doesn't exist using Node.js?

No, for multiple reasons.

  1. The path module does not have an exists/existsSync method. It is in the fs module. (Perhaps you just made a typo in your question?)

  2. The docs explicitly discourage you from using exists.

    fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

    In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

    Since we're talking about a directory rather than a file, this advice implies you should just unconditionally call mkdir and ignore EEXIST.

  3. In general, You should avoid the *Sync methods. They're blocking, which means absolutely nothing else in your program can happen while you go to the disk. This is a very expensive operation, and the time it takes breaks the core assumption of node's event loop.

    The *Sync methods are usually fine in single-purpose quick scripts (those that do one thing and then exit), but should almost never be used when you're writing a server: your server will be unable to respond to anyone for the entire duration of the I/O requests. If multiple client requests require I/O operations, your server will very quickly grind to a halt.


    The only time I'd consider using *Sync methods in a server application is in an operation that happens once (and only once), at startup. For example, require actually uses readFileSync to load modules.

    Even then, you still have to be careful because lots of synchronous I/O can unnecessarily slow down your server's startup time.


    Instead, you should use the asynchronous I/O methods.

So if we put together those pieces of advice, we get something like this:

function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') { // allow the `mask` parameter to be optional
        cb = mask;
        mask = 0777;
    }
    fs.mkdir(path, mask, function(err) {
        if (err) {
            if (err.code == 'EEXIST') cb(null); // ignore the error if the folder already exists
            else cb(err); // something else went wrong
        } else cb(null); // successfully created folder
    });
}

And we can use it like this:

ensureExists(__dirname + '/upload', 0744, function(err) {
    if (err) // handle folder creation error
    else // we're all good
});

Of course, this doesn't account for edge cases like

  • What happens if the folder gets deleted while your program is running? (assuming you only check that it exists once during startup)
  • What happens if the folder already exists but with the wrong permissions?

How to prevent IFRAME from redirecting top-level window

After reading the w3.org spec. I found the sandbox property.

You can set sandbox="", which prevents the iframe from redirecting. That being said it won't redirect the iframe either. You will lose the click essentially.

Example here: http://jsfiddle.net/ppkzS/1/
Example without sandbox: http://jsfiddle.net/ppkzS/

'list' object has no attribute 'shape'

If you have list, you can print its shape as if it is converted to array

import numpy as np
print(np.asarray(X).shape)

How to scroll HTML page to given anchor?

2018-2020 Pure js:

There is a very convenient way to scroll to the element:

el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})

But as far as I understand he does not have such good support as the options below.

enter image description here

Learn more about the method.


If it is necessary that the element is in the top:

const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({
  top: topPos, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

Demonstration example on Codepen


If you want the element to be in the center:

const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({
  top: rect.top + rect.height / 2 - viewHeight / 2,
  behavior: 'smooth' // smooth scroll
});

Demonstration example on Codepen


Support:

??????? ???? ???????? ???????????

They write that scroll is the same method as scrollTo, but support shows better in scrollTo.

More about the method

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

What's the difference between primitive and reference types?

These are the primitive types in Java:

  • boolean
  • byte
  • short
  • char
  • int
  • long
  • float
  • double

All the other types are reference types: they reference objects.

This is the first part of the Java tutorial about the basics of the language.

Serializing an object to JSON

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

function winHasJSON(){
  json_data = JSON.stringify(obj);
  // ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
  winHasJSON();
} else {
  $.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}

How can I get LINQ to return the object which has the max value for a given property?

Or you can write your own extension method:

static partial class Extensions
{
    public static T WhereMax<T, U>(this IEnumerable<T> items, Func<T, U> selector)
    {
        if (!items.Any())
        {
            throw new InvalidOperationException("Empty input sequence");
        }

        var comparer = Comparer<U>.Default;
        T   maxItem  = items.First();
        U   maxValue = selector(maxItem);

        foreach (T item in items.Skip(1))
        {
            // Get the value of the item and compare it to the current max.
            U value = selector(item);
            if (comparer.Compare(value, maxValue) > 0)
            {
                maxValue = value;
                maxItem  = item;
            }
        }

        return maxItem;
    }
}

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

The error also can occur if you try to save a python list of numpy arrays with np.save and load with np.load. I am only saying it for the sake of googler's to check out that this is not the issue. Also using allow_pickle=True fixed the issue if a list is indeed what you meant to save and load.

Collapsing Sidebar with Bootstrap

Via Angular: using ng-class of Angular, we can hide and show the side bar.

http://jsfiddle.net/DVE4f/359/

<div class="container" style="width:100%" ng-app ng-controller="AppCtrl">
<div class="row">
    <div ng-class="showgraphSidebar ? 'col-xs-3' : 'hidden'" id="colPush" >
        Sidebar
    </div>
    <div ng-class="showgraphSidebar ? 'col-xs-9' : 'col-xs-12'"  id="colMain"  >
        <button  ng-click='toggle()' >Sidebar Toggle</a>
    </div>    
  </div>
</div>

.

function AppCtrl($scope) {
    $scope.showgraphSidebar = false;
    $scope.toggle = function() {
        $scope.showgraphSidebar = !$scope.showgraphSidebar;
    }
}

How do I print the elements of a C++ vector in GDB?

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start 

And the GDB command to print N elements of an array starting at pointer P is:

print P@N

Or, in a short form (for a standard .gdbinit):

p P@N

EF 5 Enable-Migrations : No context type was found in the assembly

You dbcontext is in Toombu.DataAccess So you should enable migrations in Toombu.DataAccess.

conversion from string to json object android

try this:

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

How to create cross-domain request?

It is nothing you can do in the client side. I added @CrossOrigin in the controller in the server side and it works.

@RestController
@CrossOrigin(origins = "*")
public class MyController

Please refer to docs.

Lin

Environ Function code samples for VBA

Some time when we use Environ() function we may get the Library or property not found error. Use VBA.Environ() or VBA.Environ$() to avoid the error.

Deleting DataFrame row in Pandas based on column value

Another way of doing it. May not be the most efficient way as the code looks a bit more complex than the code mentioned in other answers, but still alternate way of doing the same thing.

  df = df.drop(df[df['line_race']==0].index)

How to execute INSERT statement using JdbcTemplate class from Spring Framework

Use jdbcTemplate.update(String sql, Object... args) method:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    var1, var2
);

or jdbcTemplate.update(String sql, Object[] args, int[] argTypes), if you need to map arguments to SQL types manually:

jdbcTemplate.update(
    "INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
    new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);

Simple way to count character occurrences in a string

You can look at sorting the string -- treat it as a char array -- and then do a modified binary search which counts occurrences? But I agree with @tofutim that traversing it is the most efficient -- O(N) versus O(N * logN) + O(logN)

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

you need to configure this in web.xml as well.Please refer below code.

<taglib>
    <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
    <taglib-location>/WEB-INF/lib/c.tld</taglib-location>
</taglib>

Please let me know if you still face any issue.

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

How do I pass a value from a child back to the parent form?

Create a property (or method) on FormOptions, say GetMyResult:

using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();

    string result = formOptions.GetMyResult;

    // do what ever with result...
}

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

Use JavaScript to place cursor at end of text in text input element

var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);

nodejs npm global config missing on windows

How to figure it out

Start with npm root -- it will show you the root folder for NPM packages for the current user. Add -g and you get a global folder. Don't forget to substract node_modules.

Use npm config / npm config -g and check that it'd create you a new .npmrc / npmrc file for you.

Tested on Windows 10 Pro, NPM v.6.4.1:

Global NPM config

C:\Users\%username%\AppData\Roaming\npm\etc\npmrc

Per-user NPM config

C:\Users\%username%\.npmrc

Built-in NPM config

C:\Program Files\nodejs\node_modules\npm\npmrc

References:

List all sequences in a Postgres db 8.1 with SQL

The following query gives names of all sequences.

SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';

Typically a sequence is named as ${table}_id_seq. Simple regex pattern matching will give you the table name.

To get last value of a sequence use the following query:

SELECT last_value FROM test_id_seq;

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

When is JavaScript synchronous?

JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.

JavaScript timers operate with this same kind of callback.

Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

RoBorg is correct, but I wanted to add a side note.

In IE7/IE8 when Microsoft added Tabs to their browser they broke one thing that will cause havoc with your JS if you are not careful.

Imagine this page layout:

MainPage.html
  IframedPage1.html   (named "foo")
  IframedPage2.html   (named "bar")
    IframedPage3.html (named "baz")

Now in frame "baz" you click a link (no target, loads in the "baz" frame) it works fine.

If the page that gets loaded, lets call it special.html, uses JS to check if "it" has a parent frame named "bar" it will return true (expected).

Now lets say that the special.html page when it loads, checks the parent frame (for existence and its name, and if it is "bar" it reloads itself in the bar frame. e.g.

if(window.parent && window.parent.name == 'bar'){
  window.parent.location = self.location;
}

So far so good. Now comes the bug.

Lets say instead of clicking on the original link like normal, and loading the special.html page in the "baz" frame, you middle-clicked it or chose to open it in a new Tab.

When that new tab loads (with no parent frames at all!) IE will enter an endless loop of page loading! because IE "copies over" the frame structure in JavaScript such that the new tab DOES have a parent, and that parent HAS the name "bar".

The good news, is that checking:

if(self == top){
  //this returns true!
}

in that new tab does return true, and thus you can test for this odd condition.

Refresh DataGridView when updating data source

I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a List. Use a BindingList. The BindingList has events that fire when items are added or changed, and the DataGridView will automatically update itself when these events are fired.

Create a string with n characters

I highly suggest not to write the loop by hand. You will do that over and over again during the course of your programming career. People reading your code - that includes you - always have to invest time, even if it are just some seconds, to digest the meaning of the loop.

Instead reuse one of the available libraries providing code that does just that like StringUtils.repeatfrom Apache Commons Lang:

StringUtils.repeat(' ', length);

That way you also do not have to bother about performance, thus all the gory details of StringBuilder, Compiler optimisations etc. are hidden. If the function would turn out as slow it would be a bug of the library.

With Java 11 it becomes even easier:

" ".repeat(length);

How to set back button text in Swift

This works for Swift 5:

self.navigationItem.backBarButtonItem?.title = ""

Please note it will be effective for the next pushed view controller not the current one on the display, that's why it's very confusing!

Also, check the storyboard and select the navigation item of the previous view controller then type something in the Back Button (Inspector).

How do I dynamically assign properties to an object in TypeScript?

Here is a special version of Object.assign, that automatically adjusts the variable type with every property change. No need for additional variables, type assertions, explicit types or object copies:

function assign<T, U>(target: T, source: U): asserts target is T & U {
    Object.assign(target, source)
}

const obj = {};
assign(obj, { prop1: "foo" })
//  const obj now has type { prop1: string; }
obj.prop1 // string
assign(obj, { prop2: 42 })
//  const obj now has type { prop1: string; prop2: number; }
obj.prop2 // number

//  const obj: { prop1: "foo", prop2: 42 }

Note: The sample makes use of TS 3.7 assertion functions. The return type of assign is void, unlike Object.assign.

Skip first entry in for loop in python?

The best way to skip the first item(s) is:

from itertools import islice
for car in islice(cars, 1, None):
    # do something

islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterator.

To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in the cars list.

reading from app.config file

Try to rebuild your project - It copies the content of App.config to "<YourProjectName.exe>.config" in the build library.

How can I post data as form data instead of a request payload?

I took a few of the other answers and made something a bit cleaner, put this .config() call on the end of your angular.module in your app.js:

.config(['$httpProvider', function ($httpProvider) {
  // Intercept POST requests, convert to standard form encoding
  $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
  $httpProvider.defaults.transformRequest.unshift(function (data, headersGetter) {
    var key, result = [];

    if (typeof data === "string")
      return data;

    for (key in data) {
      if (data.hasOwnProperty(key))
        result.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key]));
    }
    return result.join("&");
  });
}]);

Should you commit .gitignore into the Git repos?

Normally yes, .gitignore is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG or something. In those cases you probably don't want to force that on anyone else.

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

If You using Android 9.0 with legacy jar than you have to use. in your mainfest file.

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

adding a datatable in a dataset

I assume that you haven't set the TableName property of the DataTable, for example via constructor:

var tbl = new DataTable("dtImage");

If you don't provide a name, it will be automatically created with "Table1", the next table will get "Table2" and so on.

Then the solution would be to provide the TableName and then check with Contains(nameOfTable).

To clarify it: You'll get an ArgumentException if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException if there's already a DataTable in the DataSet with the same name(not case-sensitive).

http://msdn.microsoft.com/en-us/library/as4zy2kc.aspx

Hide div element when screen size is smaller than a specific size

@media only screen and (max-width: 1026px) { 
  #fadeshow1 { 
    display: none; 
  } 
}

Any time the screen is less than 1026 pixels wide, anything inside the { } will apply.

Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS

ab load testing

I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.

the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".

the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!

but did anyone think to "localhost" on any apache server for example www.apachefriends.org?

you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".

and then: benchmark it!

bench.php

<?php

for($i=1;$i<50000;$i++){
    print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>

void.php

<?php
?>

on your Desktop you should use a .bat file(in Windows) like this:

bench.bat

"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause

Now if you pay attention closely ...

the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!

here i got :

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/void.php
Document Length:        0 bytes

Concurrency Level:      1
Time taken for tests:   11.219 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2150000 bytes
HTML transferred:       0 bytes
Requests per second:    891.34 [#/sec] (mean)
Time per request:       1.122 [ms] (mean)
Time per request:       1.122 [ms] (mean, across all concurrent requests)
Transfer rate:          187.15 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:     0    1   0.9      1      17
Waiting:        0    1   0.9      1      17
Total:          0    1   0.9      1      17

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      2
  98%      2
  99%      3
 100%     17 (longest request)

c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:        Apache/2.4.33
Server Hostname:        localhost
Server Port:            80

Document Path:          /bench/bench.php
Document Length:        1799964 bytes

Concurrency Level:      1
Time taken for tests:   177.006 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      18001600000 bytes
HTML transferred:       17999640000 bytes
Requests per second:    56.50 [#/sec] (mean)
Time per request:       17.701 [ms] (mean)
Time per request:       17.701 [ms] (mean, across all concurrent requests)
Transfer rate:          99317.00 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.3      0       1
Processing:    12   17   3.2     17      90
Waiting:        0    1   1.1      1      26
Total:         13   18   3.2     18      90

Percentage of the requests served within a certain time (ms)
  50%     18
  66%     19
  75%     19
  80%     20
  90%     21
  95%     22
  98%     23
  99%     26
 100%     90 (longest request)

c:\xampp\htdocs\bench>pause
Press any key to continue . . .

90-17= 73 the result i expect !

Scrollbar without fixed height/Dynamic height with scrollbar

Use this:

style="height: 150px; max-height: 300px; overflow: auto;" 

fixe a height, it will be the default height and then a scroll bar come to access to the entire height

How to rename a pane in tmux?

You can adjust the pane title by setting the pane border in the tmux.conf for example like this:

###############
# pane border #
###############
set -g pane-border-status bottom
#colors for pane borders
setw -g pane-border-style fg=green,bg=black
setw -g pane-active-border-style fg=colour118,bg=black
setw -g automatic-rename off
setw -g pane-border-format ' #{pane_index} #{pane_title} : #{pane_current_path} '
# active pane normal, other shaded out?
setw -g window-style fg=colour28,bg=colour16
setw -g window-active-style fg=colour46,bg=colour16

Where pane_index, pane_title and pane_current_path are variables provided by tmux itself.

After reloading the config or starting a new tmux session, you can then set the title of the current pane like this:

tmux select-pane -T "fancy pane title";
#or
tmux select-pane -t paneIndexInteger -T "fancy pane title";

If all panes have some processes running, so you can't use the command line, you can also type the commands after pressing the prefix bind (C-b by default) and a colon (:) without having "tmux" in the front of the command:

select-pane -T "fancy pane title"
#or:
select-pane -t paneIndexInteger -T "fancy pane title"

What are the differences between the urllib, urllib2, urllib3 and requests module?

A key point that I find missing in the above answers is that urllib returns an object of type <class http.client.HTTPResponse> whereas requests returns <class 'requests.models.Response'>.

Due to this, read() method can be used with urllib but not with requests.

P.S. : requests is already rich with so many methods that it hardly needs one more as read() ;>

Check if application is installed - Android

Try this:

public static boolean isAvailable(Context ctx, Intent intent) {
    final PackageManager mgr = ctx.getPackageManager();
    List<ResolveInfo> list =
        mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

How to maintain state after a page refresh in React.js?

I may be late but actual code for react-create-app for react > 16 ver. After each change state is saved in sessionStorage (not localStorage) and is crypted via crypto-js. On refresh (when user demands refresh of the page by clicking refresh button) state is loaded from the storage. I also recommend not to use sourceMaps in build to avoid readablility of the key phrases.

my index.js

import React from "react";
import ReactDOM from "react-dom";
import './index.css';
import App from './containers/App';
import * as serviceWorker from './serviceWorker';
import {createStore} from "redux";
import {Provider} from "react-redux"
import {BrowserRouter} from "react-router-dom";
import rootReducer from "./reducers/rootReducer";
import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse("someRandomText_encryptionPhase");
const iv = CryptoJS.enc.Utf8.parse("someRandomIV");
const persistedState = loadFromSessionStorage();

let store = createStore(rootReducer, persistedState,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

function loadFromSessionStorage() {
    try {
        const serializedState = sessionStorage.getItem('state');
        if (serializedState === null) {
            return undefined;
        }
        const decrypted = CryptoJS.AES.decrypt(serializedState, key, {iv: iv}).toString(CryptoJS.enc.Utf8);
        return JSON.parse(decrypted);
    } catch {
        return undefined;
    }
}

function saveToSessionStorage(state) {
        try {
            const serializedState = JSON.stringify(state);
            const encrypted = CryptoJS.AES.encrypt(serializedState, key, {iv: iv});
            sessionStorage.setItem('state', encrypted)
        } catch (e) {
            console.log(e)
        }
}

ReactDOM.render(
    <BrowserRouter>
        <Provider store={store}>
            <App/>
        </Provider>
    </BrowserRouter>,
    document.getElementById('root')
);

store.subscribe(() => saveToSessionStorage(store.getState()));

serviceWorker.unregister();

How do I make a JAR from a .java file?

Perhaps the most beginner-friendly way to compile a JAR from your Java code is to use an IDE (integrated development environment; essentially just user-friendly software for development) like Netbeans or Eclipse.

  • Install and set-up an IDE. Here is the latest version of Eclipse.
  • Create a project in your IDE and put your Java files inside of the project folder.
  • Select the project in the IDE and export the project as a JAR. Double check that the appropriate java files are selected when exporting.

You can always do this all very easily with the command line. Make sure that you are in the same directory as the files targeted before executing a command such as this:

javac YourApp.java
jar -cf YourJar.jar YourApp.class

...changing "YourApp" and "YourJar" to the proper names of your files, respectively.

How do I measure request and response times at once using cURL?

This is a modified version of Simons answer which makes the multi-lined output a single line. It also introduces the current timestamp so it's easier to follow each line of output.

Sample format fle
$ cat time-format.txt
time_namelookup:%{time_namelookup} time_connect:%{time_connect} time_appconnect:%{time_appconnect} time_pretransfer:%{time_pretransfer} time_redirect:%{time_redirect} time_starttransfer:%{time_starttransfer} time_total:%{time_total}\n
example cmd
$ while [ 1 ];do echo -n "$(date) - " ; curl -w @time-format.txt -o /dev/null -s https://myapp.mydom.com/v1/endpt-http; sleep 1; done | grep -v time_total:0
results
Mon Dec 16 17:51:47 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.172 time_pretransfer:0.172 time_redirect:0.000 time_starttransfer:1.666 time_total:1.666
Mon Dec 16 17:51:50 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.175 time_pretransfer:0.175 time_redirect:0.000 time_starttransfer:3.794 time_total:3.795
Mon Dec 16 17:51:55 UTC 2019 - time_namelookup:0.004 time_connect:0.017 time_appconnect:0.175 time_pretransfer:0.175 time_redirect:0.000 time_starttransfer:1.971 time_total:1.971
Mon Dec 16 17:51:58 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.173 time_pretransfer:0.173 time_redirect:0.000 time_starttransfer:1.161 time_total:1.161
Mon Dec 16 17:52:00 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.166 time_pretransfer:0.167 time_redirect:0.000 time_starttransfer:1.434 time_total:1.434
Mon Dec 16 17:52:02 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.177 time_pretransfer:0.177 time_redirect:0.000 time_starttransfer:5.119 time_total:5.119
Mon Dec 16 17:52:08 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.172 time_pretransfer:0.172 time_redirect:0.000 time_starttransfer:30.185 time_total:30.185
Mon Dec 16 17:52:39 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.164 time_pretransfer:0.164 time_redirect:0.000 time_starttransfer:30.175 time_total:30.176
Mon Dec 16 17:54:28 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:3.191 time_pretransfer:3.191 time_redirect:0.000 time_starttransfer:3.212 time_total:3.212
Mon Dec 16 17:56:08 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:1.184 time_pretransfer:1.184 time_redirect:0.000 time_starttransfer:1.215 time_total:1.215
Mon Dec 16 18:00:24 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.181 time_pretransfer:0.181 time_redirect:0.000 time_starttransfer:1.267 time_total:1.267

I used the above to catch slow responses on the above endpoint.

Finding duplicate rows in SQL Server

 /*To get duplicate data in table */

 SELECT COUNT(EmpCode),EmpCode FROM tbl_Employees WHERE Status=1 
  GROUP BY EmpCode HAVING COUNT(EmpCode) > 1

Check if a string isn't nil or empty in Lua

Can this code be simplified in one if test instead two?

nil and '' are different values. If you need to test that s is neither, IMO you should just compare against both, because it makes your intent the most clear.

That and a few alternatives, with their generated bytecode:

if not foo or foo == '' then end
     GETGLOBAL       0 -1    ; foo
     TEST            0 0 0
     JMP             3       ; to 7
     GETGLOBAL       0 -1    ; foo
     EQ              0 0 -2  ; - ""
     JMP             0       ; to 7

if foo == nil or foo == '' then end
    GETGLOBAL       0 -1    ; foo
    EQ              1 0 -2  ; - nil
    JMP             3       ; to 7
    GETGLOBAL       0 -1    ; foo
    EQ              0 0 -3  ; - ""
    JMP             0       ; to 7

if (foo or '') == '' then end
   GETGLOBAL       0 -1    ; foo
   TEST            0 0 1
   JMP             1       ; to 5
   LOADK           0 -2    ; ""
   EQ              0 0 -2  ; - ""
   JMP             0       ; to 7

The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.

How do I revert an SVN commit?

F=code.c
REV=123
svn diff -c $REV $F | patch -R -p0 \
    && svn commit -m "undid rev $REV" $F

Get current time in hours and minutes

I have another solution for your question .

In the first when use date the output is like this :

Thu 28 Jan 2021 22:29:40 IST

Then if you want only to show current time in hours and minutes you can use this command :

date | cut -d " " -f5 | cut -d ":" -f1-2 

Then the output :

22:29

Getting data-* attribute for onclick event for an html element

here is an example

 <a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>

    $('.facultySelecter').click(function() {        
    var unhide = $(this).data("faculty");
    });

this would set var unhide as ahs, so use .data("foo") to get the "foo" value of the data-* attribute you're looking to get

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

select 
    case
        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
    else 
        'not running'
    end as run_status from processes

How to append binary data to a buffer in node.js

This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.

For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.

I have left the read method unimplemented to keep the example small in size.

The realloc function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.

For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.

Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.

var Buffer_A1 = function (chunk_size) {
    this.buffer_list = [];
    this.total_size = 0;
    this.cur_size = 0;
    this.cur_buffer = [];
    this.chunk_size = chunk_size || 4096;

    this.buffer_list.push(new Buffer(this.chunk_size));
};

Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
    var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;

    var lastbuf = this.buffer_list.length - 1;

    for (var x = 0; x < can_write; ++x) {
        this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
    }

    this.cur_size += can_write;
    this.total_size += can_write;

    if (this.cur_size == this.chunk_size) {
        this.buffer_list.push(new Buffer(this.chunk_size));
        this.cur_size = 0;
    }

    return can_write;
};

/*
    The `data` parameter can be anything that is array like. It just must
    support indexing and a length and produce an acceptable value to be
    used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
    offset = offset == undefined ? 0 : offset;
    length = length == undefined ? data.length : length;

    var rem = length;
    while (rem > 0) {
        rem -= this.writeByteArrayLimited(data, length - rem, rem);
    }
};

Buffer_A1.prototype.readByteArray = function (data, offset, length) {
    /*
        If you really wanted to implement some read functionality
        then you would have to deal with unaligned reads which could
        span two buffers.
    */
};

Buffer_A1.prototype.getSingleBuffer = function () {
    var obuf = new Buffer(this.total_size);
    var cur_off = 0;
    var x;

    for (x = 0; x < this.buffer_list.length - 1; ++x) {
        this.buffer_list[x].copy(obuf, cur_off);
        cur_off += this.buffer_list[x].length;
    }

    this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);

    return obuf;
};

Spring Boot: Cannot access REST Controller on localhost (404)

For me, the problem was that I had set up the Application in a way that it always immediately shut down after starting. So by the time I tried out if I could access the controller, the Application wasn't running anymore. The problem with immediately shutting down is adressed in this thread.

How to send a JSON object using html form data

you code is fine but never executed, cause of submit button [type="submit"] just replace it by type=button

<input value="Submit" type="button" onclick="submitform()">

inside your script; form is not declared.

let form = document.forms[0];
xhr.open(form.method, form.action, true);

Difference between require, include, require_once and include_once?

Require critical parts, like authorization and include all others.

Multiple includes are just very bad design and must be avoided at all. So, *_once doesn't really matter.

Android ADB devices unauthorized

I was hit by this problem, too. I'm using my custom build of AOSP on Nexus 5X. I've added a single line in build/core/main.mk:

diff --git a/core/main.mk b/core/main.mk
index a6f829ab6..555657539 100644
--- a/core/main.mk
+++ b/core/main.mk
@@ -362,6 +362,8 @@ else # !enable_target_debugging
   ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=0
 endif # !enable_target_debugging

+ADDITIONAL_DEFAULT_PROPERTIES += ro.adb.secure=1
+
 ## eng ##

 ifeq ($(TARGET_BUILD_VARIANT),eng)

Now adb shell works fine

Those materials are useful (Chinese articles): http://www.voidcn.com/blog/kc58236582/article/p-6335996.html, http://blog.csdn.net/fanmengke_im/article/details/28389439

Error installing mysql2: Failed to build gem native extension

If still getting error then follow the steps of mysql2 gem installation on Rails 3 on -

http://rorguide.blogspot.com/2011/03/installing-mysql2-gem-on-ruby-192-and.html

where most of the user were able to install mysql2 gem.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

I see this errormessage has a lot of different reasons. I had the same error when trying to set up locally another repository alongside one already fully working with ssh etc. and connect it to same server, but other repository. No answers were here to be found, but I figured it out. So I post it. Hopefully helps someone.

git remote add origin [email protected]:teamalpha/repositorytwo.git

Hibernate, @SequenceGenerator and allocationSize

I would check the DDL for the sequence in the schema. JPA Implementation is responsible only creation of the sequence with the correct allocation size. Therefore, if the allocation size is 50 then your sequence must have the increment of 50 in its DDL.

This case may typically occur with the creation of a sequence with allocation size 1 then later configured to allocation size 50 (or default) but the sequence DDL is not updated.

Experimental decorators warning in TypeScript compilation

This error also occurs when you choose "src" folder for your workspace folder.

When the root folder, folder where the "src", "node_modules" are located is chosen, the error disappears

ECMAScript 6 class destructor

You have to manually "destruct" objects in JS. Creating a destroy function is common in JS. In other languages this might be called free, release, dispose, close, etc. In my experience though it tends to be destroy which will unhook internal references, events and possibly propagates destroy calls to child objects as well.

WeakMaps are largely useless as they cannot be iterated and this probably wont be available until ECMA 7 if at all. All WeakMaps let you do is have invisible properties detached from the object itself except for lookup by the object reference and GC so that they don't disturb it. This can be useful for caching, extending and dealing with plurality but it doesn't really help with memory management for observables and observers. WeakSet is a subset of WeakMap (like a WeakMap with a default value of boolean true).

There are various arguments on whether to use various implementations of weak references for this or destructors. Both have potential problems and destructors are more limited.

Destructors are actually potentially useless for observers/listeners as well because typically the listener will hold references to the observer either directly or indirectly. A destructor only really works in a proxy fashion without weak references. If your Observer is really just a proxy taking something else's Listeners and putting them on an observable then it can do something there but this sort of thing is rarely useful. Destructors are more for IO related things or doing things outside of the scope of containment (IE, linking up two instances that it created).

The specific case that I started looking into this for is because I have class A instance that takes class B in the constructor, then creates class C instance which listens to B. I always keep the B instance around somewhere high above. A I sometimes throw away, create new ones, create many, etc. In this situation a Destructor would actually work for me but with a nasty side effect that in the parent if I passed the C instance around but removed all A references then the C and B binding would be broken (C has the ground removed from beneath it).

In JS having no automatic solution is painful but I don't think it's easily solvable. Consider these classes (pseudo):

function Filter(stream) {
    stream.on('data', function() {
        this.emit('data', data.toString().replace('somenoise', '')); // Pretend chunks/multibyte are not a problem.
    });
}
Filter.prototype.__proto__ = EventEmitter.prototype;
function View(df, stream) {
    df.on('data', function(data) {
        stream.write(data.toUpper()); // Shout.
    });
}

On a side note, it's hard to make things work without anonymous/unique functions which will be covered later.

In a normal case instantiation would be as so (pseudo):

var df = new Filter(stdin),
    v1 = new View(df, stdout),
    v2 = new View(df, stderr);

To GC these normally you would set them to null but it wont work because they've created a tree with stdin at the root. This is basically what event systems do. You give a parent to a child, the child adds itself to the parent and then may or may not maintain a reference to the parent. A tree is a simple example but in reality you may also find yourself with complex graphs albeit rarely.

In this case, Filter adds a reference to itself to stdin in the form of an anonymous function which indirectly references Filter by scope. Scope references are something to be aware of and that can be quite complex. A powerful GC can do some interesting things to carve away at items in scope variables but that's another topic. What is critical to understand is that when you create an anonymous function and add it to something as a listener to ab observable, the observable will maintain a reference to the function and anything the function references in the scopes above it (that it was defined in) will also be maintained. The views do the same but after the execution of their constructors the children do not maintain a reference to their parents.

If I set any or all of the vars declared above to null it isn't going to make a difference to anything (similarly when it finished that "main" scope). They will still be active and pipe data from stdin to stdout and stderr.

If I set them all to null it would be impossible to have them removed or GCed without clearing out the events on stdin or setting stdin to null (assuming it can be freed like this). You basically have a memory leak that way with in effect orphaned objects if the rest of the code needs stdin and has other important events on it prohibiting you from doing the aforementioned.

To get rid of df, v1 and v2 I need to call a destroy method on each of them. In terms of implementation this means that both the Filter and View methods need to keep the reference to the anonymous listener function they create as well as the observable and pass that to removeListener.

On a side note, alternatively you can have an obserable that returns an index to keep track of listeners so that you can add prototyped functions which at least to my understanding should be much better on performance and memory. You still have to keep track of the returned identifier though and pass your object to ensure that the listener is bound to it when called.

A destroy function adds several pains. First is that I would have to call it and free the reference:

df.destroy();
v1.destroy();
v2.destroy();
df = v1 = v2 = null;

This is a minor annoyance as it's a bit more code but that is not the real problem. When I hand these references around to many objects. In this case when exactly do you call destroy? You cannot simply hand these off to other objects. You'll end up with chains of destroys and manual implementation of tracking either through program flow or some other means. You can't fire and forget.

An example of this kind of problem is if I decide that View will also call destroy on df when it is destroyed. If v2 is still around destroying df will break it so destroy cannot simply be relayed to df. Instead when v1 takes df to use it, it would need to then tell df it is used which would raise some counter or similar to df. df's destroy function would decrease than counter and only actually destroy if it is 0. This sort of thing adds a lot of complexity and adds a lot that can go wrong the most obvious of which is destroying something while there is still a reference around somewhere that will be used and circular references (at this point it's no longer a case of managing a counter but a map of referencing objects). When you're thinking of implementing your own reference counters, MM and so on in JS then it's probably deficient.

If WeakSets were iterable, this could be used:

function Observable() {
    this.events = {open: new WeakSet(), close: new WeakSet()};
}
Observable.prototype.on = function(type, f) {
    this.events[type].add(f);
};
Observable.prototype.emit = function(type, ...args) {
    this.events[type].forEach(f => f(...args));
};
Observable.prototype.off = function(type, f) {
    this.events[type].delete(f);
};

In this case the owning class must also keep a token reference to f otherwise it will go poof.

If Observable were used instead of EventListener then memory management would be automatic in regards to the event listeners.

Instead of calling destroy on each object this would be enough to fully remove them:

df = v1 = v2 = null;

If you didn't set df to null it would still exist but v1 and v2 would automatically be unhooked.

There are two problems with this approach however.

Problem one is that it adds a new complexity. Sometimes people do not actually want this behaviour. I could create a very large chain of objects linked to each other by events rather than containment (references in constructor scopes or object properties). Eventually a tree and I would only have to pass around the root and worry about that. Freeing the root would conveniently free the entire thing. Both behaviours depending on coding style, etc are useful and when creating reusable objects it's going to be hard to either know what people want, what they have done, what you have done and a pain to work around what has been done. If I use Observable instead of EventListener then either df will need to reference v1 and v2 or I'll have to pass them all if I want to transfer ownership of the reference to something else out of scope. A weak reference like thing would mitigate the problem a little by transferring control from Observable to an observer but would not solve it entirely (and needs check on every emit or event on itself). This problem can be fixed I suppose if the behaviour only applies to isolated graphs which would complicate the GC severely and would not apply to cases where there are references outside the graph that are in practice noops (only consume CPU cycles, no changes made).

Problem two is that either it is unpredictable in certain cases or forces the JS engine to traverse the GC graph for those objects on demand which can have a horrific performance impact (although if it is clever it can avoid doing it per member by doing it per WeakMap loop instead). The GC may never run if memory usage does not reach a certain threshold and the object with its events wont be removed. If I set v1 to null it may still relay to stdout forever. Even if it does get GCed this will be arbitrary, it may continue to relay to stdout for any amount of time (1 lines, 10 lines, 2.5 lines, etc).

The reason WeakMap gets away with not caring about the GC when non-iterable is that to access an object you have to have a reference to it anyway so either it hasn't been GCed or hasn't been added to the map.

I am not sure what I think about this kind of thing. You're sort of breaking memory management to fix it with the iterable WeakMap approach. Problem two can also exist for destructors as well.

All of this invokes several levels of hell so I would suggest to try to work around it with good program design, good practices, avoiding certain things, etc. It can be frustrating in JS however because of how flexible it is in certain aspects and because it is more naturally asynchronous and event based with heavy inversion of control.

There is one other solution that is fairly elegant but again still has some potentially serious hangups. If you have a class that extends an observable class you can override the event functions. Add your events to other observables only when events are added to yourself. When all events are removed from you then remove your events from children. You can also make a class to extend your observable class to do this for you. Such a class could provide hooks for empty and non-empty so in a since you would be Observing yourself. This approach isn't bad but also has hangups. There is a complexity increase as well as performance decrease. You'll have to keep a reference to object you observe. Critically, it also will not work for leaves but at least the intermediates will self destruct if you destroy the leaf. It's like chaining destroy but hidden behind calls that you already have to chain. A large performance problem is with this however is that you may have to reinitialise internal data from the Observable everytime your class becomes active. If this process takes a very long time then you might be in trouble.

If you could iterate WeakMap then you could perhaps combine things (switch to Weak when no events, Strong when events) but all that is really doing is putting the performance problem on someone else.

There are also immediate annoyances with iterable WeakMap when it comes to behaviour. I mentioned briefly before about functions having scope references and carving. If I instantiate a child that in the constructor that hooks the listener 'console.log(param)' to parent and fails to persist the parent then when I remove all references to the child it could be freed entirely as the anonymous function added to the parent references nothing from within the child. This leaves the question of what to do about parent.weakmap.add(child, (param) => console.log(param)). To my knowledge the key is weak but not the value so weakmap.add(object, object) is persistent. This is something I need to reevaluate though. To me that looks like a memory leak if I dispose all other object references but I suspect in reality it manages that basically by seeing it as a circular reference. Either the anonymous function maintains an implicit reference to objects resulting from parent scopes for consistency wasting a lot of memory or you have behaviour varying based on circumstances which is hard to predict or manage. I think the former is actually impossible. In the latter case if I have a method on a class that simply takes an object and adds console.log it would be freed when I clear the references to the class even if I returned the function and maintained a reference. To be fair this particular scenario is rarely needed legitimately but eventually someone will find an angle and will be asking for a HalfWeakMap which is iterable (free on key and value refs released) but that is unpredictable as well (obj = null magically ending IO, f = null magically ending IO, both doable at incredible distances).

'Use of Unresolved Identifier' in Swift

I did a stupid mistake. I forgot to mention the class as public or open while updating code in cocoapod workspace.

Please do check whether accesor if working in separate workspace.

How to create a string with format?

Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code.

So from my bag of tricks we first need string multiplication for use in indentation.

@inlinable func * (string: String, scalar: Int) -> String {
    let array = [String](repeating: string, count: scalar)
    return array.joined(separator: "")
}

and then the code to add commas.

extension Int {
    @inlinable var withCommas:String {
        var i = self
        var retValue:[String] = []
        while i >= 1000 {
            retValue.append(String(format:"%03d",i%1000))
            i /= 1000
        }
        retValue.append("\(i)")
        return retValue.reversed().joined(separator: ",")
    }

    @inlinable func withCommas(_ count:Int = 0) -> String {
        let retValue = self.withCommas
        let indentation = count - retValue.count
        let indent:String = indentation >= 0 ? " " * indentation : ""

        return indent + retValue
    }
}

I just wrote this last function so I could get the columns to line up.

The @inlinable is great because it takes small functions and reduces their functionality so they run faster.

You can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field.

Now you have something that is pure Swift and does not rely on some old objective C routine for NSString.

Reading JSON from a file?

The json.load() method (without "s" in "load") can read a file directly:

import json

with open('strings.json') as f:
    d = json.load(f)
    print(d)

You were using the json.loads() method, which is used for string arguments only.

Edit: The new message is a totally different problem. In that case, there is some invalid json in that file. For that, I would recommend running the file through a json validator.

There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string?.

What exactly is node.js used for?

From Node.js website

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Event-driven means that the server only reacts when an event occurs. This allow us to create high performance, highly scalable, “real-time” applications.

Finally, this is probably the best article that will get you excited about Node.js

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

I landed here because of an XCTestCase, in which I'd disabled most of the tests by prefixing them with 'no_' as in no_testBackgroundAdding. Once I noticed that most of the answers had something to do with locks and threading, I realized the test contained a few instances of XCTestExpectation with corresponding waitForExpectations. They were all in the disabled tests, but apparently Xcode was still evaluating them at some level.

In the end I found an XCTestExpectation that was defined as @property but lacked the @synthesize. Once I added the synthesize directive, the EXC_BAD_INSTRUCTION disappeared.

How do you access the element HTML from within an Angular attribute directive?

I suggest using Render, as the ElementRef API doc suggests:

... take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker or Universal.

Always use the Renderer for it will make you code (or library you right) be able to work when using Universal or WebWorkers.

import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';

export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
        renderer.setElementProperty(el.nativeElement, 'innerHTML', 'some new value');
    }
}

It doesn't look like Render has a getElementProperty() method though, so I guess we still need to use NativeElement for that part. Or (better) pass the content in as an input property to the directive.

How to use git merge --squash?

What finally cleared this up for me was a comment showing that:

git checkout main
git merge --squash feature

is the equivalent of doing:

git checkout feature
git diff main > feature.patch
git checkout main
patch -p1 < feature.patch
git add .

When I want to merge a feature branch with 105(!!) commits and have them all squashed into one, I don't want to git rebase -i origin/master because I need to separately resolve merge conflicts for each of the intermediate commits (or at least the ones which git can't figure out itself). Using git merge --squash gets me the result I want, of a single commit for merging an entire feature branch. And, I only need to do at most one manual conflict resolution.

Set selected radio from radio group with a value

When you change attribute value like mentioned above the change event is not triggered so if needed for some reasons you can trigger it like so

$('input[name=video_radio][value="' + r.data.video_radio + '"]')
       .prop('checked', true)
       .trigger('change');

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

Hi you can do it this way

    temp = sp.coo_matrix((data, (row, col)), shape=(3, 59))
    temp1 = temp.tocsr()

    #Cosine similarity
    row_sums = ((temp1.multiply(temp1)).sum(axis=1))
    rows_sums_sqrt = np.array(np.sqrt(row_sums))[:,0]
    row_indices, col_indices = temp1.nonzero()
    temp1.data /= rows_sums_sqrt[row_indices]
    temp2 = temp1.transpose()
    temp3 = temp1*temp2

Load local HTML file in a C# WebBrowser

quite late but it's the first hit i found from google

Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:

//using System.IO;  
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);

What does <a href="#" class="view"> mean?

It probably works with Javascript. When you click the link, nothing happens because it points to the current site. The javascript will then load a window or an url. It's used a lot in AJAX web apps.

Swift days between two NSDates

Swift 5

Working, you need to set the time to be the same for both days, if you are off by seconds it will be wrong

func daysBetween(start: Date, end: Date) -> Int {
    let start = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: start)!
    let end = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: end)!
    return Calendar.current.dateComponents([.day], from: start, to: end).day ?? 0
}

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

Case insensitive regular expression without re.compile?

You can also define case insensitive during the pattern compile:

pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Why is nginx responding to any domain name?

I was unable to resolve my problem with any of the other answers. I resolved the issue by checking to see if the host matched and returning a 403 if it did not. (I had some random website pointing to my web servers content. I'm guessing to hijack search rank)

server {
    listen 443;
    server_name example.com;

    if ($host != "example.com") {
        return 403;
    }

    ...
}

Python 3: UnboundLocalError: local variable referenced before assignment

You can fix this by passing parameters rather than relying on Globals

def function(Var1, Var2): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1
function(1, 1)

Accessing SQL Database in Excel-VBA

Suggested changes:

  • Do not invoke the Command object's Execute method;
  • Set the Recordset object's Source property to be your Command object;
  • Invoke the Recordset object's Open method with no parameters;
  • Remove the parentheses from around the Recordset object in the call to CopyFromRecordset;
  • Actually declare your variables :)

Revised code:

Sub GetDataFromADO()

    'Declare variables'
        Dim objMyConn As ADODB.Connection
        Dim objMyCmd As ADODB.Command
        Dim objMyRecordset As ADODB.Recordset

        Set objMyConn = New ADODB.Connection
        Set objMyCmd = New ADODB.Command
        Set objMyRecordset = New ADODB.Recordset

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"    
        objMyConn.Open

    'Set and Excecute SQL Command'
        Set objMyCmd.ActiveConnection = objMyConn
        objMyCmd.CommandText = "select * from mytable"
        objMyCmd.CommandType = adCmdText

    'Open Recordset'
        Set objMyRecordset.Source = objMyCmd
        objMyRecordset.Open

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset

End Sub

Difference between $.ajax() and $.get() and $.load()

Everyone has it right. Functions .load, .get, and .post, are different ways of using the function .ajax.

Personally, I find the .ajax raw function very confusing, and prefer to use load, get, or post as I need it.

POST has the following structure:

$.post(target, post_data, function(response) { });

GET has the following:

$.get(target, post_data, function(response) { });

LOAD has the following:

$(*selector*).load(target, post_data, function(response) { });

As you can see, there are little differences between them, because its the situation that determines which one to use. Need to send the info to a file internally? Use .post (this would be most of the cases). Need to send the info in such a way that you could provide a link to the specific moment? Use .get. Both of them allow a callback where you can handle the response of the files.

An important note is that .load acts in two different manners. If you only provide the url of the target document, it will act as a get (and I say act because I tested checking for $_POST in the called PHP while using default .load behaviour and it detects $_POST, not $_GET; maybe it would be more precise to say it acts as .post without any arguments); however, as http://api.jquery.com/load/ says, once you provide an array of arguments to the function, it will POST the information to the file. Whatever the case is, .load function will directly insert the information into a DOM element, which in MANY cases is very legible, and very direct; but still provides a callback if you want to do something more with the response. Additionally, .load allows you to extract a certain block of code from a file, giving you the possibility to save a catalog, for example, in a html file, and retrieve pieces of it (items) directly into DOM elements.

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

WAMP won't turn green. And the VCRUNTIME140.dll error

WAMP is not turning GREEN? Don`t panic

First of all check your windows update by searching "Windows Update"

or

Download updates from microsoft windows site (i had windows 7 x64 updated to service pack 1 full) windows 7 Service pack 1 download

Now there are some more downloads that support WAMP for installing time

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

VC9 Packages (Visual C++ 2008 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=5582 https://www.microsoft.com/en-us/download/details.aspx?id=2092

VC10 Packages (Visual C++ 2010 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=8328 https://www.microsoft.com/en-us/download/details.aspx?id=13523

VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679

VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe

VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685

VC Packages x64 (Visual C++ 2017)

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

Android Saving created bitmap to directory on sd card

just change the extension to .bmp.

Do this:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);

//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.bmp")

It'll sound that I'm just fooling around, but try it once and it'll get saved in BMP format. Cheers!

Changing the interval of SetInterval while it's running

This is my way of doing this, i use setTimeout:

var timer = {
    running: false,
    iv: 5000,
    timeout: false,
    cb : function(){},
    start : function(cb,iv){
        var elm = this;
        clearInterval(this.timeout);
        this.running = true;
        if(cb) this.cb = cb;
        if(iv) this.iv = iv;
        this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
    },
    execute : function(e){
        if(!e.running) return false;
        e.cb();
        e.start();
    },
    stop : function(){
        this.running = false;
    },
    set_interval : function(iv){
        clearInterval(this.timeout);
        this.start(false, iv);
    }
};

Usage:

timer.start(function(){
    console.debug('go');
}, 2000);

timer.set_interval(500);

timer.stop();

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

I faced the same problem on Mac OS X and with Miniconda. After trying many of the proposed solutions for hours I found that I needed to correctly set Condas environment – specifically requests environment variable – to use the Root certificate that my company provided rather than the generic ones that Conda provides.

Here is how I solved it:

  1. Open Chrome, got to any website, click on the lock icon on the left of the URL. Click on «Certificate» on the dropdown. In the next window you see a stack of certificates. The uppermost (aka top line in window) is the root certificate (e.g. Zscaler Root CA in my case, yours will very likely be a different one).

enter image description here

  1. Open Mac OS keychain, click on «Certificates» and choose among the many certificates the root certificate that you just identified. Export this to any folder of your choosing.
  2. Convert this certificate with openssl: openssl x509 -inform der -in /path/to/your/certificate.cer -out /path/to/converted/certificate.pem
  3. For a quick check set your shell to acknowledge the certificate: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem
  4. To set this permanently open your shell profile (.bshrs or e.g. .zshrc) and add this line: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem. Now exit your terminal/shell and reopen. Check again.

You should be set and Conda should work fine.

Uses of content-disposition in an HTTP response header

For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition

Basic usage:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());

How can I clear event subscriptions in C#?

This is my solution:

public class Foo : IDisposable
{
    private event EventHandler _statusChanged;
    public event EventHandler StatusChanged
    {
        add
        {
            _statusChanged += value;
        }
        remove
        {
            _statusChanged -= value;
        }
    }

    public void Dispose()
    {
        _statusChanged = null;
    }
}

You need to call Dispose() or use using(new Foo()){/*...*/} pattern to unsubscribe all members of invocation list.

How to convert String into Hashmap in java

String value = "{first_name = naresh,last_name = kumar,gender = male}"

Let's start

  1. Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
  2. Split the String from ,>> array of 3 element
  3. Now you have an array with 3 element
  4. Iterate the array and split each element by =
  5. Create a Map<String,String> put each part separated by =. first part as Key and second part as Value

Limiting the output of PHP's echo to 200 characters

In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.

function the_excerpt(string $text,int $length){
    if(strlen($text) > $length){$text = substr($text,0,$length);}
    return $text; 
}

macOS on VMware doesn't recognize iOS device

The other answer is lacking some additional information also in the following post. For example, when the iPhone keep Connect / Disconnect in loop. So here is a better solution:

  1. In vmware.log search the vid & pid of your iphone USB:
    Example:

    vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:12a8
    
  2. Close vmware (to unlock .vmx)

  3. In the .vmx, add:

    usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"  
    

    Replace 0xvid:0xpid by the vid & pid found in vmware.log. Example:

    usb.quirks.device0 = "0x05ac:0x12a8 skip-reset, skip-refresh, skip-setconfig"
    
  4. In vmware > Edit virtual machine > USB Controller : USB compatibility : USB 2.0
    Active : Automatically connect new USB Devices
    Active : Show all USB input devices
    Active : Share Bluetooth devices with the virtual Machine

  5. Launch Mac OS and make sure that the mouse is Focus on vmware (or just use the login prompt if it appear)

Is there any difference between GROUP BY and DISTINCT

GROUP BY lets you use aggregate functions, like AVG, MAX, MIN, SUM, and COUNT. On the other hand DISTINCT just removes duplicates.

For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like:

SELECT department, SUM(amount) FROM purchases GROUP BY department

This will give you one row per department, containing the department name and the sum of all of the amount values in all rows for that department.

android.content.res.Resources$NotFoundException: String resource ID #0x0

You can do it. this is a easy way.

txtTopicNo.setText(10+"");

How do you give iframe 100% height

The problem with iframes not getting 100% height is not because they're unwieldy. The problem is that for them to get 100% height they need their parents to have 100% height. If one of the iframe's parents is not 100% tall the iframe won't be able to go beyond that parent's height.

So the best possible solution would be:

html, body, iframe { height: 100%; }

…given the iframe is directly under body. If the iframe has a parent between itself and the body, the iframe will still get the height of its parent. One must explicitly set the height of every parent to 100% as well (if that's what one wants).

Tested in:

Chrome 30, Firefox 24, Safari 6.0.5, Opera 16, IE 7, 8, 9 and 10

PS: I don't mean to be picky but the solution marked as correct doesn't work on Firefox 24 at the time of this writing, but worked on Chrome 30. Haven't tested on other browsers though. I came across the error on Firefox because the page I was testing had very little content... It could be it's my meager markup or the CSS reset altering the output, but if I experienced this error I guess the accepted answer doesn't work in every situation.

Update 2021

@Zeni suggested this in 2015:

iframe { height: 100vh }

...and indeed it does the trick!

Careful with positioning as it can potentially break the effect. Test thoroughly, you might not need positioning depending of what you're trying to achieve.

Dynamically Add C# Properties at Runtime

Have you taken a look at ExpandoObject?

see: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

From MSDN:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Allowing you to do cool things like:

dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
    {
        Console.WriteLine(msg);
    };

dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);

Based on your actual code you may be more interested in:

public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
    return new MyDynObject(properties);
}

public sealed class MyDynObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;

    public MyDynObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }

    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

That way you just need:

var dyn = GetDynamicObject(new Dictionary<string, object>()
    {
        {"prop1", 12},
    });

Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;

Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.

jQuery textbox change event doesn't fire until textbox loses focus?

Binding to both events is the typical way to do it. You can also bind to the paste event.

You can bind to multiple events like this:

$("#textbox").on('change keyup paste', function() {
    console.log('I am pretty sure the text box changed');
});

If you wanted to be pedantic about it, you should also bind to mouseup to cater for dragging text around, and add a lastValue variable to ensure that the text actually did change:

var lastValue = '';
$("#textbox").on('change keyup paste mouseup', function() {
    if ($(this).val() != lastValue) {
        lastValue = $(this).val();
        console.log('The text box really changed this time');
    }
});

And if you want to be super duper pedantic then you should use an interval timer to cater for auto fill, plugins, etc:

var lastValue = '';
setInterval(function() {
    if ($("#textbox").val() != lastValue) {
        lastValue = $("#textbox").val();
        console.log('I am definitely sure the text box realy realy changed this time');
    }
}, 500);

Where to find 64 bit version of chromedriver.exe for Selenium WebDriver?

There is no separate 64-bit version of Chromedriver. The version available at https://sites.google.com/a/chromium.org/chromedriver/downloads works on both 32 and 64-bit Windows, against either 32-or 64-bit Chrome.

This was confirmed in the Chromedriver issue tracker: https://bugs.chromium.org/p/chromedriver/issues/detail?id=1797#c1

Yes, Chromedriver works on 64-bit Windows and against 64-bit Chrome successfully.

I came here while searching for the answer to if it works on 64-bit Chrome following the announcement that from version 58 Chrome will default to 64-bit on Windows provided certain conditions are met:
https://chromereleases.googleblog.com/2017/05/stable-channel-update-for-desktop.html

In order to improve stability, performance, and security, users who are currently on 32-bit version of Chrome, and 64-bit Windows with 4GB or more of memory and auto-update enabled will be automatically migrated to 64-bit Chrome during this update. 32-bit Chrome will still be available via the Chrome download page.

Can I inject a service into a directive in AngularJS?

Change your directive definition from app.module to app.directive. Apart from that everything looks fine. Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.

It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.

http://plnkr.co/edit/M8omDEjvPvBtrBHM84Am

How to process SIGTERM signal gracefully?

First, I'm not certain that you need a second thread to set the shutdown_flag.
Why not set it directly in the SIGTERM handler?

An alternative is to raise an exception from the SIGTERM handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with/contextmanager and try: ... finally: blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.

Example program signals-test.py:

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

Now see the Ctrl+C behaviour:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

This time I send it SIGTERM after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}'):

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

This time I enable my custom SIGTERM handler and send it SIGTERM:

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0

How to run console application from Windows Service?

I have a Windows service, and I added the following line to the constructor for my service:

using System.Diagnostics;
try {
    Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
    Debugger.Break();
}

When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.

But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.

How to execute a program or call a system command from Python

import os
cmd = 'ls -al'
os.system(cmd)

If you want to return the results of the command, you can use os.popen. However, this is deprecated since version 2.6 in favor of the subprocess module, which other answers have covered well.

TypeError: module.__init__() takes at most 2 arguments (3 given)

Your error is happening because Object is a module, not a class. So your inheritance is screwy.

Change your import statement to:

from Object import ClassName

and your class definition to:

class Visitor(ClassName):

or

change your class definition to:

class Visitor(Object.ClassName):
   etc

What does auto do in margin:0 auto?

When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;

Which would give:

margin-left:25;
margin-right:25;

Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

How to make an ImageView with rounded corners?

If any of you are facing this problem

enter image description here

Most probably , you are using Android Studio. Due to image re-size and all in Android Studio ,you may encounter this problem. An easy fix to this problem is to decrease the radius of circle in drawCircle(). In my case i use this fix

Using canvas.drawCircle(100, 100, 90, paint); instead of canvas.drawCircle(100, 100, 100, paint); this will definitely solve your problem.

Here is finally edited code:-

  public class Profile extends ActionBarActivity {


    TextView username;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);


        username= (TextView) findViewById(R.id.txt);

        String recievedusername=getIntent().getExtras().getString("toname");
        username.setText(recievedusername);


        Bitmap bm = BitmapFactory.decodeResource(getResources(),
                R.mipmap.gomez);

        Bitmap resizedBitmap = Bitmap.createScaledBitmap(bm, 200,200, false);
        Bitmap conv_bm=getCircleBitmap(resizedBitmap,100);
        // set circle bitmap
        ImageView mImage = (ImageView) findViewById(R.id.profile_image);
        mImage.setImageBitmap(conv_bm);
        // TODO Auto-generated method stub
    }
    private Bitmap getCircleBitmap(Bitmap bitmap , int pixels) {
        final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(),bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(100,100, 90, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        bitmap.recycle();
        return output;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_apploud, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_addnew) {
            Intent i;
            i=new Intent(Profile.this,ApplaudSomeone.class);
            startActivity(i);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

What algorithms compute directions from point A to point B on a map?

I've done this quite a lot of times, actually, trying several different methods. Depending on the size (geographical) of the map, you might want to consider using the haversine function as a heuristic.

The best solution I've made was using A* with a straight line distance as a heuristic function. But then you need some sort of coordinates for each point (intersection or vertex) on the map. You can also try different weightings for the heuristic function, i.e.

f(n) = k*h(n) + g(n)

where k is some constant greater than 0.

Remove the complete styling of an HTML button/submit

Your question says "Internet Explorer," but for those interested in other browsers, you can now use all: unset on buttons to unstyle them.

It doesn't work in IE, but it's well-supported everywhere else.

https://caniuse.com/#feat=css-all

Old Safari color warning: Setting the text color of the button after using all: unset can fail in Safari 13.1, due to a bug in WebKit. (The bug is fixed in Safari 14 and up.) "all: unset is setting -webkit-text-fill-color to black, and that overrides color." If you need to set text color after using all: unset, be sure to set both the color and the -webkit-text-fill-color to the same color.

Accessibility warning: For the sake of users who aren't using a mouse pointer, be sure to re-add some :focus styling, e.g. button:focus { outline: orange auto 5px } for keyboard accessibility.

And don't forget cursor: pointer. all: unset removes all styling, including the cursor: pointer, which makes your mouse cursor look like a pointing hand when you hover over the button. You almost certainly want to bring that back.

_x000D_
_x000D_
button {
  all: unset;
  color: blue;
  -webkit-text-fill-color: blue;
  cursor: pointer;
}

button:focus {
  outline: orange 5px auto;
}
_x000D_
<button>check it out</button>
_x000D_
_x000D_
_x000D_

Date vs DateTime

Unfortunately, not in the .Net BCL. Dates are usually represented as a DateTime object with the time set to midnight.

As you can guess, this means that you have all the attendant timezone issues around it, even though for a Date object you'd want absolutely no timezone handling.

Is it possible to focus on a <div> using JavaScript focus() function?

window.location.hash = '#tries';

This will scroll to the element in question, essentially "focus"ing it.

What is a CSRF token? What is its importance and how does it work?

The Cloud Under blog has a good explanation of CSRF tokens. (archived)

Imagine you had a website like a simplified Twitter, hosted on a.com. Signed in users can enter some text (a tweet) into a form that’s being sent to the server as a POST request and published when they hit the submit button. On the server the user is identified by a cookie containing their unique session ID, so your server knows who posted the Tweet.

The form could be as simple as that:

 <form action="http://a.com/tweet" method="POST">
   <input type="text" name="tweet">
   <input type="submit">
 </form> 

Now imagine, a bad guy copies and pastes this form to his malicious website, let’s say b.com. The form would still work. As long

as a user is signed in to your Twitter (i.e. they’ve got a valid session cookie for a.com), the POST request would be sent to http://a.com/tweet and processed as usual when the user clicks the submit button.

So far this is not a big issue as long as the user is made aware about what the form exactly does, but what if our bad guy tweaks the form like this:

 <form action="https://example.com/tweet" method="POST">
   <input type="hidden" name="tweet" value="Buy great products at http://b.com/#iambad">
   <input type="submit" value="Click to win!">
 </form> 

Now, if one of your users ends up on the bad guy’s website and hits the “Click to win!” button, the form is submitted to

your website, the user is correctly identified by the session ID in the cookie and the hidden Tweet gets published.

If our bad guy was even worse, he would make the innocent user submit this form as soon they open his web page using JavaScript, maybe even completely hidden away in an invisible iframe. This basically is cross-site request forgery.

A form can easily be submitted from everywhere to everywhere. Generally that’s a common feature, but there are many more cases where it’s important to only allow a form being submitted from the domain where it belongs to.

Things are even worse if your web application doesn’t distinguish between POST and GET requests (e.g. in PHP by using $_REQUEST instead of $_POST). Don’t do that! Data altering requests could be submitted as easy as <img src="http://a.com/tweet?tweet=This+is+really+bad">, embedded in a malicious website or even an email.

How do I make sure a form can only be submitted from my own website? This is where the CSRF token comes in. A CSRF token is a random, hard-to-guess string. On a page with a form you want to protect, the server would generate a random string, the CSRF token, add it to the form as a hidden field and also remember it somehow, either by storing it in the session or by setting a cookie containing the value. Now the form would look like this:

    <form action="https://example.com/tweet" method="POST">
      <input type="hidden" name="csrf-token" value="nc98P987bcpncYhoadjoiydc9ajDlcn">
      <input type="text" name="tweet">
      <input type="submit">
    </form> 

When the user submits the form, the server simply has to compare the value of the posted field csrf-token (the name doesn’t

matter) with the CSRF token remembered by the server. If both strings are equal, the server may continue to process the form. Otherwise the server should immediately stop processing the form and respond with an error.

Why does this work? There are several reasons why the bad guy from our example above is unable to obtain the CSRF token:

Copying the static source code from our page to a different website would be useless, because the value of the hidden field changes with each user. Without the bad guy’s website knowing the current user’s CSRF token your server would always reject the POST request.

Because the bad guy’s malicious page is loaded by your user’s browser from a different domain (b.com instead of a.com), the bad guy has no chance to code a JavaScript, that loads the content and therefore our user’s current CSRF token from your website. That is because web browsers don’t allow cross-domain AJAX requests by default.

The bad guy is also unable to access the cookie set by your server, because the domains wouldn’t match.

When should I protect against cross-site request forgery? If you can ensure that you don’t mix up GET, POST and other request methods as described above, a good start would be to protect all POST requests by default.

You don’t have to protect PUT and DELETE requests, because as explained above, a standard HTML form cannot be submitted by a browser using those methods.

JavaScript on the other hand can indeed make other types of requests, e.g. using jQuery’s $.ajax() function, but remember, for AJAX requests to work the domains must match (as long as you don’t explicitly configure your web server otherwise).

This means, often you do not even have to add a CSRF token to AJAX requests, even if they are POST requests, but you will have to make sure that you only bypass the CSRF check in your web application if the POST request is actually an AJAX request. You can do that by looking for the presence of a header like X-Requested-With, which AJAX requests usually include. You could also set another custom header and check for its presence on the server side. That’s safe, because a browser would not add custom headers to a regular HTML form submission (see above), so no chance for Mr Bad Guy to simulate this behaviour with a form.

If you’re in doubt about AJAX requests, because for some reason you cannot check for a header like X-Requested-With, simply pass the generated CSRF token to your JavaScript and add the token to the AJAX request. There are several ways of doing this; either add it to the payload just like a regular HTML form would, or add a custom header to the AJAX request. As long as your server knows where to look for it in an incoming request and is able to compare it to the original value it remembers from the session or cookie, you’re sorted.

Angular + Material - How to refresh a data source (mat-table)

// this is the dataSource
this.guests = [];

this.guests.push({id: 1, name: 'Ricardo'});

// refresh the dataSource this.guests = Array.from(this.guest);

Remove all spaces from a string in SQL Server

I had this issue today and replace / trim did the trick..see below.

update table_foo 
set column_bar  = REPLACE(LTRIM(RTRIM(column_bar)), '  ', '')

before and after :

old-bad:  column_bar    |   New-fixed:   column_bar
       '  xyz  '        |                'xyz'   
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 

.war vs .ear file

Ear files provide more options to configure the interaction with the application server.

For example: if the hibernate version of the application server is older than the one provided by your dependencies, you can add the following to ear-deployer-jboss-beans.xml for JBOSS to isolate classloaders and avoid conflicts:

<bean name="EARClassLoaderDeployer" class="org.jboss.deployment.EarClassLoaderDeployer">    
  <property name="isolated">true</property>
</bean>

or to src/main/application/META-INF/jboss-app.xml :

<?xml version="1.0"?>
<jboss-app>
<loader-repository>
    loader=nameofyourear.ear
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>
</jboss-app> 

This will make sure that there is no classloader conflict between your application and the application server.

Normally the classloader mechanism works like this:

When a class loading request is presented to a class loader, it first asks its parent class loader to fulfill the request. The parent, in turn, asks its parent for the class until the request reaches the top of the hierarchy. If the class loader at the top of the hierarchy cannot fulfill the request, then the child class loader that called it is responsible for loading the class.

By isolating the classloaders, your ear classloader will not look in the parent (=JBoss / other AS classloader). As far is I know, this is not possible with war files.