Programs & Examples On #Pagemethods

Page Methods are functions in the code-behind file for an ASP.net WebForms page that can be invoked from Web Services or AJAX. They are decorated with the [WebMethod] attribute and marked with the static keyword (Shared in VB.NET).

Check if key exists in JSON object using jQuery

if you have an array

var subcategories=[{name:"test",desc:"test"}];

function hasCategory(nameStr) {
        for(let i=0;i<subcategories.length;i++){
            if(subcategories[i].name===nameStr){
                return true;
            }
        }
        return false;
    }

if you have an object

var category={name:"asd",test:""};

if(category.hasOwnProperty('name')){//or category.name!==undefined
   return true;
}else{
   return false;
}

Setting Curl's Timeout in PHP

You can't run the request from a browser, it will timeout waiting for the server running the CURL request to respond. The browser is probably timing out in 1-2 minutes, the default network timeout.

You need to run it from the command line/terminal.

How do I initialize a TypeScript Object with a JSON-Object?

TLDR: TypedJSON (working proof of concept)


The root of the complexity of this problem is that we need to deserialize JSON at runtime using type information that only exists at compile time. This requires that type-information is somehow made available at runtime.

Fortunately, this can be solved in a very elegant and robust way with decorators and ReflectDecorators:

  1. Use property decorators on properties which are subject to serialization, to record metadata information and store that information somewhere, for example on the class prototype
  2. Feed this metadata information to a recursive initializer (deserializer)

 

Recording Type-Information

With a combination of ReflectDecorators and property decorators, type information can be easily recorded about a property. A rudimentary implementation of this approach would be:

function JsonMember(target: any, propertyKey: string) {
    var metadataFieldKey = "__propertyTypes__";

    // Get the already recorded type-information from target, or create
    // empty object if this is the first property.
    var propertyTypes = target[metadataFieldKey] || (target[metadataFieldKey] = {});

    // Get the constructor reference of the current property.
    // This is provided by TypeScript, built-in (make sure to enable emit
    // decorator metadata).
    propertyTypes[propertyKey] = Reflect.getMetadata("design:type", target, propertyKey);
}

For any given property, the above snippet will add a reference of the constructor function of the property to the hidden __propertyTypes__ property on the class prototype. For example:

class Language {
    @JsonMember // String
    name: string;

    @JsonMember// Number
    level: number;
}

class Person {
    @JsonMember // String
    name: string;

    @JsonMember// Language
    language: Language;
}

And that's it, we have the required type-information at runtime, which can now be processed.

 

Processing Type-Information

We first need to obtain an Object instance using JSON.parse -- after that, we can iterate over the entires in __propertyTypes__ (collected above) and instantiate the required properties accordingly. The type of the root object must be specified, so that the deserializer has a starting-point.

Again, a dead simple implementation of this approach would be:

function deserialize<T>(jsonObject: any, Constructor: { new (): T }): T {
    if (!Constructor || !Constructor.prototype.__propertyTypes__ || !jsonObject || typeof jsonObject !== "object") {
        // No root-type with usable type-information is available.
        return jsonObject;
    }

    // Create an instance of root-type.
    var instance: any = new Constructor();

    // For each property marked with @JsonMember, do...
    Object.keys(Constructor.prototype.__propertyTypes__).forEach(propertyKey => {
        var PropertyType = Constructor.prototype.__propertyTypes__[propertyKey];

        // Deserialize recursively, treat property type as root-type.
        instance[propertyKey] = deserialize(jsonObject[propertyKey], PropertyType);
    });

    return instance;
}
var json = '{ "name": "John Doe", "language": { "name": "en", "level": 5 } }';
var person: Person = deserialize(JSON.parse(json), Person);

The above idea has a big advantage of deserializing by expected types (for complex/object values), instead of what is present in the JSON. If a Person is expected, then it is a Person instance that is created. With some additional security measures in place for primitive types and arrays, this approach can be made secure, that resists any malicious JSON.

 

Edge Cases

However, if you are now happy that the solution is that simple, I have some bad news: there is a vast number of edge cases that need to be taken care of. Only some of which are:

  • Arrays and array elements (especially in nested arrays)
  • Polymorphism
  • Abstract classes and interfaces
  • ...

If you don't want to fiddle around with all of these (I bet you don't), I'd be glad to recommend a working experimental version of a proof-of-concept utilizing this approach, TypedJSON -- which I created to tackle this exact problem, a problem I face myself daily.

Due to how decorators are still being considered experimental, I wouldn't recommend using it for production use, but so far it served me well.

Cell spacing in UICollectionView

I have tried iago849's answer and it worked.

Swift 4

open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    guard let answer = super.layoutAttributesForElements(in: rect) else {
        return nil
    }
    let count = answer.count
    for i in 1..<count {
        let currentLayoutAttributes = answer[i]
        let prevLayoutAttributes = answer[i-1]
        let origin = prevLayoutAttributes.frame.maxX
        if (origin + CGFloat(spacing) + currentLayoutAttributes.frame.size.width) < self.collectionViewContentSize.width && currentLayoutAttributes.frame.origin.x > prevLayoutAttributes.frame.origin.x {
            var frame = currentLayoutAttributes.frame
            frame.origin.x = origin + CGFloat(spacing)
            currentLayoutAttributes.frame = frame
        }
    }
    return answer
}

Here is the link for the github project. https://github.com/vishalwaka/MultiTags

Clear back stack using fragments

It is working for me,try this one:

public void clearFragmentBackStack() {
        FragmentManager fm = getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount() - 1; i++) {
            fm.popBackStack();
        }
    }

How do I Merge two Arrays in VBA?

This function will do as JohnFx suggested and allow for varied lengths on the arrays

Function mergeArrays(ByVal arr1 As Variant, ByVal arr2 As Variant) As Variant
    Dim holdarr As Variant
    Dim ub1 As Long
    Dim ub2 As Long
    Dim bi As Long
    Dim i As Long
    Dim newind As Long

        ub1 = UBound(arr1) + 1
        ub2 = UBound(arr2) + 1

        bi = IIf(ub1 >= ub2, ub1, ub2)

        ReDim holdarr(ub1 + ub2 - 1)

        For i = 0 To bi
            If i < ub1 Then
                holdarr(newind) = arr1(i)
                newind = newind + 1
            End If

            If i < ub2 Then
                holdarr(newind) = arr2(i)
                newind = newind + 1
            End If
        Next i

        mergeArrays = holdarr
End Function

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

nVarchar2 is a Unicode-only storage.

Though both data types are variable length String datatypes, you can notice the difference in how they store values. Each character is stored in bytes. As we know, not all languages have alphabets with same length, eg, English alphabet needs 1 byte per character, however, languages like Japanese or Chinese need more than 1 byte for storing a character.

When you specify varchar2(10), you are telling the DB that only 10 bytes of data will be stored. But, when you say nVarchar2(10), it means 10 characters will be stored. In this case, you don't have to worry about the number of bytes each character takes.

How to downgrade or install an older version of Cocoapods

PROMPT> gem uninstall cocoapods

Select gem to uninstall:
 1. cocoapods-0.32.1
 2. cocoapods-0.33.1
 3. cocoapods-0.36.0.beta.2
 4. cocoapods-0.38.2
 5. cocoapods-0.39.0
 6. cocoapods-1.0.0
 7. All versions
> 6
Successfully uninstalled cocoapods-1.0.0
PROMPT> gem install cocoapods -v 0.39.0
Successfully installed cocoapods-0.39.0
Parsing documentation for cocoapods-0.39.0
Done installing documentation for cocoapods after 1 seconds
1 gem installed
PROMPT> pod --version
0.39.0
PROMPT>

HashMap get/put complexity

It has already been mentioned that hashmaps are O(n/m) in average, if n is the number of items and m is the size. It has also been mentioned that in principle the whole thing could collapse into a singly linked list with O(n) query time. (This all assumes that calculating the hash is constant time).

However what isn't often mentioned is, that with probability at least 1-1/n (so for 1000 items that's a 99.9% chance) the largest bucket won't be filled more than O(logn)! Hence matching the average complexity of binary search trees. (And the constant is good, a tighter bound is (log n)*(m/n) + O(1)).

All that's required for this theoretical bound is that you use a reasonably good hash function (see Wikipedia: Universal Hashing. It can be as simple as a*x>>m). And of course that the person giving you the values to hash doesn't know how you have chosen your random constants.

TL;DR: With Very High Probability the worst case get/put complexity of a hashmap is O(logn).

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

make sure you're using the newest jquery, and problem solved

I met this problem with this code:

<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

After change it to this:

<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

It works fine

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    return Task.Run(() =>
    {
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
    }      
}

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

JQuery style display value

Just call css with one argument

  $('#idDetails').css('display');

If I understand your question. Otherwise, you want cletus' answer.

Why does Google prepend while(1); to their JSON responses?

As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]

This attack can be achieved in 3 major steps:

Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

<script src="http://<jsonsite>/json_server.php"></script>

The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

Object.prototype.__defineSetter__('ccnum',function(obj){

secrets =secrets.concat(" ", obj);

});

At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

There are several ways in which JSON Hijacking can be prevented:

  • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

  • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

  • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

*

Blurry text after using CSS transform: scale(); in Chrome

I was facing the blurry text issue on Chrome but not on Firefox when I used transform: translate(-50%,-50%).

Well, I really tried a lot of workarounds like:

transform: perspective(1px);
filter: blur(0);
transform: translateZ(0);
backface-visibility: hidden;

None of these worked to me.

Finally, I made the height and width of the element even. It resolved the issue for me!!!

Note: It might depend from use case to use case. But surely worth a try!

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

This occurred when trying to connect to the WCF Service using only host name e.g. https://host/MyService.svc while using a certificate tied to a name e.g. host.mysite.com.

Switching to the https://host.mysite.com/MyService.svc and this resolved it.

Display animated GIF in iOS

#import <QuickLook/QuickLook.h>
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    QLPreviewController *preview = [[QLPreviewController alloc] init];
    preview.dataSource = self;

    [self addChildViewController:preview];
    [self.view addSubview:preview.view];
}

#pragma mark - QLPreviewControllerDataSource

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController
{
    return 1;
}

- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx
{
    NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myanimated.gif" ofType:nil]];
    return fileURL;
}

@end

Reducing video size with same format and reducing frame size

There is an application for both Mac & Windows call Handbrake, i know this isn't command line stuff but for a quick open file - select output file format & rough output size whilst keeping most of the good stuff about the video then this is good, it's a just a graphical view of ffmpeg at its best ... It does support command line input for those die hard texters.. https://handbrake.fr/downloads.php

What is the difference between a static method and a non-static method?

Static method example

class StaticDemo
{

 public static void copyArg(String str1, String str2)
    {
       str2 = str1;
       System.out.println("First String arg is: "+str1);
       System.out.println("Second String arg is: "+str2);
    }
    public static void main(String agrs[])
    {
      //StaticDemo.copyArg("XYZ", "ABC");
      copyArg("XYZ", "ABC");
    }
}

Output:

First String arg is: XYZ

Second String arg is: XYZ

As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.

Non-static method example

class Test
{
    public void display()
    {
       System.out.println("I'm non-static method");
    }
    public static void main(String agrs[])
    {
       Test obj=new Test();
       obj.display();
    }
}

Output:

I'm non-static method

A non-static method is always be called by using the object of class as shown in the above example.

Key Points:

How to call static methods: direct or using class name:

StaticDemo.copyArg(s1, s2);

or

copyArg(s1, s2);

How to call a non-static method: using object of the class:

Test obj = new Test();

How do I modify a MySQL column to allow NULL?

Under some circumstances (if you get "ERROR 1064 (42000): You have an error in your SQL syntax;...") you need to do

ALTER TABLE mytable MODIFY mytable.mycolumn varchar(255);

How to replace multiple strings in a file using PowerShell

Assuming you can only have one 'something1' or 'something2', etc. per line, you can use a lookup table:

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line -replace $_.Key, $_.Value
            break
        }
    }
} | Set-Content -Path $destination_file

If you can have more than one of those, just remove the break in the if statement.

How to get the selected radio button’s value?

In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:

var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);

or simpler:

alert(document.theForm.genderS.value);

refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How do I call ::CreateProcess in c++ to launch a Windows executable?

If you application is a Windows GUI application then using the code below to do the waiting is not ideal as messages for your application will not be getting processing. To the user it will look like your application has hung.

WaitForSingleObject(&processInfo.hProcess, INFINITE)

Something like the untested code below might be better as it will keep processing the windows message queue and your application will remain responsive:

//-- wait for the process to finish
while (true)
{
  //-- see if the task has terminated
  DWORD dwExitCode = WaitForSingleObject(ProcessInfo.hProcess, 0);

  if (   (dwExitCode == WAIT_FAILED   )
      || (dwExitCode == WAIT_OBJECT_0 )
      || (dwExitCode == WAIT_ABANDONED) )
  {
    DWORD dwExitCode;

    //-- get the process exit code
    GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode);

    //-- the task has ended so close the handle
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);

    //-- save the exit code
    lExitCode = dwExitCode;

    return;
  }
  else
  {
    //-- see if there are any message that need to be processed
    while (PeekMessage(&message.msg, 0, 0, 0, PM_NOREMOVE))
    {
      if (message.msg.message == WM_QUIT)
      {
        return;
      }

      //-- process the message queue
      if (GetMessage(&message.msg, 0, 0, 0))
      {
        //-- process the message
        TranslateMessage(&pMessage->msg);
        DispatchMessage(&pMessage->msg);
      }
    }
  }
}

How to change background color in the Notepad++ text editor?

If anyone wants to enable dark mode, you may follow the below steps

  • Open your Notepad++, and select “Settings” on the menu bar, and choose “Style configurator”.
  • Select theme “Obsidian” (you can choose other dark themes)
  • Click on Save&Colse

enter image description here

Winforms issue - Error creating window handle

I think it's normally related to the computer running out of memory so it's not able to create any more window handles. Normally windows starts to show some strange behavior at this point as well.

How to upload a project to Github

What you need it an SSH connection and GitHub init into your project. I will explain under Linux machine.

Let's start with some easy stuff: navigate into your project in the terminal, and use:

git init
git add .
git commit 

now let's add SSH into your machine: use ssh-keygen -t rsa -C "[email protected]" and copy the public key, then add it to your GitHub repo Deploy keys -> add one back to your machine project now launch: git push origin master if there is an error config your .github/config by nano .github/config and change the URL to ssh one by url = [email protected]:username/repo.... and that's it

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

Works for Navigation Based Application

    var addStatusBar = UIView()
    addStatusBar.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 20);
    addStatusBar.backgroundColor = global().UIColorFromRGB(0x65b4d9)
    self.window?.rootViewController?.view .addSubview(addStatusBar)

What is the Ruby <=> (spaceship) operator?

What is <=> ( The 'Spaceship' Operator )

According to the RFC that introduced the operator, $a <=> $b

 -  0 if $a == $b
 - -1 if $a < $b
 -  1 if $a > $b

 - Return 0 if values on either side are equal
 - Return 1 if value on the left is greater
 - Return -1 if the value on the right is greater

Example:

//Comparing Integers

echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1

//String Comparison

echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1

MORE:

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

How can I divide two integers to get a double?

Complementing the @NoahD's answer

To have a greater precision you can cast to decimal:

(decimal)100/863
//0.1158748551564310544611819235

Or:

Decimal.Divide(100, 863)
//0.1158748551564310544611819235

Double are represented allocating 64 bits while decimal uses 128

(double)100/863
//0.11587485515643106

In depth explanation of "precision"

For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats and doubles and this one where he talks about decimals.

How to add "active" class to wp_nav_menu() current menu item (simple way)

To also highlight the menu item when one of the child pages is active, also check for the other class (current-page-ancestor) like below:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

Git: How to pull a single file from a server repository in Git?

It is possible to do (in the deployed repository):

git fetch
// git fetch will download all the recent changes, but it will not put it in your current checked out code (working area).

Followed by:

git checkout origin/master -- path/to/file
// git checkout <local repo name (default is origin)>/<branch name> -- path/to/file will checkout the particular file from the downloaded changes (origin/master).

Change directory command in Docker?

You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.

In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

javascript regex - look behind alternative?

^(?!filename).+\.js works for me

tested against:

  • test.js match
  • blabla.js match
  • filename.js no match

A proper explanation for this regex can be found at Regular expression to match string not containing a word?

Look ahead is available since version 1.5 of javascript and is supported by all major browsers

Updated to match filename2.js and 2filename.js but not filename.js

(^(?!filename\.js$).).+\.js

Getting the name / key of a JToken with JSON.net

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}

Using Application context everywhere?

Application Class:

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getAppContext() {
        return mContext;
    }

}

Declare the Application in the AndroidManifest:

<application android:name=".MyApplication"
    ...
/>

Usage:

MyApplication.getAppContext()

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

@koby's answer doesn't work for me, so I make a little change.

cd ~/.ssh
chmod 700 id_rsa.pub

This works well for me on Mac.

Find IP address of directly connected device

To use DHCP, you'd have to run a DHCP server on the primary and a client on the secondary; the primary could then query the server to find out what address it handed out. Probably overkill.

I can't help you with Windows directly. On Unix, the "arp" command will tell you what IP addresses are known to be attached to the local ethernet segment. Windows will have this same information (since it's a core part of the IP/Ethernet interface) but I don't know how you get at it.

Of course, the networking stack will only know about the other host if it has previously seen traffic from it. You may have to first send a broadcast packet on the interface to elicit some sort of response and thus populate the local ARP table.

Check if an element is present in a Bash array

1) Initialize array arr and add elements

2) set variable to search for SEARCH_STRING

3) check if your array contains element

arr=()
arr+=('a')
arr+=('b')
arr+=('c')

SEARCH_STRING='b'

if [[ " ${arr[*]} " == *"$SEARCH_STRING"* ]];
then
    echo "YES, your arr contains $SEARCH_STRING"
else
    echo "NO, your arr does not contain $SEARCH_STRING"
fi

ReactJS: setTimeout() not working?

setTimeout(() => {
  this.setState({ position: 1 });
}, 3000);

The above would also work because the ES6 arrow function does not change the context of this.

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

Alphabet range in Python

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

If you really need a list:

>>> list(string.ascii_lowercase)
['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']

And to do it with range

>>> list(map(chr, range(97, 123))) #or list(map(chr, range(ord('a'), ord('z')+1)))
['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']

Other helpful string module features:

>>> help(string) # on Python 3
....
DATA
    ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
    ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    digits = '0123456789'
    hexdigits = '0123456789abcdefABCDEF'
    octdigits = '01234567'
    printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
    punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
    whitespace = ' \t\n\r\x0b\x0c'

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

How to add custom method to Spring Data JPA

This is limited in usage, but for simple custom methods you can use default interface methods like:

import demo.database.Customer;
import org.springframework.data.repository.CrudRepository;

public interface CustomerService extends CrudRepository<Customer, Long> {


    default void addSomeCustomers() {
        Customer[] customers = {
            new Customer("Józef", "Nowak", "[email protected]", 679856885, "Rzeszów", "Podkarpackie", "35-061", "Zamknieta 12"),
            new Customer("Adrian", "Mularczyk", "[email protected]", 867569344, "Krosno", "Podkarpackie", "32-442", "Hynka 3/16"),
            new Customer("Kazimierz", "Dejna", "[email protected]", 996435876, "Jaroslaw", "Podkarpackie", "25-122", "Korotynskiego 11"),
            new Customer("Celina", "Dykiel", "[email protected]", 947845734, "Zywiec", "Slaskie", "54-333", "Polna 29")
        };

        for (Customer customer : customers) {
            save(customer);
        }
    }
}

EDIT:

In this spring tutorial it is written:

Spring Data JPA also allows you to define other query methods by simply declaring their method signature.

So it is even possible to just declare method like:

Customer findByHobby(Hobby personHobby);

and if object Hobby is a property of Customer then Spring will automatically define method for you.

Are parameters in strings.xml possible?

If you need two variables in the XML, you can use:

%1$d text... %2$d or %1$s text... %2$s for string variables.

Example :

strings.xml

<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>

activity.java

String site = "site.tld";
String days = "11";

//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();

Count indexes using "for" in Python

In additon to other answers - very often, you do not have to iterate using the index but you can simply use a for-each expression:

my_list = ['a', 'b', 'c']
for item in my_list:
    print item

How to show only next line after the matched one?

I don't know of any way to do this with grep, but it is possible to use awk to achieve the same result:

awk '/blah/ {getline;print}' < logfile

How does the SQL injection from the "Bobby Tables" XKCD comic work?

The ' character in SQL is used for string constants. In this case it is used for ending the string constant and not for comment.

jQuery $.ajax(), pass success data into separate function

I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)

How do you access the value of an SQL count () query in a Java program

The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

rs3.getInt(1);

to get the value in the first, and in your case, only column.

How to set the size of a column in a Bootstrap responsive table

you can use the following Bootstrap class with

<tr class="w-25">

</tr>

for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Grouping functions (tapply, by, aggregate) and the *apply family

First start with Joran's excellent answer -- doubtful anything can better that.

Then the following mnemonics may help to remember the distinctions between each. Whilst some are obvious, others may be less so --- for these you'll find justification in Joran's discussions.

Mnemonics

  • lapply is a list apply which acts on a list or vector and returns a list.
  • sapply is a simple lapply (function defaults to returning a vector or matrix when possible)
  • vapply is a verified apply (allows the return object type to be prespecified)
  • rapply is a recursive apply for nested lists, i.e. lists within lists
  • tapply is a tagged apply where the tags identify the subsets
  • apply is generic: applies a function to a matrix's rows or columns (or, more generally, to dimensions of an array)

Building the Right Background

If using the apply family still feels a bit alien to you, then it might be that you're missing a key point of view.

These two articles can help. They provide the necessary background to motivate the functional programming techniques that are being provided by the apply family of functions.

Users of Lisp will recognise the paradigm immediately. If you're not familiar with Lisp, once you get your head around FP, you'll have gained a powerful point of view for use in R -- and apply will make a lot more sense.

jQuery javascript regex Replace <br> with \n

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");

or using jQuery:

var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));

example

edit: added i flag

edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Reading from file using read() function

fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/

If you don't want to use fgets, following method will work for you :-

int readline(FILE *f, char *buffer, size_t len)
{
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
   {   
      int c = fgetc(f); 

      if (!feof(f)) 
      {   
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
         {   
            buffer[i] = 0;

            return i+1;
         }   
         else
            buffer[i] = c; 
      }   
      else
      {   
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 
      }   
   }   

   return -1; 
}

Have bash script answer interactive prompts

I found the best way to send input is to use cat and a text file to pass along whatever input you need.

cat "input.txt" | ./Script.sh

IIS w3svc error

I have got same issue on my server. Follow below steps -

  1. Open command prompt (run as administrator)
  2. type IISReset and enter.

It works and solved my problem.

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

How to use the addr2line command in Linux?

That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.

For example:

$ cat t.c
#include <stdio.h>
int main()
{
    printf("hello\n");
    return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0

0x400534 is the address of main in my case. 0x400408 is also a valid function address in a.out, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init. You can see the layout of your executable with readelf -a your_exe.)

Other times when addr2line will fail is if you're including a library that has no debug information.

ImportError: No module named scipy

I recommend you to remove scipy via

apt-get purge scipy

and then to install it by

pip install scipy

If you do both then you might confuse you deb package manager due to possibly differing versions.

Swift - How to detect orientation changes

Using NotificationCenter and UIDevice's beginGeneratingDeviceOrientationNotifications

Swift 4.2+

override func viewDidLoad() {
    super.viewDidLoad()        

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)
}

deinit {
   NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil)         
}

func rotated() {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

Swift 3

override func viewDidLoad() {
    super.viewDidLoad()        

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}

deinit {
     NotificationCenter.default.removeObserver(self)
}

func rotated() {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else {
        print("Portrait")
    }
}

Disable building workspace process in Eclipse

For anyone running into a problem where build automatically is unchecked but the project is still building. Make sure your project isn't deployed to the server in the server tab and told to stay synchronous.

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

Extract value of attribute node via XPath

To get just the value (without attribute names), use string():

string(//Parent[@id='1']/Children/child/@name)

The fn:string() fucntion will return the value of its argument as xs:string. In case its argument is an attribute, it will therefore return the attribute's value as xs:string.

Currently running queries in SQL Server

There's this, from SQL Server DMV's In Action book:

The output shows the spid (process identifier), the ecid (this is similar to a thread within the same spid and is useful for identifying queries running in parallel), the user running the SQL, the status (whether the SQL is running or waiting), the wait status (why it’s waiting), the hostname, the domain name, and the start time (useful for determining how long the batch has been running).

The nice part is the query and parent query. That shows, for example, a stored proc as the parent and the query within the stored proc that is running. It has been very handy for me. I hope this helps someone else.

USE master
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
er.session_Id AS [Spid]
, sp.ecid
, er.start_time
, DATEDIFF(SS,er.start_time,GETDATE()) as [Age Seconds]
, sp.nt_username
, er.status
, er.wait_type
, SUBSTRING (qt.text, (er.statement_start_offset/2) + 1,
((CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1) AS [Individual Query]
, qt.text AS [Parent Query]
, sp.program_name
, sp.Hostname
, sp.nt_domain


FROM sys.dm_exec_requests er
INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE session_Id > 50
AND session_Id NOT IN (@@SPID)
ORDER BY session_Id, ecid

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

When your getting this error "ORA-12505, TNS:listener does not currently know of SID given in connect descriptor"

Solution: Open Services, and start OracleServiceXE, after that try to connect...

What is the difference between .text, .value, and .value2?

Out of curiosity, I wanted to see how Value performed against Value2. After about 12 trials of similar processes, I could not see any significant differences in speed so I would always recommend using Value. I used the below code to run some tests with various ranges.

If anyone sees anything contrary regarding performance, please post.

Sub Trial_RUN()
    For t = 0 To 5
        TestValueMethod (True)
        TestValueMethod (False)
    Next t

End Sub




Sub TestValueMethod(useValue2 As Boolean)
Dim beginTime As Date, aCell As Range, rngAddress As String, ResultsColumn As Long
ResultsColumn = 5

'have some values in your RngAddress. in my case i put =Rand() in the cells, and then set to values
rngAddress = "A2:A399999" 'I changed this around on my sets.



With ThisWorkbook.Sheets(1)
.Range(rngAddress).Offset(0, 1).ClearContents


beginTime = Now

For Each aCell In .Range(rngAddress).Cells
    If useValue2 Then
        aCell.Offset(0, 1).Value2 = aCell.Value2 + aCell.Offset(-1, 1).Value2
    Else
        aCell.Offset(0, 1).Value = aCell.Value + aCell.Offset(-1, 1).Value
    End If

Next aCell

Dim Answer As String
 If useValue2 Then Answer = " using Value2"

.Cells(Rows.Count, ResultsColumn).End(xlUp).Offset(1, 0) = DateDiff("S", beginTime, Now) & _
            " seconds. For " & .Range(rngAddress).Cells.Count & " cells, at " & Now & Answer


End With


End Sub

enter image description here

Finding absolute value of a number without using Math.abs()

If you look inside Math.abs you can probably find the best answer:

Eg, for floats:

    /*
     * Returns the absolute value of a {@code float} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     * Special cases:
     * <ul><li>If the argument is positive zero or negative zero, the
     * result is positive zero.
     * <li>If the argument is infinite, the result is positive infinity.
     * <li>If the argument is NaN, the result is NaN.</ul>
     * In other words, the result is the same as the value of the expression:
     * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static float abs(float a) {
        return (a <= 0.0F) ? 0.0F - a : a;
    }

Python: Converting string into decimal number

If you are converting string to float:

import re
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
float_values = [float(re.search(r'\d+.\d+',number).group()) for number in A1]
print(float_values)
>>> [29.0, 65.2, 75.2]

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

If you are using rails, you can use #present?

require 'rails'

nil.present?  # ==> false (Works on nil)
''.present?    # ==> false (Works on strings)
'  '.present?  # ==> false (Works on blank strings)
[].present?    # ==> false(Works on arrays)
false.present? # ==> false (Works on boolean)

So, conversely to check for nil or zero length use !present?

!(nil.present?)  # ==> true
!(''.present?)    # ==> true
!('  '.present?)  # ==> true
!([].present?)    # ==> true
!(false.present?) # ==> true

Usage of __slots__?

Each python object has a __dict__ atttribute which is a dictionary containing all other attributes. e.g. when you type self.attr python is actually doing self.__dict__['attr']. As you can imagine using a dictionary to store attribute takes some extra space & time for accessing it.

However, when you use __slots__, any object created for that class won't have a __dict__ attribute. Instead, all attribute access is done directly via pointers.

So if want a C style structure rather than a full fledged class you can use __slots__ for compacting size of the objects & reducing attribute access time. A good example is a Point class containing attributes x & y. If you are going to have a lot of points, you can try using __slots__ in order to conserve some memory.

$watch an object

The reason why your code doesn't work is because $watch by default does reference check. So in a nutshell it make sure that the object which is passed to it is new object. But in your case you are just modifying some property of form object not creating a new one. In order to make it work you can pass true as the third parameter.

$scope.$watch('form', function(newVal, oldVal){
    console.log('invoked');
}, true);

It will work but You can use $watchCollection which will be more efficient then $watch because $watchCollection will watch for shallow properties on form object. E.g.

$scope.$watchCollection('form', function (newVal, oldVal) {
    console.log(newVal, oldVal);
});

Youtube - How to force 480p video quality in embed link / <iframe>

I found that as of May, 2012, if you set the frame size so that the minimum pixel area (width • height) is above a certain threshold, it bumps the quality up from 360p to 480p, if you're video is at least 640 x 360.

I've discovered that setting a frame size to 780 x 480 for the embed frame triggers the 480p quality, without distorting the video (scaling up). 640 x 585 also works in this manner. I also used the &hd=1 parameter, but I doubt this has much control if your video is not uploaded in HD (720p or higher).

For instance:

<iframe width="780" height="480" src="http://www.youtube.com/embed/[VIDEO-ID]?rel=0&fs=1&showinfo=0&autohide=1&hd=1"></iframe>

Of course, the drawback is that by setting these static frame dimensions, you will most likely get black bars on the sides or above and below, depending on what you prefer.

If you didn't care about the controls being cut-off, you could go on to use CSS and overflow: hidden to crop the black bars out of the frame, providing you know the exact dimensions of the video.

Hope this helps, and hope the Embed method soon gets discrete quality parameters again one day!

Why does .json() return a promise?

Why does response.json return a promise?

Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.

Why do I get the value if I return the promise from the then handler?

Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.

You can use

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.

How to open an Excel file in C#?

Imports

 using Excel= Microsoft.Office.Interop.Excel;
 using Microsoft.VisualStudio.Tools.Applications.Runtime;

Here is the code to open an excel sheet using C#.

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
    Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

    wbv.Close(true, Type.Missing, Type.Missing);
    excel.Quit();

Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4

How do you scroll up/down on the console of a Linux VM

Another alternative, that might be already installed on your system is to use GNU screen :

# This starts screen which adds basic window management in terminals
screen

# This starts the copy mode you can use to scroll
<CTRL-A> [

# Now use the arrows to scroll

# To exit copy mode, do
<ESC>

See man screen for much more useful options (multiple windows, ...)...

Find the files that have been changed in last 24 hours

On GNU-compatible systems (i.e. Linux):

find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more

This will list files and directories that have been modified in the last 24 hours (-mtime 0). It will list them with the last modified time in a format that is both sortable and human-readable (%T+), followed by the file size (%s), followed by the full filename (%p), each separated by tabs (\t).

2>/dev/null throws away any stderr output, so that error messages don't muddy the waters; sort -r sorts the results by most recently modified first; and | more lists one page of results at a time.

What is the difference between compare() and compareTo()?

There is a technical aspect that should be emphasized, too. Say you need comparison behavior parameterization from a client class, and you are wondering whether to use Comparable or Comparator for a method like this:

class Pokemon {
    int healthPoints;
    int attackDamage;
    public void battle (Comparable<Pokemon> comparable, Pokemon opponent) {
        if (comparable.compareTo(opponent) > 0) { //comparable needs to, but cannot, access this.healthPoints for example
            System.out.println("battle won");
        } else {
            System.out.println("battle lost");
        }
    }
}

comparable would a lambda or an object, and there is no way for comparable to access the fields of this Pokemon. (In a lambda, this refers to the outer class instance in the lambda's scope, as defined in the program text.) So this doesn't fly, and we have to use a Comparator with two arguments.

How do I prevent people from doing XSS in Spring MVC?

I use Hibernate Validator via @Valid for all input objects (binding and @RequestBody json, see https://dzone.com/articles/spring-31-valid-requestbody). So @org.hibernate.validator.constraints.SafeHtml is a good solution for me.

Hibernate SafeHtmlValidator depends on org.jsoup, so it's needed to add one more project dependencies:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.1</version>
</dependency>

For bean User with field

@NotEmpty
@SafeHtml
protected String name;

for update attempt with value <script>alert(123)</script> in controller

@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public void update(@Valid @RequestBody User user, @PathVariable("id") int id) 

or

@PostMapping
public void createOrUpdate(@Valid User user) {

is thrown BindException for binding and MethodArgumentNotValidException for @RequestBody with default message:

name may have unsafe html content

Validator works as well for binding, as before persisting. Apps could be tested at http://topjava.herokuapp.com/

UPDATE: see also comment from @GuyT

CVE-2019-10219 and status of @SafeHtml

We have been made aware of a CVE-2019-10219 related to the @SafeHtml constraint and it was fixed in both 6.0.18.Final and 6.1.0.Final....

However, we came to the conclusion that the @SafeHtml constraint was fragile, highly security-sensitive and depending on an external library that wasn’t designed for this purpose. Having it included in core Hibernate Validator was not a very good idea. That’s why we deprecated it and marked it for removal.There is no magic plan here so our users will have to maintain this constraint themselves

Resume for myself: it is safe and could be used, until solution better be found.

How can I loop through a C++ map of maps?

As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:

int main() {
    std::map<std::string, std::map<std::string, std::string>> m {
        {"name1", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name2", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name3", {{"value1", "data1"}, {"value2", "data2"}}}
    };

    for (const auto& [k1, v1] : m)
        for (const auto& [k2, v2] : v1)
            std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;

    return 0;
}

Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.

Note 2: If you want to modify the map m within the loops, you have to remove the const keywords.

Code on Coliru

How to dismiss AlertDialog in android

I think there's a simpler solution: Just use the DialogInterface argument that is passed to the onClick method.

AlertDialog.Builder db = new AlertDialog.Builder(context);
        db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface d, int arg1) {
                db.cancel();
                //here db.cancel will dismiss the builder

            };  
        });

See, for example, http://www.mkyong.com/android/android-alert-dialog-example.

'ng' is not recognized as an internal or external command, operable program or batch file

Just adding a little info to the previous answers, If you have windows 7 or above then go to start and search Node.js command prompt and you will be directly shown the app. Click on it, and start working by using that command prompt for angular.

Vim delete blank lines

Found it, it's:

g/^\s*$/d

Source: Power of g at vim wikia

Brief explanation of :g

:[range]g/pattern/cmd

This acts on the specified [range] (default whole file), by executing the Ex command cmd for each line matching pattern (an Ex command is one starting with a colon such as :d for delete). Before executing cmd, "." is set to the current line.

How to convert a ruby hash object to JSON?

Add the following line on the top of your file

require 'json'

Then you can use:

car = {:make => "bmw", :year => "2003"}
car.to_json

Alternatively, you can use:

JSON.generate({:make => "bmw", :year => "2003"})

onClick function of an input type="button" not working

You have to change the ID of the button to be different from the function name JSFiddle

_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
  counter++;_x000D_
  var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
  newFields.id = '';_x000D_
  newFields.style.display = 'block';_x000D_
  var newField = newFields.childNodes;_x000D_
  for (var i = 0; i < newField.length; i++) {_x000D_
    var theName = newField[i].name_x000D_
    if (theName) newField[i].name = theName + counter;_x000D_
  }_x000D_
  var insertHere = document.getElementById('writeroot');_x000D_
  insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
  <input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
  <br />_x000D_
  <br />_x000D_
  <input name="cd" value="title" />_x000D_
  <select name="rankingsel">_x000D_
    <option>Rating</option>_x000D_
    <option value="excellent">Excellent</option>_x000D_
    <option value="good">Good</option>_x000D_
    <option value="ok">OK</option>_x000D_
    <option value="poor">Poor</option>_x000D_
    <option value="bad">Bad</option>_x000D_
  </select>_x000D_
  <br />_x000D_
  <br />_x000D_
  <textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
  <br />Radio buttons included to test them in Explorer:_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test1" />Test 1_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
  <input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
  <input type="submit" value="Send form" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to convert DateTime to a number with a precision greater than days in T-SQL?

SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as float)

yields 39977.9590277778

Percentage width in a RelativeLayout

You cannot use percentages to define the dimensions of a View inside a RelativeLayout. The best ways to do it is to use LinearLayout and weights, or a custom Layout.

AngularJS Multiple ng-app within a page

_x000D_
_x000D_
         var shoppingCartModule = angular.module("shoppingCart", [])_x000D_
          shoppingCartModule.controller("ShoppingCartController",_x000D_
           function($scope) {_x000D_
             $scope.items = [{_x000D_
               product_name: "Product 1",_x000D_
               price: 50_x000D_
             }, {_x000D_
               product_name: "Product 2",_x000D_
               price: 20_x000D_
             }, {_x000D_
               product_name: "Product 3",_x000D_
               price: 180_x000D_
             }];_x000D_
             $scope.remove = function(index) {_x000D_
               $scope.items.splice(index, 1);_x000D_
             }_x000D_
           }_x000D_
         );_x000D_
         var namesModule = angular.module("namesList", [])_x000D_
          namesModule.controller("NamesController",_x000D_
           function($scope) {_x000D_
             $scope.names = [{_x000D_
               username: "Nitin"_x000D_
             }, {_x000D_
               username: "Mukesh"_x000D_
             }];_x000D_
           }_x000D_
         );_x000D_
_x000D_
_x000D_
         var namesModule = angular.module("namesList2", [])_x000D_
          namesModule.controller("NamesController",_x000D_
           function($scope) {_x000D_
             $scope.names = [{_x000D_
               username: "Nitin"_x000D_
             }, {_x000D_
               username: "Mukesh"_x000D_
             }];_x000D_
           }_x000D_
         );_x000D_
_x000D_
_x000D_
         angular.element(document).ready(function() {_x000D_
           angular.bootstrap(document.getElementById("App2"), ['namesList']);_x000D_
           angular.bootstrap(document.getElementById("App3"), ['namesList2']);_x000D_
         });
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">_x000D_
    <h1>Your order</h1>_x000D_
    <div ng-repeat="item in items">_x000D_
      <span>{{item.product_name}}</span>_x000D_
      <span>{{item.price | currency}}</span>_x000D_
      <button ng-click="remove($index);">Remove</button>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div id="App2" ng-app="namesList" ng-controller="NamesController">_x000D_
    <h1>List of Names</h1>_x000D_
    <div ng-repeat="_name in names">_x000D_
      <p>{{_name.username}}</p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div id="App3" ng-app="namesList2" ng-controller="NamesController">_x000D_
    <h1>List of Names</h1>_x000D_
    <div ng-repeat="_name in names">_x000D_
      <p>{{_name.username}}</p>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Return different type of data from a method in java?

I just want to put my view

So you need to create a generic Return type and implemented by different types of concret return types. The Service class can create different types of objects concrete class and return as a generic type.

public interface GenericReturnType{
    public static RETURN_TYPE enum{
        MACHINE, PERSON;    
    }
    public RETURN_TYPE getReturnType();
}

public class PersonReturnType implements GenericReturnType{
    // CONSTRUCTORS //

    // GETTRE AND SETTER //

    public RETURN_TYPE getReturnType(){
        return PERSON;
    }
    public String getAddress(){
        return something;
    }
}

public class MachineReturnType implements GenericReturnType{
    // CONSTRUCTORS //

    // GETTRE AND SETTER //

    public RETURN_TYPE getReturnType(){
        return MACHINE;
    }
    public String getManufatureName(){
        return something;
    }
}


public class TestService{
    public GenericReturnType getObject(// some input //){
        GenericReturnType obj ;
        if(// some code //){
            obj = new  PersonReturnType();
            // some code //
        }
        if(// some code //){
            obj = new  MachineReturnType();
            // some code //
        }
        return obj;
    }
}

public class TestDriver{
    TestService service = new TestService();
    GenericReturnType genObj = TestService.getObject(// some input //);
    if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
        // SOME CODE // 
    }
    if(genObj.getReturnType() == RETURN_TYPE.PERSON){
        // SOME CODE // 
    }
}

Python Key Error=0 - Can't find Dict error in code

Try this:

class Flonetwork(Object):
    def __init__(self,adj = {},flow={}):
        self.adj = adj
        self.flow = flow

How to check if an element exists in the xml using xpath?

The Saxon documentation, though a little unclear, seems to suggest that the JAXP XPath API will return false when evaluating an XPath expression if no matching nodes are found.

This IBM article mentions a return value of null when no nodes are matched.

You might need to play around with the return types a bit based on this API, but the basic idea is that you just run a normal XPath and check whether the result is a node / false / null / etc.

XPathFactory xpathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml");
Object result = expr.evaluate(doc, XPathConstants.NODE);

if ( result == null ) {
    // do something
}

How to leave/exit/deactivate a Python virtualenv

Use:

$ deactivate 

If this doesn't work, try

$ source deactivate

Anyone who knows how Bash source works will think that's odd, but some wrappers/workflows around virtualenv implement it as a complement/counterpart to source activate. Your mileage may vary.

Single line sftp from terminal

Or echo 'put {path to file}' | sftp {user}@{host}:{dir}, which would work in both unix and powershell.

How to add bootstrap to an angular-cli project

Since this became so confusing and the answers here are totally mixed I will just suggest going with the official ui-team for BS4 repo (yes there are so many of those repos for NG-Bootstrap.

Just follow the instructions here https://github.com/ng-bootstrap/ng-bootstrap to get BS4.

Quoting from the lib:

This library is being built from scratch by the ui-bootstrap team. We are using TypeScript and targeting the Bootstrap 4 CSS framework.

As with Bootstrap 4, this library is a work in progress. Please check out our list of issues to see all the things we are implementing. Feel free to make comments there.

Just copy pasting what is there for the sake of it:

npm install --save @ng-bootstrap/ng-bootstrap

Once installed you need to import our main module:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

The only remaining part is to list the imported module in your application module. The exact method will be slightly different for the root (top-level) module for which you should end up with the code similar to (notice NgbModule.forRoot()):

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],  
  bootstrap: [AppComponent]
})
export class AppModule {
}

Other modules in your application can simply import NgbModule:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [NgbModule, ...], 
})
export class OtherModule {
}

This seems to be the most consistent behavior by far

Initializing IEnumerable<string> In C#

Ok, adding to the answers stated you might be also looking for

IEnumerable<string> m_oEnum = Enumerable.Empty<string>();

or

IEnumerable<string> m_oEnum = new string[]{};

Batch files: List all files in a directory with relative paths

You could simply get the character length of the current directory, and remove them from your absolute list

setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
  set "absPath=%%g"
  setlocal EnableDelayedExpansion
  set "relPath=!absPath:~%len%!"
  echo(!relPath!
  endlocal
)

How do I upgrade to Python 3.6 with conda?

I found this page with detailed instructions to upgrade Anaconda to a major newer version of Python (from Anaconda 4.0+). First,

conda update conda
conda remove argcomplete conda-manager

I also had to conda remove some packages not on the official list:

  • backports_abc
  • beautiful-soup
  • blaze-core

Depending on packages installed on your system, you may get additional UnsatisfiableError errors - simply add those packages to the remove list. Next, install the version of Python,

conda install python==3.6

which takes a while, after which a message indicated to conda install anaconda-client, so I did

conda install anaconda-client

which said it's already there. Finally, following the directions,

conda update anaconda

I did this in the Windows 10 command prompt, but things should be similar in Mac OS X.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Efficient way of having a function only execute once in a loop

A simple function you can reuse in many places in your code (based on the other answers here):

def firstrun(keyword, _keys=[]):
    """Returns True only the first time it's called with each keyword."""
    if keyword in _keys:
        return False
    else:
        _keys.append(keyword)
        return True

or equivalently (if you like to rely on other libraries):

from collections import defaultdict
from itertools import count
def firstrun(keyword, _keys=defaultdict(count)):
    """Returns True only the first time it's called with each keyword."""
    return not _keys[keyword].next()

Sample usage:

for i in range(20):
    if firstrun('house'):
        build_house() # runs only once
if firstrun(42): # True
    print 'This will print.'
if firstrun(42): # False
    print 'This will never print.'

How do we download a blob url video

You can simply right-click and save the blob as mp4.

When I was playing around with browser based video/audio recording the output blob was available to download directly.

DLL load failed error when importing cv2

I ran into this problem on Windows 10 (N) with a new Anaconda installation based on Python 3.7 (OpenCV version 4.0). None of the above advice helped (such as installing OpenCV from the unofficial site nor installing VC Redistributable).

I checked DLL dependencies of ...\AppData\Local\conda\conda\envs\foo\Lib\site-packages\cv2\cv2.cp37-win_amd64.pyd using dumpbin.exe according to this github issue. I noticed a library MF.dll, which I figured out belongs to Windows Media Foundation.

So I installed Media Feature Pack for N versions of Windows 10 and voilà, the issue was resolved!

Splitting words into letters in Java

 char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();

How to fix Ora-01427 single-row subquery returns more than one row in select?

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

What does 'foo' really mean?

I think it's meant to mean nothing. The wiki says:

"Foo is commonly used with the metasyntactic variables bar and foobar."

SyntaxError: cannot assign to operator

Well, as the error says, you have an expression (((t[1])/length) * t[1]) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string to it (which is always "") and assign it to... where? ((t[1])/length) * t[1] isn't a variable name, so you can't store the result into it.

Did you mean string += ((t[1])/length) * t[1]? That would make more sense. Of course, you're still trying to add a number to a string, or multiply by a string... one of those t[1]s should probably be a t[0].

Reading CSV files using C#

My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.

These are the variants I have ran into:

  • quotes are quoted and doubled (excel) i.e. 15" -> field1,"15""",field3
  • quotes are not changed unless the field is quoted for some other reason. i.e. 15" -> field1,15",fields3
  • quotes are escaped with \. i.e. 15" -> field1,"15\"",field3
  • quotes are not changed at all (this is not always possible to parse correctly)
  • delimiter is quoted (excel). i.e. a,b -> field1,"a,b",field3
  • delimiter is escaped with \. i.e. a,b -> field1,a\,b,field3

I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.

In my projects I now use either the VB TextFieldParser or a custom splitter.

Illegal Character when trying to compile java code

I solved this by right clicking in my textEdit program file and selecting [substitutions] and un-checking smart quotes.

Cursor inside cursor

I had the same problem,

what you have to do is declare the second cursor as: DECLARE [second_cursor] Cursor LOCAL For

You see"CURSOR LOCAL FOR" instead of "CURSOR FOR"

How to run a cronjob every X minutes?

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

To set for x minutes we need to set x minutes in the 1st argument and then the path of your script

For 15 mins

*/15 * * * *  /usr/bin/php /mydomain.in/cromail.php > /dev/null 2>&1

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Progress during large file copy (Copy-Item & Write-Progress?)

Sean Kearney from the Hey, Scripting Guy! Blog has a solution I found works pretty nicely.

Function Copy-WithProgress
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
            ValueFromPipelineByPropertyName=$true,
            Position=0)]
        $Source,
        [Parameter(Mandatory=$true,
            ValueFromPipelineByPropertyName=$true,
            Position=0)]
        $Destination
    )

    $Source=$Source.tolower()
    $Filelist=Get-Childitem "$Source" –Recurse
    $Total=$Filelist.count
    $Position=0

    foreach ($File in $Filelist)
    {
        $Filename=$File.Fullname.tolower().replace($Source,'')
        $DestinationFile=($Destination+$Filename)
        Write-Progress -Activity "Copying data from '$source' to '$Destination'" -Status "Copying File $Filename" -PercentComplete (($Position/$total)*100)
        Copy-Item $File.FullName -Destination $DestinationFile
        $Position++
    }
}

Then to use it:

Copy-WithProgress -Source $src -Destination $dest

What is the difference between supervised learning and unsupervised learning?

In supervised learning, the input x is provided with the expected outcome y (i.e., the output the model is supposed to produce when the input is x), which is often called the "class" (or "label") of the corresponding input x.

In unsupervised learning, the "class" of an example x is not provided. So, unsupervised learning can be thought of as finding "hidden structure" in unlabelled data set.

Approaches to supervised learning include:

  • Classification (1R, Naive Bayes, decision tree learning algorithm, such as ID3 CART, and so on)

  • Numeric Value Prediction

Approaches to unsupervised learning include:

  • Clustering (K-means, hierarchical clustering)

  • Association Rule Learning

Entity Framework - Code First - Can't Store List<String>

Of course Pawel has given the right answer. But I found in this post that since EF 6+ it is possible to save private properties. So I would prefer this code, because you are not able to save the Strings in a wrong way.

public class Test
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column]
    [Required]
    private String StringsAsStrings { get; set; }

    public List<String> Strings
    {
        get { return StringsAsStrings.Split(',').ToList(); }
        set
        {
            StringsAsStrings = String.Join(",", value);
        }
    }
    public Test()
    {
        Strings = new List<string>
        {
            "test",
            "test2",
            "test3",
            "test4"
        };
    }
}

Tesseract running error

You can grab eng.traineddata Github:

wget https://github.com/tesseract-ocr/tessdata/raw/master/eng.traineddata

Check https://github.com/tesseract-ocr/tessdata for a full list of trained language data.

When you grab the file(s), move them to the /usr/local/share/tessdata folder. Warning: some Linux distributions (such as openSUSE and Ubuntu) may be expecting it in /usr/share/tessdata instead.

# If you got the data from Google, unzip it first!
gunzip eng.traineddata.gz 
# Move the data
sudo mv -v eng.traineddata /usr/local/share/tessdata/

How do I rename a column in a SQLite database table?

Recently I had to do that in SQLite3 with a table named points with the colunms id, lon, lat. Erroneusly, when the table was imported, the values for latitude where stored in the lon column and viceversa, so an obvious fix would be to rename those columns. So the trick was:

create table points_tmp as select id, lon as lat, lat as lon from points;
drop table points;
alter table points_tmp rename to points;

I hope this would be useful for you!

How to find all the subclasses of a class given its name?

Note: I see that someone (not @unutbu) changed the referenced answer so that it no longer uses vars()['Foo'] — so the primary point of my post no longer applies.

FWIW, here's what I meant about @unutbu's answer only working with locally defined classes — and that using eval() instead of vars() would make it work with any accessible class, not only those defined in the current scope.

For those who dislike using eval(), a way is also shown to avoid it.

First here's a concrete example demonstrating the potential problem with using vars():

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

# unutbu's approach
def all_subclasses(cls):
    return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                       for g in all_subclasses(s)]

print(all_subclasses(vars()['Foo']))  # Fine because  Foo is in scope
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

def func():  # won't work because Foo class is not locally defined
    print(all_subclasses(vars()['Foo']))

try:
    func()  # not OK because Foo is not local to func()
except Exception as e:
    print('calling func() raised exception: {!r}'.format(e))
    # -> calling func() raised exception: KeyError('Foo',)

print(all_subclasses(eval('Foo')))  # OK
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

# using eval('xxx') instead of vars()['xxx']
def func2():
    print(all_subclasses(eval('Foo')))

func2()  # Works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

This could be improved by moving the eval('ClassName') down into the function defined, which makes using it easier without loss of the additional generality gained by using eval() which unlike vars() is not context-sensitive:

# easier to use version
def all_subclasses2(classname):
    direct_subclasses = eval(classname).__subclasses__()
    return direct_subclasses + [g for s in direct_subclasses
                                    for g in all_subclasses2(s.__name__)]

# pass 'xxx' instead of eval('xxx')
def func_ez():
    print(all_subclasses2('Foo'))  # simpler

func_ez()
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

Lastly, it's possible, and perhaps even important in some cases, to avoid using eval() for security reasons, so here's a version without it:

def get_all_subclasses(cls):
    """ Generator of all a class's subclasses. """
    try:
        for subclass in cls.__subclasses__():
            yield subclass
            for subclass in get_all_subclasses(subclass):
                yield subclass
    except TypeError:
        return

def all_subclasses3(classname):
    for cls in get_all_subclasses(object):  # object is base of all new-style classes.
        if cls.__name__.split('.')[-1] == classname:
            break
    else:
        raise ValueError('class %s not found' % classname)
    direct_subclasses = cls.__subclasses__()
    return direct_subclasses + [g for s in direct_subclasses
                                    for g in all_subclasses3(s.__name__)]

# no eval('xxx')
def func3():
    print(all_subclasses3('Foo'))

func3()  # Also works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

How do I draw a circle in iOS Swift?

WARNING! This is an incorrect solution. layers are added infinitely in the drawRect method (every time the view is drawn). You should NEVER add layers in the drawRect method. Use layoutSubview instead.

You can draw a circle with this (Swift 3.0+):

let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100, y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
    
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
    
// Change the fill color
shapeLayer.fillColor = UIColor.clear.cgColor
// You can change the stroke color
shapeLayer.strokeColor = UIColor.red.cgColor
// You can change the line width
shapeLayer.lineWidth = 3.0
    
view.layer.addSublayer(shapeLayer)

With the code you have posted you are cropping the corners of the UIView, not adding a circle to the view.


Here's a full example of using that method:

/// A special UIView displayed as a ring of color
class Ring: UIView {
    override func drawRect(rect: CGRect) {
        drawRingFittingInsideView()
    }
    
    internal func drawRingFittingInsideView() -> () {
        let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
        let desiredLineWidth:CGFloat = 1 // your desired value
            
        let circlePath = UIBezierPath(
                arcCenter: CGPoint(x:halfSize,y:halfSize),
                radius: CGFloat( halfSize - (desiredLineWidth/2) ),
                startAngle: CGFloat(0),
                endAngle:CGFloat(M_PI * 2),
                clockwise: true)
    
         let shapeLayer = CAShapeLayer()
         shapeLayer.path = circlePath.CGPath
            
         shapeLayer.fillColor = UIColor.clearColor().CGColor
         shapeLayer.strokeColor = UIColor.redColor().CGColor
         shapeLayer.lineWidth = desiredLineWidth
    
         layer.addSublayer(shapeLayer)
     }
}

A circle outlined in red and filled with yellow on a yellow background.


Note, however there's an incredibly handy call:

let circlePath = UIBezierPath(ovalInRect: rect)

which does all the work of making the path. (Don't forget to inset it for the line thickness, which is also incredibly easy with CGRectInset.)

internal func drawRingFittingInsideView(rect: CGRect) {
    let desiredLineWidth:CGFloat = 4    // Your desired value
    let hw:CGFloat = desiredLineWidth/2
    
    let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw))
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.CGPath
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    shapeLayer.lineWidth = desiredLineWidth
    layer.addSublayer(shapeLayer)
}

An ellipses (oval-like) outlined in red and filled with yellow on a yellow background.


In practice these days in Swift, you would certainly use @IBDesignable and @IBInspectable. Using these you can actually see and change the rendering, in Storyboard!

As you can see, it actually adds new features to the Inspector on the Storyboard, which you can change on the Storyboard:

Xcode Storyboard Attributes Inspector with custom fields.

/// A dot with a border, which you can control completely in Storyboard
@IBDesignable class Dot: UIView {

    @IBInspectable var mainColor: UIColor = UIColor.blueColor() {
        didSet { 
             print("mainColor was set here")
        }
    }

    @IBInspectable var ringColor: UIColor = UIColor.orangeColor() {
         didSet {
             print("bColor was set here") 
        }
    }

    @IBInspectable var ringThickness: CGFloat = 4 {
        didSet { 
            print("ringThickness was set here")
        }
    }
    
    @IBInspectable var isSelected: Bool = true
    
    override func drawRect(rect: CGRect) {
        let dotPath = UIBezierPath(ovalInRect:rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.CGPath
        shapeLayer.fillColor = mainColor.CGColor
        layer.addSublayer(shapeLayer)
        
        if (isSelected) { 
            drawRingFittingInsideView(rect)
        }
    }
    
    internal func drawRingFittingInsideView(rect: CGRect) {
        let hw:CGFloat = ringThickness/2
        let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw) )
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.CGPath
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = ringColor.CGColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

Finally, note that if you have a UIView (which is square, and which you set to say red in Storyboard) and you simply want to turn it in to a red circle, you can just do the following:

// Makes a UIView into a circular dot of color
class Dot: UIView {
    override func layoutSubviews() {
        layer.cornerRadius = bounds.size.width/2
    }
}

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

pythonic way to do something N times without an index variable?

since function is first-class citizen, you can write small wrapper (from Alex answers)

def repeat(f, N):
    for _ in itertools.repeat(None, N): f()

then you can pass function as argument.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

What it seems like to me is that by calling the keys method you're returning to python a dictionary object when it's looking for a list or a tuple. So try taking all of the keys in the dictionary, putting them into a list and then using the for loop.

How to fill OpenCV image with one solid color?

The simplest is using the OpenCV Mat class:

img=cv::Scalar(blue_value, green_value, red_value);

where img was defined as a cv::Mat.

Convert xlsx file to csv using batch

You need an external tool, in example: SoftInterface.com - Convert XLSX to CSV.

After installing it, you can use following command in your batch:

"c:\Program Files\Softinterface, Inc\Convert XLS\ConvertXLS.EXE" /S"C:\MyExcelFile.xlsx" /F51 /N"Sheet1" /T"C:\MyExcelFile.CSV" /C6 /M1 /V

How to select specific form element in jQuery?

$("#name", '#form2').val("Hello World")

Div not expanding even with content inside

Add <br style="clear: both" /> after the last floated div worked for me.

Spring REST Service: how to configure to remove null objects in json response

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
public class Shop {
    //...
}

for jackson 2.0 or later use @JsonInclude(Include.NON_NULL)

This will remove both empty and null Objects.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

TestNG ERROR Cannot find class in classpath

If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Intellij Console

Clicking on the highlighted part expands and displays the complete class path.

you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION

java -cp "path_copied" org.testng.TestNG testng.xml

If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>config/testrun_config.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

twitter bootstrap typeahead ajax example

Try this if your service is not returning the right application/json content type header:

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            var json = JSON.parse(data); // string to json
            return process(json.options);
        });
    }
});

PHP: How to remove specific element from an array?

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
     function remove_embpty($values)
     {
        if($values=='orange')
        {
            $values='any name';
        }
        return $values;
     }
     $detils=array_map('remove_embpty',$detils);
    print_r($detils);

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

How to include quotes in a string

As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:

string msg = @"I want to learn ""c#""";

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

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

Using only CSS, show div on hover over <a>

This answer doesn't require that you know the what type of display (inline, etc.) the hideable element is supposed to be when being shown:

_x000D_
_x000D_
.hoverable:not(:hover) + .show-on-hover {_x000D_
    display: none;_x000D_
}
_x000D_
<a class="hoverable">Hover over me!</a>_x000D_
<div class="show-on-hover">I'm a block element.</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<a class="hoverable">Hover over me also!</a>_x000D_
<span class="show-on-hover">I'm an inline element.</span>
_x000D_
_x000D_
_x000D_

This uses the adjacent sibling selector and the not selector.

Developing for Android in Eclipse: R.java not regenerating

Try checking the project.properties file. It might be the case that your Android JAR file in the build path doesn't match with the version mentioned over there.

It solved my problem as I had changed my target.

How do I find out which keystore was used to sign an app?

You can use Java 7's Key and Certificate Management Tool keytool to check the signature of a keystore or an APK without extracting any files.

Signature of an APK or AAB

# APK file
keytool -printcert -jarfile app.apk

# AAB file
keytool -printcert -jarfile app.aab

The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk or AAB file app.aab.

(Note that the -jarfile argument was introduced in Java 7; see the documentation for more details.)

Signature of a keystore

keytool -list -v -keystore release.jks

The output will reveal the aliases (entries) in the keystore file release.jks, with the certificate fingerprints (MD5, SHA1 and SHA256).

If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.

2 column div layout: right column with fixed width, left fluid

Best to avoid placing the right column before the left, simply use a negative right-margin.

And be "responsive" by including an @media setting so the right column falls under the left on narrow screens.

<div style="background: #f1f2ea;">
  <div id="container">
    <div id="content">
        <strong>Column 1 - content</strong>
    </div>
  </div>
  <div id="sidebar">
    <strong>Column 2 - sidebar</strong>
  </div>
<div style="clear:both"></div>

<style type="text/css">
#container {
    margin-right: -300px;
    float:left;
    width:100%;
}
#content {
    margin-right: 320px; /* 20px added for center margin */
}
#sidebar {
    width:300px;
    float:left
}
@media (max-width: 480px) {
    #container {
        margin-right:0px;
        margin-bottom:20px;
    }
    #content {
        margin-right:0px;
        width:100%;
    }
    #sidebar {
        clear:left;
    }
}
</style>

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Get a Windows Forms control by name in C#

Since you're generating them dynamically, keep a map between a string and the menu item, that will allow fast retrieval.

// in class scope
private readonly Dictionary<string, ToolStripMenuItem> _menuItemsByName = new Dictionary<string, ToolStripMenuItem>();

// in your method creating items
ToolStripMenuItem createdItem = ...
_menuItemsByName.Add("<name here>", createdItem);

// to access it
ToolStripMenuItem menuItem = _menuItemsByName["<name here>"];

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

pandas loc vs. iloc vs. at vs. iat?

df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])

df

                        A   B
                100     a   54
                200     b   67
                300     c   89
In [19]:    
df.loc[100]

Out[19]:
A     a
B    54
Name: 100, dtype: object

In [20]:    
df.iloc[0]

Out[20]:
A     a
B    54
Name: 100, dtype: object

In [24]:    
df2 = df.set_index([df.index,'A'])
df2

Out[24]:
        B
    A   
100 a   54
200 b   67
300 c   89

In [25]:    
df2.ix[100, 'a']

Out[25]:    
B    54
Name: (100, a), dtype: int64

How to retry image pull in a kubernetes Pods?

$ kubectl replace --force -f <resource-file>

if all goes well, you should see something like:

<resource-type> <resource-name> deleted
<resource-type> <resource-name> replaced

details of this can be found in the Kubernetes documentation, "manage-deployment" and kubectl-cheatsheet pages at the time of writing.

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

ArrayList: how does the size increase?

Default capacity of ArrayList is 10. Once the Capacity reaches its maximum capacity, Size of the ArrayList will be 16, once the capacity reaches its maximum capacity of 16, size of the ArrayList will be 25 and keep on increasing based on Data size.....

How? Here is the Answer and Formula

New capacity = (Current Capacity * 3/2) + 1

So, if the default capacity is 10, then

Current Capacity = 10
New capacity = (10 * 3/2) + 1
Output is 16

Lombok annotations do not compile under Intellij idea

I am unable to get this working with the javac compiler, and I get the same error.

Error:(9, 14) java: package lombok does not exist

I have enabled annotation processor, and have also tried rebuilding the project, invalidate cache/restart. Doesn't help.

I did however get it to work partially with eclipse compiler. I say partial because although the build passes successfully, the editor still complains about "Cannot resolve symbol".

Idea - 15.04 community edition Lombok - 1.16.6 Lombok plugin (https://github.com/mplushnikov/lombok-intellij-plugin) - 0.9.8 JDK - 1.8.0_51

Update: Ok, I finally got this working. Mine was a gradle project, and lombok was configured as a custom "provided" configuration. Worked fine after adding this in build.gradle

idea {
 module {
     scopes.PROVIDED.plus += [configurations.provided]
    }
}

So, 3 steps

  1. Install Lombok plugin from File->Settings->Plugins
  2. Enable Annotation Processor (javac compiler works too)
  3. Ensure that you have build.gradle or pom.xml updated for idea if you are adding lombok as a custom config.

How to compare strings in C conditional preprocessor-directives

[UPDATE: 2021.01.04]

One thing that has changed since I first posted this in 2014, is the format of #pragma message.

Nowadays, the parens are required!

#pragma message ("USER    IS " USER)
#pragma message ("USER_VS IS " USER_VS)

That said, the 2016 code (using characters, not strings) still works in VS2019.

But, as @Artyer points out, the version involving c_strcmp will NOT work in ANY modern compiler.

[UPDATE: 2018.05.03]

CAVEAT: Not all compilers implement the C++11 specification in the same way. The below code works in the compiler I tested on, while many commenters used a different compiler.

Quoting from Shafik Yaghmour's answer at: Computing length of a C string at compile time. Is this really a constexpr?

Constant expressions are not guaranteed to be evaluated at compile time, we only have a non-normative quote from draft C++ standard section 5.19 Constant expressions that says this though:

[...]>[ Note: Constant expressions can be evaluated during translation.—end note ]

That word can makes all the difference in the world.

So, YMMV on this (or any) answer involving constexpr, depending on the compiler writer's interpretation of the spec.

[UPDATED 2016.01.31]

As some didn't like my earlier answer because it avoided the whole compile time string compare aspect of the OP by accomplishing the goal with no need for string compares, here is a more detailed answer.

You can't! Not in C98 or C99. Not even in C11. No amount of MACRO manipulation will change this.

The definition of const-expression used in the #if does not allow strings.

It does allow characters, so if you limit yourself to characters you might use this:

#define JACK 'J'
#define QUEEN 'Q'

#define CHOICE JACK     // or QUEEN, your choice

#if 'J' == CHOICE
#define USER "jack"
#define USER_VS "queen"
#elif 'Q' == CHOICE
#define USER "queen"
#define USER_VS "jack"
#else
#define USER "anonymous1"
#define USER_VS "anonymous2"
#endif

#pragma message "USER    IS " USER
#pragma message "USER_VS IS " USER_VS

You can! In C++11. If you define a compile time helper function for the comparison.

[2021.01.04: CAVEAT: This does not work in any MODERN compiler. See comment by @Artyer.]

// compares two strings in compile time constant fashion
constexpr int c_strcmp( char const* lhs, char const* rhs )
{
    return (('\0' == lhs[0]) && ('\0' == rhs[0])) ? 0
        :  (lhs[0] != rhs[0]) ? (lhs[0] - rhs[0])
        : c_strcmp( lhs+1, rhs+1 );
}
// some compilers may require ((int)lhs[0] - (int)rhs[0])

#define JACK "jack"
#define QUEEN "queen"

#define USER JACK       // or QUEEN, your choice

#if 0 == c_strcmp( USER, JACK )
#define USER_VS QUEEN
#elif 0 == c_strcmp( USER, QUEEN )
#define USER_VS JACK
#else
#define USER_VS "unknown"
#endif

#pragma message "USER    IS " USER
#pragma message "USER_VS IS " USER_VS

So, ultimately, you will have to change the way you accomlish your goal of choosing final string values for USER and USER_VS.

You can't do compile time string compares in C99, but you can do compile time choosing of strings.

If you really must do compile time sting comparisons, then you need to change to C++11 or newer variants that allow that feature.

[ORIGINAL ANSWER FOLLOWS]

Try:

#define jack_VS queen
#define queen_VS jack

#define USER jack          // jack    or queen, your choice
#define USER_VS USER##_VS  // jack_VS or queen_VS

// stringify usage: S(USER) or S(USER_VS) when you need the string form.
#define S(U) S_(U)
#define S_(U) #U

UPDATE: ANSI token pasting is sometimes less than obvious. ;-D

Putting a single # before a macro causes it to be changed into a string of its value, instead of its bare value.

Putting a double ## between two tokens causes them to be concatenated into a single token.

So, the macro USER_VS has the expansion jack_VS or queen_VS, depending on how you set USER.

The stringify macro S(...) uses macro indirection so the value of the named macro gets converted into a string. instead of the name of the macro.

Thus USER##_VS becomes jack_VS (or queen_VS), depending on how you set USER.

Later, when the stringify macro is used as S(USER_VS) the value of USER_VS (jack_VS in this example) is passed to the indirection step S_(jack_VS) which converts its value (queen) into a string "queen".

If you set USER to queen then the final result is the string "jack".

For token concatenation, see: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

For token string conversion, see: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification

[UPDATED 2015.02.15 to correct a typo.]

Passing an Array as Arguments, not an Array, in PHP

Also note that if you want to apply an instance method to an array, you need to pass the function as:

call_user_func_array(array($instance, "MethodName"), $myArgs);

How do you convert CString and std::string std::wstring to each other?

One interesting approach is to cast CString to CStringA inside a string constructor. Unlike std::string s((LPCTSTR)cs); this will work even if _UNICODE is defined. However, if that is the case, this will perform conversion from Unicode to ANSI, so it is unsafe for higher Unicode values beyond the ASCII character set. Such conversion is subject to the _CSTRING_DISABLE_NARROW_WIDE_CONVERSION preprocessor definition. https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx

        CString s1("SomeString");
        string s2((CStringA)s1);

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

This thing also happened with my code, but somehow I solved my problem. I checked my routes folder (where my all endpoints are their). I would recommend you check your routes folder file and check whether you forgot to add your particular router link.

mysqli::query(): Couldn't fetch mysqli

Reason of the error is wrong initialization of the mysqli object. True construction would be like this:

$DBConnect = new mysqli("localhost","root","","Ladle");

take(1) vs first()

It turns out there's a very important distinction between the two methods: first() will emit an error if the stream completes before a value is emitted. Or, if you've provided a predicate (i.e. first(value => value === 'foo')), it will emit an error if the stream completes before a value that passes the predicate is emitted.

take(1), on the other hand, will happily carry on if a value is never emitted from the stream. Here's a simple example:

const subject$ = new Subject();

// logs "no elements in sequence" when the subject completes
subject$.first().subscribe(null, (err) => console.log(err.message));

// never does anything
subject$.take(1).subscribe(console.log);

subject$.complete();

Another example, using a predicate:

const observable$ = of(1, 2, 3);

// logs "no elements in sequence" when the observable completes
observable$
 .first((value) => value > 5)
 .subscribe(null, (err) => console.log(err.message));

// the above can also be written like this, and will never do
// anything because the filter predicate will never return true
observable$
 .filter((value) => value > 5);
 .take(1)
 .subscribe(console.log);

As a newcomer to RxJS, this behavior was very confusing to me, although it was my own fault because I made some incorrect assumptions. If I had bothered to check the docs, I would have seen that the behavior is clearly documented:

Throws an error if defaultValue was not provided and a matching element is not found.

The reason I've run into this so frequently is a fairly common Angular 2 pattern where observables are cleaned up manually during the OnDestroy lifecycle hook:

class MyComponent implements OnInit, OnDestroy {
  private stream$: Subject = someDelayedStream();
  private destroy$ = new Subject();

  ngOnInit() {
    this.stream$
      .takeUntil(this.destroy$)
      .first()
      .subscribe(doSomething);
  }

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}

The code looks harmless at first, but problems arise when the component in destroyed before stream$ can emit a value. Because I'm using first(), an error is thrown when the component is destroyed. I'm usually only subscribing to a stream to get a value that is to be used within the component, so I don't care if the component gets destroyed before the stream emits. Because of this, I've started using take(1) in almost all places where I would have previously used first().

filter(fn).take(1) is a bit more verbose than first(fn), but in most cases I prefer a little more verbosity over handling errors that ultimately have no impact on the application.

Also important to note: The same applies for last() and takeLast(1).

reference

How to prevent line-break in a column of a table cell (not a single cell)?

You can use the CSS style white-space:

white-space: nowrap;

C - error: storage size of ‘a’ isn’t known

1)declare the structs before the main function. it worked for me. 2) And also fix the spelling mistake of that variable name if any e

how to POST/Submit an Input Checkbox that is disabled?

The simplest way to this is:

<input type="checkbox" class="special" onclick="event.preventDefault();" checked />

This will prevent the user from being able to deselect this checkbox and it will still submit its value when the form is submitted. Remove checked if you want the user to not be able to select this checkbox.

Also, you can then use javascript to clear the onclick once a certain condition has been met (if that's what you're after). Here's a down-and-dirty fiddle showing what I mean. It's not perfect, but you get the gist.

http://jsfiddle.net/vwUUc/

How to parse unix timestamp to time.Time

I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:

func dateFormat(layout string, d float64) string{
    intTime := int64(d)
    t := time.Unix(intTime, 0)
    if layout == "" {
        layout = "2006-01-02 15:04:05"
    }
    return t.Format(layout)
}

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

How to do INSERT into a table records extracted from another table

inserting data form one table to another table in different DATABASE

insert into DocTypeGroup 
    Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType 
    from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }

How should the ViewModel close the form?

FYI, I ran into this same problem and I think I figured out a work around that doesn't require globals or statics, although it may not be the best answer. I let the you guys decide that for yourself.

In my case, the ViewModel that instantiates the Window to be displayed (lets call it ViewModelMain) also knows about the LoginFormViewModel (using the situation above as an example).

So what I did was to create a property on the LoginFormViewModel that was of type ICommand (Lets call it CloseWindowCommand). Then, before I call .ShowDialog() on the Window, I set the CloseWindowCommand property on the LoginFormViewModel to the window.Close() method of the Window I instantiated. Then inside the LoginFormViewModel all I have to do is call CloseWindowCommand.Execute() to close the window.

It is a bit of a workaround/hack I suppose, but it works well without really breaking the MVVM pattern.

Feel free to critique this process as much as you like, I can take it! :)

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

open() in Python does not create a file if it doesn't exist

Put w+ for writing the file, truncating if it exist, r+ to read the file, creating one if it don't exist but not writing (and returning null) or a+ for creating a new file or appending to a existing one.

How do I install a Python package with a .whl file?

I just used the following which was quite simple. First open a console then cd to where you've downloaded your file like some-package.whl and use

pip install some-package.whl

Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. If pip is not installed, this page can help: How do I install pip on Windows?

Note: for clarification
If you copy the *.whl file to your local drive (ex. C:\some-dir\some-file.whl) use the following command line parameters --

pip install C:/some-dir/some-file.whl

Regex not operator

No, there's no direct not operator. At least not the way you hope for.

You can use a zero-width negative lookahead, however:

\((?!2001)[0-9a-zA-z _\.\-:]*\)

The (?!...) part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).

There are actually 4 combinations of lookarounds with 2 axes:

  • lookbehind / lookahead : specifies if the characters before or after the point are considered
  • positive / negative : specifies if the characters must match or must not match.

Ignore parent padding

Another solution:

position: absolute;
top: 0;
left: 0;

just change the top/right/bottom/left to your case.

Validating Phone Numbers Using Javascript

_x000D_
_x000D_
function telephoneCheck(str) {_x000D_
  var a = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);_x000D_
  alert(a);_x000D_
}_x000D_
telephoneCheck("(555) 555-5555");
_x000D_
_x000D_
_x000D_

Where str could be any of these formats: 555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555

How to write a full path in a batch file having a folder name with space?

I made a **

automatic-network-drive connector

** using a batch file.

Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!

looks a little bit different but works:

net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES

Thx for the Hint :)

Use ffmpeg to add text subtitles

ffmpeg supports the mov_text subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.

Your line would read:

ffmpeg -i input.mp4 -i input.srt -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4

Why split the <script> tag when writing it with document.write()?

The solution Bobince posted works perfectly for me. I wanted to offer an alternative method as well for future visitors:

if (typeof(jQuery) == 'undefined') {
    (function() {
        var sct = document.createElement('script');
        sct.src = ('https:' == document.location.protocol ? 'https' : 'http') +
          '://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';
        sct.type = 'text/javascript';
        sct.async = 'true';
        var domel = document.getElementsByTagName('script')[0];
        domel.parentNode.insertBefore(sct, domel);
    })();
}

In this example, I've included a conditional load for jQuery to demonstrate use case. Hope that's useful for someone!

Composer install error - requires ext_curl when it's actually enabled

on php7 run for example:

> sudo apt-get install php-curl
> sudo apt-get install php-mbstring

for every missing extension. Then:

> sudo apt-get update

and finally (in the project's root folder):

> composer install

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

Can you center a Button in RelativeLayout?

Its easy, dont Align it to anything

_x000D_
_x000D_
<Button_x000D_
        android:id="@+id/the_button"_x000D_
        android:layout_width="wrap_content"_x000D_
        android:layout_height="wrap_content" _x000D_
        android:layout_centerInParent="true"_x000D_
        android:text="Centered Button"/>
_x000D_
_x000D_
_x000D_

Where are the Android icon drawables within the SDK?

i found mine here:

~/android-sdks/platforms/android-23/data/res/drawable...

Any way to write a Windows .bat file to kill processes?

taskkill /f /im "devenv.exe"

this will forcibly kill the pid with the exe name "devenv.exe"

equivalent to -9 on the nix'y kill command

How to press/click the button using Selenium if the button does not have the Id?

You don't need to use only identifier as elements locators. You can use a few ways to find an element. Read this article and choose the best for you.

Call static method with reflection

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

How to return a specific element of an array?

(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:

array3[i]=e1

Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.

There has been an error processing your request, Error log record number

In my case this problem appears when magento updated automatically. I restored my back up and bingo it starts working properly.

Change EditText hint color when using TextInputLayout

Looks like the parent view had a style for a 3rd party library that was causing the EditText to be white.

android:theme="@style/com_mixpanel_android_SurveyActivityTheme"

Once I removed this everything worked fine.

How to Get JSON Array Within JSON Object?

Your int length = jsonObj.length(); should be int length = ja_data.length();

How to execute only one test spec with angular-cli

This is working for me in Angular 7. It is based on the --main option of the ng command. I am not sure if this option is undocumented and possibly subject to change, but it works for me. I put a line in my package.json file in scripts section. There using the --main option of with the ng test command, I specify the path to the .spec.ts file I want to execute. For example

"test 1": "ng test --main E:/WebRxAngularClient/src/app/test/shared/my-date-utils.spec.ts",

You can run the script as you run any such script. I run it in Webstorm by clicking on "test 1" in the npm section.

SQL Server remove milliseconds from datetime

You just have to figure out the millisecond part of the date and subtract it out before comparison, like this:

select * 
from table 
where DATEADD(ms, -DATEPART(ms, date), date) > '2010-07-20 03:21:52'

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.

HTML

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

<input type="text" value="default!" id="myInput" />

JavaScript

$(document).ready(function (){
    $('#myInput').keyup(function(event) {
        // 27 is key code of ESC
        if (event.keyCode == 27) {
            $('#myInput').val('default!');
            // Loose focus on input field
            $('#myInput').blur();
        }
    });
});

Working source can be found here: http://jsfiddle.net/S3N5H/1/

Please let me know if you meant something different, I can adjust the code later.

Counting words in string

function WordCount(str) {
    var totalSoFar = 0;
    for (var i = 1; i < str.length; i++) {
        if (str[i] === " ") {
            totalSoFar ++;
        }
    }
    return totalSoFar; 
}
console.log(WordCount("hi my name is raj));

Can you explain the HttpURLConnection connection process?

String message = URLEncoder.encode("my message", "UTF-8");

try {
    // instantiate the URL object with the target URL of the resource to
    // request
    URL url = new URL("http://www.example.com/comment");

    // instantiate the HttpURLConnection with the URL object - A new
    // connection is opened every time by calling the openConnection
    // method of the protocol handler for this URL.
    // 1. This is the point where the connection is opened.
    HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
    // set connection output to true
    connection.setDoOutput(true);
    // instead of a GET, we're going to send using method="POST"
    connection.setRequestMethod("POST");

    // instantiate OutputStreamWriter using the output stream, returned
    // from getOutputStream, that writes to this connection.
    // 2. This is the point where you'll know if the connection was
    // successfully established. If an I/O error occurs while creating
    // the output stream, you'll see an IOException.
    OutputStreamWriter writer = new OutputStreamWriter(
            connection.getOutputStream());

    // write data to the connection. This is data that you are sending
    // to the server
    // 3. No. Sending the data is conducted here. We established the
    // connection with getOutputStream
    writer.write("message=" + message);

    // Closes this output stream and releases any system resources
    // associated with this stream. At this point, we've sent all the
    // data. Only the outputStream is closed at this point, not the
    // actual connection
    writer.close();
    // if there is a response code AND that response code is 200 OK, do
    // stuff in the first if block
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // OK

        // otherwise, if any other status code is returned, or no status
        // code is returned, do stuff in the else block
    } else {
        // Server returned HTTP error code.
    }
} catch (MalformedURLException e) {
    // ...
} catch (IOException e) {
    // ...
}

The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.

From getOutputStream:

Returns an output stream that writes to this connection.

Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. getOutputStream basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream, you're opening the connection stream for writing, but you don't actually write any data until you call writer.write("message=" + message);.

From getInputStream():

Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

getInputStream does the opposite. Like getOutputStream, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException.

How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?

Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream url.openConnection(), you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.

In layman's terms, making a getInputStream request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.

Using a similar example for getOutputStream would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.

Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)

Question #5:

Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.

openConnection creates a new connection object. From the URL.openConnection javadocs:

A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.

The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.

Question #6:

To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:

long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );

// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );

I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.

For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.

Sorting an IList in C#

This looks MUCH MORE SIMPLE if you ask me. This works PERFECTLY for me.

You could use Cast() to change it to IList then use OrderBy():

    var ordered = theIList.Cast<T>().OrderBy(e => e);

WHERE T is the type eg. Model.Employee or Plugin.ContactService.Shared.Contact

Then you can use a for loop and its DONE.

  ObservableCollection<Plugin.ContactService.Shared.Contact> ContactItems= new ObservableCollection<Contact>();

    foreach (var item in ordered)
    {
       ContactItems.Add(item);
    }

How to scroll to top of a div using jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

How do I reference tables in Excel using VBA?

In addition to the above, you can do this (where "YourListObjectName" is the name of your table):

Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")

But I think that only works if you want to reference a list object that's on the active sheet.

I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.

Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.

    Dim WB As Workbook
    Set WB = ActiveWorkbook

    ' Create a PivotTable object and set it to be
    ' the pivot table in the active cell:
    Dim PT As PivotTable
    Set PT = ActiveCell.PivotTable

    Dim LO As ListObject
    Dim LOWS As Worksheet

    ' Loop through the worksheets and each worksheet's list objects
    ' to find the name of the worksheet that contains the list object
    ' that the pivot table uses as its source data:
    Dim WS As Worksheet
    For Each WS In WB.Worksheets
        ' Loop through the ListObjects in each workshet:
        For Each LO In WS.ListObjects
            ' If the ListObject's name is the name of the pivot table's soure data,
            ' set the LOWS to be the worksheet that contains the list object:
            If LO.Name = PT.SourceData Then
                Set LOWS = WB.Worksheets(LO.Parent.Name)
            End If
        Next LO
    Next WS

    Debug.Print LOWS.Name

End Sub

Maybe someone knows a more direct way.

break/exit script

Perhaps you just want to stop executing a long script at some point. ie. like you want to hard code an exit() in C or Python.

print("this is the last message")
stop()
print("you should not see this")

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

How to implement a queue using two stacks?

public class QueueUsingStacks<T>
{
    private LinkedListStack<T> stack1;
    private LinkedListStack<T> stack2;

    public QueueUsingStacks()
    {
        stack1=new LinkedListStack<T>();
        stack2 = new LinkedListStack<T>();

    }
    public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )
    {
        while(source.Head!=null)
        {
            dest.Push(source.Head.Data);
            source.Head = source.Head.Next;
        }
    }
    public void Enqueue(T entry)
    {

       stack1.Push(entry);
    }
    public T Dequeue()
    {
        T obj;
        if (stack2 != null)
        {
            Copy(stack1, stack2);
             obj = stack2.Pop();
            Copy(stack2, stack1);
        }
        else
        {
            throw new Exception("Stack is empty");
        }
        return obj;
    }

    public void Display()
    {
        stack1.Display();
    }


}

For every enqueue operation, we add to the top of the stack1. For every dequeue, we empty the content's of stack1 into stack2, and remove the element at top of the stack.Time complexity is O(n) for dequeue, as we have to copy the stack1 to stack2. time complexity of enqueue is the same as a regular stack

Under what conditions is a JSESSIONID created?

For links generated in a JSP with custom tags, I had to use

<%@ page session="false" %>

in the JSP

AND

request.getSession().invalidate();

in the Struts action

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

this worked for me on iis8 together with some of the other answers. My error was a 404.6 specifically

<system.webServer>
  <security>
  <requestFiltering>
    <verbs applyToWebDAV="false">
       <add verb="DELETE" allowed="true" />
    </verbs>
  </requestFiltering>
  </security>
</system.webServer>

What's the difference between JPA and Hibernate?

JPA is a specification that you implement in your data layer to perform db opertations, OR mappings and other required tasks.

Since it is just a specification, you need a tool to have it implemented. That tool can be either Hibernate, TopLink, iBatis, spring-data etc.

You don't necessarily require JPA if you are using Hibernate in your Data Layer. But if you use JPA specification for Hibernate, then it will make switching to other ORM tools like iBatis, TopLink easy in future, because the specification is common for others as well.

*(if you remember, you do import javax.persistence.*; when you use annotations for OR mapping (like @Id, @Column, @GeneratedValue etc.) in Hibernate, that's where you are using JPA under Hibernate, you can use JPA's @Query & other features as well)

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

IIS - can't access page by ip address instead of localhost

Try with disabling Windows Firewall, it worked for me, but in my case, I was able to access IIS through 127.0.0.1