Programs & Examples On #Sap iq

Sybase IQ is a column-based RDBMS used for business intelligence, data warehousing, and data marts. Produced by Sybase, an SAP company, its primary function is to analyze large amounts of data in a low-cost, high-availability environment.

Bash Templating: How to build configuration files from templates with Bash?

This page describes an answer with awk

awk '{while(match($0,"[$]{[^}]*}")) {var=substr($0,RSTART+2,RLENGTH -3);gsub("[$]{"var"}",ENVIRON[var])}}1' < input.txt > output.txt

Recreate the default website in IIS

Check out this answer on SuperUser:

In short: Reinstall both IIS and WAS.

In details -

Step 1

Go to "Add remove programs" "Turn windows features on or off" Remove both IIS and WAS (Windows Process Activation Service) Restart the PC Step 2

Go to "Add remove programs" "Turn windows features on or off" Turn on both IIS and WAS (Windows Process Activation Service) Note: Reinstalling IIS alone won't help. You have to reinstall both IIS and WAS

This approach fixed the problem for me.

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

In my case, my co-worker changed the solution name so that after I get latest version of the project, I run my web application with IIS EXPRESS, then I got the message ERR_CONNECTION_REFUSED in my google chrome.

After I try all the solution that I find on the internet, finally I solved the problem with these steps :

  1. Close VS
  2. Delete the .vs folder in the project folder enter image description here

  3. Run As Administrator VS

  4. Open Debug > [Your Application] Properties > Web

  5. Change the port in Project URL and don't forget using https because in my case, when I'm using http it still did not work.

  6. Click Create virtual directory

  7. Run the application again using IIS EXPRESS.

  8. And the web application ran successfully.

Hope these helps.

How to remove a directory from git repository?

A combination of the 2 answers worked for me

git rm -r one-of-the-directories
git commit . -m "Remove duplicated directory"
git push

if it still shows some warning, remove the files manually

git filter-branch --tree-filter 'rm -rf path/to/your/file' HEAD
git push

Can't use Swift classes inside Objective-C

In my case, apart from these steps:

  1. Product Module Name : myproject
  2. Defines Module : YES
  3. Embedded Content Contains Swift : YES
  4. Install Objective-C Compatibility Header : YES
  5. Objective-C Bridging Header : $(SRCROOT)/Sources/SwiftBridging.h

I have needed to put the class as public in order to create productName-Swift.h file:

import UIKit

   @objc public class TestSwift: NSObject {
       func sayHello() {
          print("Hi there!")
       }
   }

Maven skip tests

During maven compilation you can skip test execution by adding following plugin in pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration>
         <skipTests>true</skipTests>
    </configuration>
</plugin>

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
str.codePoints().forEachOrdered(i -> System.out.print((char)i));

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

The method codePoints() also returns an IntStream as per doc:

Returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream.

How is char and code point different? As mentioned in this article:

Unicode 3.1 added supplementary characters, bringing the total number of characters to more than the 2^16 = 65536 characters that can be distinguished by a single 16-bit char. Therefore, a char value no longer has a one-to-one mapping to the fundamental semantic unit in Unicode. JDK 5 was updated to support the larger set of character values. Instead of changing the definition of the char type, some of the new supplementary characters are represented by a surrogate pair of two char values. To reduce naming confusion, a code point will be used to refer to the number that represents a particular Unicode character, including supplementary ones.

Finally why forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

For difference between a character, a code point, a glyph and a grapheme check this question.

Does VBA contain a comment block syntax?

There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

IE 8: background-size fix

As pointed by @RSK IE8 doesn't support background-size. To figure out a way to deal with this, I used some IE specific hacks as showed here:

//IE8.0 Hack!
@media \0screen {
    .brand {
        background-image: url("./images/logo1.png");
        margin-top: 8px;
    }

    .navbar .brand {
        margin-left: -2px;
        padding-bottom: 2px;
    }
}

//IE7.0 Hack!
*+html .brand {
    background-image: url("./images/logo1.png");
    margin-top: 8px;
}

*+html .navbar .brand {
    margin-left: -2px;
    padding-bottom: 2px;
}

Using this I was able to change my logo image to a ugly resided picture. But the final result is fine. I suggest u try something like this.

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

How do I pass an object from one activity to another on Android?

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I had similar issues when using 'java' at the beginning of the package name, e.g. java.jem.pc

Check your console output, I was receiving:

Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.jem.pc

What does 'x packages are looking for funding' mean when running `npm install`?

npm install --silent

Seems to suppress the funding issue.

Simple DateTime sql query

select getdate()

O/P
----
2011-05-25 17:29:44.763

select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'

O/P
---
22/06/1432  5:29:44:763PM

Default optional parameter in Swift function

It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,

func test(param: Int? = nil)

These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.

So it is always better not to use nil as default value.

ssh : Permission denied (publickey,gssapi-with-mic)

please make sure following changes should be uncommented, which I did and got succeed in centos7

vi /etc/ssh/sshd_config

1.PubkeyAuthentication yes

2.PasswordAuthentication yes

3.GSSAPIKeyExchange no

4.GSSAPICleanupCredentials no

systemctl restart sshd

ssh-keygen

chmod 777 /root/.ssh/id_rsa.pub 

ssh-copy-id -i /root/.ssh/id_rsa.pub user@ipaddress

thank you all and good luck

How to Define Callbacks in Android?

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

Just as a random example:

// The callback interface
interface MyCallback {
    void callbackCall();
}

// The class that takes the callback
class Worker {
   MyCallback callback;

   void onEvent() {
      callback.callbackCall();
   }
}

// Option 1:

class Callback implements MyCallback {
   void callbackCall() {
      // callback code goes here
   }
}

worker.callback = new Callback();

// Option 2:

worker.callback = new MyCallback() {

   void callbackCall() {
      // callback code goes here
   }
};

I probably messed up the syntax in option 2. It's early.

Inline list initialization in VB.NET

Collection initializers are only available in VB.NET 2010, released 2010-04-12:

Dim theVar = New List(Of String) From { "one", "two", "three" }

java.lang.OutOfMemoryError: Java heap space

No, I think you are thinking of stack space. Heap space is occupied by objects. The way to increase it is -Xmx256m, replacing the 256 with the amount you need on the command line.

Create XML in Javascript

Consider that we need to create the following XML document:

<?xml version="1.0"?>
<people>
  <person first-name="eric" middle-initial="H" last-name="jung">
    <address street="321 south st" city="denver" state="co" country="usa"/>
    <address street="123 main st" city="arlington" state="ma" country="usa"/>
  </person>

  <person first-name="jed" last-name="brown">
    <address street="321 north st" city="atlanta" state="ga" country="usa"/>
    <address street="123 west st" city="seattle" state="wa" country="usa"/>
    <address street="321 south avenue" city="denver" state="co" country="usa"/>
  </person>
</people>

we can write the following code to generate the above XML

var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");

var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");

var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);

var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);

var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");

var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);

var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);

var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);

peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);

If any text need to be written between a tag we can use innerHTML property to achieve it.

Example

elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)

For more details please follow the below link. The above example has been explained there in more details.

https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree

Find rows that have the same value on a column in MySQL

Get the entire record as you want using the condition with inner select query.

SELECT *
FROM   member
WHERE  email IN (SELECT email
                 FROM   member
                 WHERE  login_id = [email protected]) 

How to restore/reset npm configuration to default values?

Config is written to .npmrc files so just delete it. NPM looks up config in this order, setting in the next overwrites the previous one. So make sure there might be global config that usually is overwritten in per-project that becomes active after you have deleted the per-project config file. npm config list will allways list the active config.

  1. npm builtin config file (/path/to/npm/npmrc)
  2. global config file ($PREFIX/etc/npmrc)
  3. per-user config file ($HOME/.npmrc)
  4. per-project config file (/path/to/my/project/.npmrc)

How to disable JavaScript in Chrome Developer Tools?

chrome://settings/content Javascript/Manage Exceptions

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A, Ctrl + \ - Exit screen and terminate all programs in this screen. It is helpful, for example, if you need to close a tty connection.

  • Ctrl + D, D or - Ctrl + A, Ctrl + D - "minimize" screen and screen -r to restore it.

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

MySql : Grant read only options?

Even user has got answer and @Michael - sqlbot has covered mostly points very well in his post but one point is missing, so just trying to cover it.

If you want to provide read permission to a simple user (Not admin kind of)-

GRANT SELECT, EXECUTE ON DB_NAME.* TO 'user'@'localhost' IDENTIFIED BY 'PASSWORD';

Note: EXECUTE is required here, so that user can read data if there is a stored procedure which produce a report (have few select statements).

Replace localhost with specific IP from which user will connect to DB.

Additional Read Permissions are-

  • SHOW VIEW : If you want to show view schema.
  • REPLICATION CLIENT : If user need to check replication/slave status. But need to give permission on all DB.
  • PROCESS : If user need to check running process. Will work with all DB only.

Why is my Spring @Autowired field null?

I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.

I make Spring inject applicationContext in this bean:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils {

    public static ApplicationContext ctx;

    /**
     * Make Spring inject the application context
     * and save it on a static variable,
     * so that it can be accessed from any point in the application. 
     */
    @Autowired
    private void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;       
    }
}

You can put this code also in the main application class if you want.

Other classes can use it like this:

MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);

In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.

How to check for changes on remote (origin) Git repository

My regular question is rather "anything new or changed in repo" so whatchanged comes handy. Found it here.

git whatchanged origin/master -n 1

How to Deep clone in javascript

My solution, deep clones objects, arrays and functions.

let superClone = (object) => {
  let cloning = {};

  Object.keys(object).map(prop => {
     if(Array.isArray(object[prop])) {
        cloning[prop] = [].concat(object[prop])
    } else if(typeof  object[prop] === 'object') {
      cloning[prop] = superClone(object[prop])
    } else cloning[prop] = object[prop]
  })

  return cloning
}

example

let obj = {
  a: 'a',
  b: 'b',
  c: {
    deep: 'try and copy me',
    d: {
      deeper: 'try me again',
      callDeeper() {
       return this.deeper
     }
    },
    arr: [1, 2, 3]
  },
  hi() {
    return this.a
  }
};


const cloned = superClone(obj)
obj.a = 'A' 
obj.c.deep = 'i changed'
obj.c.arr = [45,454]
obj.c.d.deeper = 'i changed'

console.log(cloned) // unchanged object

If your objects contain methods don't use JSON to deep clone, JSON deep cloning doesn't clone methods.

If you take a look at this, object person2 only clones the name, not person1's greet method.


const person1 = {
  name: 'John',
  greet() {
    return `HI, ${this.name}`
  }
}
 
const person2 = JSON.parse(JSON.stringify(person1))
 
console.log(person2)  // { name: 'John' }

How to put a UserControl into Visual Studio toolBox

Basic qustion if you are using generics in your base control. If yes:

lets say we have control:

public class MyComboDropDown : ComboDropDownComon<MyType>
{
    public MyComboDropDown() { }
}

MyComboDropDown will not allow to open designer on it and will be not shown in Toolbox. Why? Because base control is not already compiled - when MyComboDropDown is complied. You can modify to this:

public class MyComboDropDown : MyComboDropDownBase
{
    public MyComboDropDown() { }
}

public class MyComboDropDownBase : ComboDropDownComon<MyType>
{

}

Than after rebuild, and reset toolbox it should be able to see MyComboDropDown in designer and also in Toolbox

Putting HTML inside Html.ActionLink(), plus No Link Text?

It's very simple.

If you want to have something like a glyphicon icon and then "Wish List",

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")

Why doesn't importing java.util.* include Arrays and Lists?

The difference between

import java.util.*;

and

import java.util.*;
import java.util.List;
import java.util.Arrays;

becomes apparent when the code refers to some other List or Arrays (for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays will be used.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

That's not exactly what I had in mind. What do you do if you have a generic type to only be known at runtime?

public MyDTO toObject() {
  try {
    var methodInfo = MethodBase.GetCurrentMethod();
    if (methodInfo.DeclaringType != null) {
      var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName;
      Type type = Type.GetType(fullName);
      if (type != null) {
        var obj = JsonConvert.DeserializeObject(payload);
      //var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload);  // <--- type ?????
          ...
      }
    }

    // Example for java..   Convert this to C#
    return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader()));
  } catch (Exception ex) {
    throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex);
  }
}

How to detect IE11?

IE11 no longer reports as MSIE, according to this list of changes it's intentional to avoid mis-detection.

What you can do if you really want to know it's IE is to detect the Trident/ string in the user agent if navigator.appName returns Netscape, something like (the untested);

_x000D_
_x000D_
function getInternetExplorerVersion()_x000D_
{_x000D_
  var rv = -1;_x000D_
  if (navigator.appName == 'Microsoft Internet Explorer')_x000D_
  {_x000D_
    var ua = navigator.userAgent;_x000D_
    var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  }_x000D_
  else if (navigator.appName == 'Netscape')_x000D_
  {_x000D_
    var ua = navigator.userAgent;_x000D_
    var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  }_x000D_
  return rv;_x000D_
}_x000D_
_x000D_
console.log('IE version:', getInternetExplorerVersion());
_x000D_
_x000D_
_x000D_

Note that IE11 (afaik) still is in preview, and the user agent may change before release.

Rename a file in C#

None of the answers mention writing a unit testable solution. You could use System.IO.Abstractions as it provides a testable wrapper around FileSystem operations, using which you can create a mocked file system objects and write unit tests.

using System.IO.Abstractions;

IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));

It was tested, and it is working code to rename a file.

How to remove all characters after a specific character in python?

another easy way using re will be

import re, clr

text = 'some string... this part will be removed.'

text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)

// text = some string

nginx- duplicate default server error

You likely have other files (such as the default configuration) located in /etc/nginx/sites-enabled that needs to be removed.

This issue is caused by a repeat of the default_server parameter supplied to one or more listen directives in your files. You'll likely find this conflicting directive reads something similar to:

listen 80 default_server;

As the nginx core module documentation for listen states:

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.

This means that there must be another file or server block defined in your configuration with default_server set for port 80. nginx is encountering that first before your mysite.com file so try removing or adjusting that other configuration.

If you are struggling to find where these directives and parameters are set, try a search like so:

grep -R default_server /etc/nginx

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Flatten an irregular list of lists

I used recursive to solve nested list with any depth

def combine_nlist(nlist,init=0,combiner=lambda x,y: x+y):
    '''
    apply function: combiner to a nested list element by element(treated as flatten list)
    '''
    current_value=init
    for each_item in nlist:
        if isinstance(each_item,list):
            current_value =combine_nlist(each_item,current_value,combiner)
        else:
            current_value = combiner(current_value,each_item)
    return current_value

So after i define function combine_nlist, it is easy to use this function do flatting. Or you can combine it into one function. I like my solution because it can be applied to any nested list.

def flatten_nlist(nlist):
    return combine_nlist(nlist,[],lambda x,y:x+[y])

result

In [379]: flatten_nlist([1,2,3,[4,5],[6],[[[7],8],9],10])
Out[379]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Sometimes adding a WCF Service Reference generates an empty reference.cs

I've been bashing my head for a whole day with this exact problem. I've just fixed it. Here's how...

The service had to run over SSL (i.e. it's at https://mydomain.com/MyService.svc)

Adding a service reference to the WCF service on a development server worked just fine.

Deploying the exact same build of the WCF service on the live production server, then switching to the client application and configuring the service reference to point to the live service displayed no errors but the app wouldn't build: It turns out that the service reference's Reference.cs file was completely empty! Updating the service reference made no difference. Cleaning the solution didn't help. Restarting VS2010 made no difference. Creating a new blank solution, starting a console project and adding a service reference to the live service exhibited exactly the same problem.

I didn't think it was due to conflicting types or anything, but what the heck - I reconfigured the WCF service reference by unchecking "Reuse types in all referenced assemblies". No joy; I put the check mark back.

Next step was to try svcutil on the reference URL to see if that would help uncover the problem. Here's the command:

svcutil /t:code https://mydomain.com/MyService.svc /d:D:\test

This produced the following:

Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 'https://mydomain.com/MyService.svc' using WS-Metadata Exchange or DISCO.
Error: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Schema with target namespace 'http://mynamespace.com//' could not be found.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://mynamespace.com//']/wsdl:portType[@name='IMyService']


Error: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='http://mynamespace.com//']/wsdl:portType[@name='IMyService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_IMyService']


Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_IMyService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:service[@name='MyService']/wsdl:port[@name='WSHttpBinding_IMyService']


Generating files...
Warning: No code was generated.
If you were trying to generate a client, this could be because the metadata documents did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assemblies. Verify that you passed all the metadata documents to the tool.

Warning: If you would like to generate data contracts from schemas make sure to use the /dataContractOnly option.

That had me completely stumped. Despite heavy googling and getting really rather cross, and reconsidering a career as a bus driver, I finally considered why it worked OK on the development box. Could it be an IIS configuration issue?

I remoted simultaneously into both the development and live boxes, and on each I fired up the IIS Manager (running IIS 7.5). Next, I went through each configuration setting on each box, comparing the values on each server.

And there's the problem: Under "SSL Settings" for the site, make sure "Require SSL" is checked, and check the Client Certificates radio button for "Accept". Problem fixed!

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

If you support IE, for versions of Internet Explorer 8 and above, this:

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />

Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.

If you separate with semi-colon, it sets compatibility levels for different versions. For example:

<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />

Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

For this:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

It forces the browser the render at whatever the most recent version's standards are.

For more information, there is plenty to read about on MSDN,

HTML select dropdown list

Make a JavaScript control that before the submit cheek that the selected option is different to your first option

Javascript for "Add to Home Screen" on iPhone?

In 2020, this is still not possible on Mobile Safari.

The next best solution is to show instructions on the steps to adding your page to the homescreen.

enter image description here

Picture is from this great article which covers that an many other tips on how to make your PWA feel iOS native.

How do I parse a URL into hostname and path in javascript?

Use https://www.npmjs.com/package/uri-parse-lib for this

var t = parserURI("http://user:[email protected]:8080/directory/file.ext?query=1&next=4&sed=5#anchor");

How to iterate over a std::map full of strings in C++

Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.

jQuery add text to span within a div

Careful - append() will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>').

Use text() to replace element content with text, or append(document.createTextNode(x)) to append a text node.

Why do you have to link the math library in C?

All libraries like stdio.h and stdlib.h have their implementation in libc.so or libc.a and get linked by the linker by default. The libraries for libc.so are automatically linked while compiling and is included in the executable file.
But math.h has its implementations in libm.so or libm.a which is seperate from libc.so and it does not get linked by default and you have to manually link it while compiling your program in gcc by using -lm flag.

The gnu gcc team designed it to be seperate from the other header files, while the other header files get linked by default but math.h file doesn't.

Here read the item no 14.3, you could read it all if you wish: Reason why math.h is needs to be linked
Look at this article: why we have to link math.h in gcc?
Have a look at the usage: using the library

Calculating text width

If you are trying to determine the width of a mix of text nodes and elements inside a given element, you need to wrap all the contents with wrapInner(), calculate the width, and then unwrap the contents.

*Note: You will also need to extend jQuery to add an unwrapInner() function since it is not provided by default.

$.fn.extend({
  unwrapInner: function(selector) {
      return this.each(function() {
          var t = this,
              c = $(t).children(selector);
          if (c.length === 1) {
              c.contents().appendTo(t);
              c.remove();
          }
      });
  },
  textWidth: function() {
    var self = $(this);
    $(this).wrapInner('<span id="text-width-calc"></span>');
    var width = $(this).find('#text-width-calc').width();
    $(this).unwrapInner();
    return width;
  }
});

How do I search a Perl array for a matching string?

It depends on what you want the search to do:

  • if you want to find all matches, use the built-in grep:

    my @matches = grep { /pattern/ } @list_of_strings;
    
  • if you want to find the first match, use first in List::Util:

    use List::Util 'first';  
    my $match = first { /pattern/ } @list_of_strings;
    
  • if you want to find the count of all matches, use true in List::MoreUtils:

    use List::MoreUtils 'true';
    my $count = true { /pattern/ } @list_of_strings;
    
  • if you want to know the index of the first match, use first_index in List::MoreUtils:

    use List::MoreUtils 'first_index'; 
    my $index = first_index { /pattern/ } @list_of_strings;
    
  • if you want to simply know if there was a match, but you don't care which element it was or its value, use any in List::Util:

    use List::Util 1.33 'any';
    my $match_found = any { /pattern/ } @list_of_strings;
    

All these examples do similar things at their core, but their implementations have been heavily optimized to be fast, and will be faster than any pure-perl implementation that you might write yourself with grep, map or a for loop.


Note that the algorithm for doing the looping is a separate issue than performing the individual matches. To match a string case-insensitively, you can simply use the i flag in the pattern: /pattern/i. You should definitely read through perldoc perlre if you have not previously done so.

Run function from the command line

It is always an option to enter python on the command line with the command python

then import your file so import example_file

then run the command with example_file.hello()

This avoids the weird .pyc copy function that crops up every time you run python -c etc.

Maybe not as convenient as a single-command, but a good quick fix to text a file from the command line, and allows you to use python to call and execute your file.

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

Best way to integrate Python and JavaScript?

You could also use XPCOM, say in XUL based apps like Firefox, Thunderbird or Komodo.

How can one tell the version of React running at runtime in the browser?

To know the react version, Open package.json file in root folder, search the keywork react. You will see like "react": "^16.4.0",

Truncate (not round) decimal places in SQL Server

Do you want the decimal or not?

If not, use

select ceiling(@value),floor(@value)

If you do it with 0 then do a round:

select round(@value,2)

Python "extend" for a dictionary

Have you tried using dictionary comprehension with dictionary mapping:

a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}

c = {**a, **b}
# c = {"a": 1, "b": 2, "c": 3, "d": 4}

Another way of doing is by Using dict(iterable, **kwarg)

c = dict(a, **b)
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In Python 3.9 you can add two dict using union | operator

# use the merging operator |
c = a | b
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Get controller and action name from within controller?

This seems to work nicely for me (so far), also works if you are using attribute routing.

public class BaseController : Controller
{
    protected string CurrentAction { get; private set; }
    protected string CurrentController { get; private set; }

    protected override void Initialize(RequestContext requestContext)
    {
        this.PopulateControllerActionInfo(requestContext);
    }

    private void PopulateControllerActionInfo(RequestContext requestContext)
    {
        RouteData routedata = requestContext.RouteData;

        object routes;

        if (routedata.Values.TryGetValue("MS_DirectRouteMatches", out routes))
        {
            routedata = (routes as List<RouteData>)?.FirstOrDefault();
        }

        if (routedata == null)
            return;

        Func<string, string> getValue = (s) =>
        {
            object o;
            return routedata.Values.TryGetValue(s, out o) ? o.ToString() : String.Empty;
        };

        this.CurrentAction = getValue("action");
        this.CurrentController = getValue("controller");
    }
}

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

How to format numbers by prepending 0 to single-digit numbers?

Here's my version. Can easily be adapted to other scenarios.

function setNumericFormat(value) {
    var length = value.toString().length;
    if (length < 4) {
        var prefix = "";
        for (var i = 1; i <= 4 - length; i++) {
            prefix += "0";
        }
        return prefix + value.toString();
    }
    return  value.toString();
}

How to delete selected text in the vi editor

I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?

Forget the mouse. To remove 5 lines, either:

  • Go to the first line and type d5d (dd deletes one line, d5d deletes 5 lines) ~or~
  • Type Shift-v to enter linewise selection mode, then move the cursor down using j (yes, use h, j, k and l to move left, down, up, right respectively, that's much more efficient than using the arrows) and type d to delete the selection.

Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?

As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.

I suggest spending some time with the Vim Tutor (run vimtutor) to get more familiar with Vim in a very didactic way.

See also

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

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

How to format a Java string with leading zero?

You may have to take care of edgecase. This is a generic method.

public class Test {
    public static void main(String[] args){
        System.out.println(padCharacter("0",8,"hello"));
    }
    public static String padCharacter(String c, int num, String str){
        for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
        return str;
    }
}

How to iterate a table rows with JQuery and access some cell values?

try this

var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');

function iterate(selector)
{
  var result = '';
  if ($(selector))
  {
    $(selector).each(function ()
    {
      if (result == '')
      {
        result = $(this).html();
      }
      else
      {
        result = result + "," + $(this).html();
      }
    });
  }
}

How to close form

You can also close the application:

Application.Exit();

It will end the processes.

How to split a string to 2 strings in C

This is how you implement a strtok() like function (taken from a BSD licensed string processing library for C, called zString).

Below function differs from the standard strtok() in the way it recognizes consecutive delimiters, whereas the standard strtok() does not.

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

Below is an example code that demonstrates the usage

  Example Usage
      char str[] = "A,B,,,C";
      printf("1 %s\n",zstring_strtok(s,","));
      printf("2 %s\n",zstring_strtok(NULL,","));
      printf("3 %s\n",zstring_strtok(NULL,","));
      printf("4 %s\n",zstring_strtok(NULL,","));
      printf("5 %s\n",zstring_strtok(NULL,","));
      printf("6 %s\n",zstring_strtok(NULL,","));

  Example Output
      1 A
      2 B
      3 ,
      4 ,
      5 C
      6 (null)

You can even use a while loop (standard library's strtok() would give the same result here)

char s[]="some text here;
do {
    printf("%s\n",zstring_strtok(s," "));
} while(zstring_strtok(NULL," "));

Java Wait and Notify: IllegalMonitorStateException

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

class Runner implements Runnable
{
  public void run()
  {
    try
    {
      synchronized(Main.main) {
        Main.main.wait();
      }
    } catch (InterruptedException e) {}
    System.out.println("Runner away!");
  }
}

The same rule applies to notify()/notifyAll() as well.

The Javadocs for wait() mention this:

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:

IllegalMonitorStateException – if the current thread is not the owner of this object's monitor.

And from notify():

A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Div width 100% minus fixed amount of pixels

In some contexts, you can leverage margin settings to effectively specify "100% width minus N pixels". See the accepted answer to this question.

How to initialize a two-dimensional array in Python?

Here is an easier way :

import numpy as np
twoD = np.array([[]*m]*n)

For initializing all cells with any 'x' value use :

twoD = np.array([[x]*m]*n

Eclipse error: 'Failed to create the Java Virtual Machine'

I remove -XX:+UseStringDeduplication from eclipse.ini . If you run eclipsec.exe you get better descryiption .

How to change the JDK for a Jenkins job?

For those who couldn't find this option. Install JDK Parameter Plugin

The developers of this app have not set up this app properly for Facebook Login?

I had the same problem but now here is how I solved it
Go to https://developers.facebook.com/
• Click on the Apps menu on the top bar.
• Select the respective app from the drop down.
• Click Settings from the table in the left side of the page
• Then under the Contact Email type in your email you would like to use
• Then click save settings button
• Go to 'Status & Review' from the table in the left side of the page.
• Do you want to make this app and all its live features available to the general public? - Select switch to set YES/NO value.

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

I'm sure after years you probably have an answer already. But in case someone else is looking for an answer in the future.

For my problem, I didn't have to at anything to the web.config. I didn't think I would need to either as it was working previously.

Make sure no folder is named the same as your page, I had a folder called "blog" and a page named "blog.aspx", it was trying to load the folder, I noticed this in the link, changed the folder to blogContent, now it loads fine.

I'm posting a copy here as you're the first in the search query.

Is there a decorator to simply cache function return values?

It sounds like you're not asking for a general-purpose memoization decorator (i.e., you're not interested in the general case where you want to cache return values for different argument values). That is, you'd like to have this:

x = obj.name  # expensive
y = obj.name  # cheap

while a general-purpose memoization decorator would give you this:

x = obj.name()  # expensive
y = obj.name()  # cheap

I submit that the method-call syntax is better style, because it suggests the possibility of expensive computation while the property syntax suggests a quick lookup.

[Update: The class-based memoization decorator I had linked to and quoted here previously doesn't work for methods. I've replaced it with a decorator function.] If you're willing to use a general-purpose memoization decorator, here's a simple one:

def memoize(function):
  memo = {}
  def wrapper(*args):
    if args in memo:
      return memo[args]
    else:
      rv = function(*args)
      memo[args] = rv
      return rv
  return wrapper

Example usage:

@memoize
def fibonacci(n):
  if n < 2: return n
  return fibonacci(n - 1) + fibonacci(n - 2)

Another memoization decorator with a limit on the cache size can be found here.

Download the Android SDK components for offline install

There is an open source offline package deployer for Windows which I wrote:

http://siddharthbarman.com/apd/

You can try this out to see if it meets your needs.

Communication between multiple docker-compose projects

I would ensure all containers are docker-compose'd to the same network by composing them together at the same time, using:

docker compose --file ~/front/docker-compose.yml --file ~/api/docker-compose.yml up -d

Delete element in a slice

In golang's wiki it show some tricks for slice, including delete an element from slice.

Link: enter link description here

For example a is the slice which you want to delete the number i element.

a = append(a[:i], a[i+1:]...)

OR

a = a[:i+copy(a[i:], a[i+1:])]

HTML5 live streaming

<object classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
            height="285" id="mediaPlayer" standby="Loading Microsoft Windows Media Player components..."
            type="application/x-oleobject" width="360" style="margin-bottom:30px;">
            <param name="fileName" value="mms://my_IP_Address:my_port" />
            <param name="animationatStart" value="true" />
            <param name="transparentatStart" value="true" />
            <param name="autoStart" value="true" />
            <param name="showControls" value="true" />
            <param name="loop" value="true" />
            <embed autosize="-1" autostart="true" bgcolor="darkblue" designtimesp="5311" displaysize="4"
                height="285" id="mediaPlayer" loop="true" name="mediaPlayer" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/"
                showcontrols="true" showdisplay="0" showstatusbar="-1" showtracker="-1" src="mms://my_IP_Address:my_port"
                type="application/x-mplayer2" videoborder3d="-1" width="360"></embed>
</object>

QtCreator: No valid kits found

Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.

To do so:

Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.

C# : Converting Base Class to Child Class

I don't think you can downcast an object, however there is a simple way to "downcast" the object outside the box. It isn't type safe, but it works. First serialize the object into json, then deserialize it into the child class object. It works the same as if you were passing the object between apis. So, while there are some people who may say "this doesn't work or isn't good", I would argue that it is exactly the way our internet currently works, so... why not use that method? No mapping required as long as parameter names are the same, and they will be if it is a child class. Note: This will likely not copy any private fields; if you have a constructor with parameters, this probably needs to be tested as well to ensure there aren't side effects.

Here's my toolbox:

public static string ConvertToJson<T>(this T obj)
{
    return JsonConvert.SerializeObject(obj);
}
public static T ConvertToObject<T>(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return Activator.CreateInstance<T>();
    }
    return JsonConvert.DeserializeObject<T>(json);
}

Here's how to use it:

var sfcl = networkClient.ConvertToJson().ConvertToObject<SkyfilterClient>();

How to deselect all selected rows in a DataGridView control?

Thanks Cody heres the c# for ref:

if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hit = dgv_track.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.None)
            {
                dgv_track.ClearSelection();
                dgv_track.CurrentCell = null;
            }
        }

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Python: How to ignore an exception and proceed?

Generic answer

The standard "nop" in Python is the pass statement:

try:
    do_something()
except Exception:
    pass

Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.

Python 2

Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:

try:
    do_something()
except Exception:
    sys.exc_clear()

This clears the last thrown exception.

Python 3

In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

The last parameter to the rgba() function is the "alpha" or "opacity" parameter. If you set it to 0 it will mean "completely transparent", and the first three parameters (the red, green, and blue channels) won't matter because you won't be able to see the color anyway.

With that in mind, I would choose rgba(0, 0, 0, 0) because:

  1. it's less typing,
  2. it keeps a few extra bytes out of your CSS file, and
  3. you will see an obvious problem if the alpha value changes to something undesirable.

You could avoid the rgba model altogether and use the transparent keyword instead, which according to w3.org, is equivalent to "transparent black" and should compute to rgba(0, 0, 0, 0). For example:

h1 {
    background-color: transparent;
}

This saves you yet another couple bytes while your intentions of using transparency are obvious (in case one is unfamiliar with RGBA).

As of CSS3, you can use the transparent keyword for any CSS property that accepts a color.

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

This worked for me after i tryed many solutions:
For some reason the adb process didn't restart itself after installing new packages. Manualy killing adb.exe and attempt to import the project another time solved this problem for me.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

What are bitwise shift (bit-shift) operators and how do they work?

I am writing tips and tricks only. It may be useful in tests and exams.

  1. n = n*2: n = n<<1
  2. n = n/2: n = n>>1
  3. Checking if n is power of 2 (1,2,4,8,...): check !(n & (n-1))
  4. Getting xth bit of n: n |= (1 << x)
  5. Checking if x is even or odd: x&1 == 0 (even)
  6. Toggle the nth bit of x: x ^ (1<<n)

How to change title of Activity in Android?

If you have multiple activities, you can set it like this in AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NumbersActivity"
        android:label="@string/category_numbers"
        android:theme="@style/category_numbers" />
    <activity
        android:name=".FamilyActivity"
        android:label="@string/category_family"
        android:theme="@style/category_family" />
    <activity
        android:name=".ColorsActivity"
        android:label="@string/category_colors"
        android:theme="@style/category_colors" />
    <activity
        android:name=".PhrasesActivity"
        android:label="@string/category_phrases"
        android:theme="@style/category_phrases" />
    <activity
        android:name=".ExperimentActivity"
        android:label="@string/category_experiment"
        android:theme="@style/category_experiment" />
</application>

Is there a way to specify which pytest tests to run from a file?

According to the doc about Run tests by node ids

since you have all node ids in foo.txt, just run

pytest `cat foo.txt | tr '\n' ' '`

this is same with below command (with file content in the question)

pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test

ArrayList filter

I agree with a previous answer that Google Guava is probably helping a lot here, readability-wise:

final Iterables.removeIf(list, new Predicate<String>() {
    @Override
    public boolean apply(String input) {
        if(input.contains("How")) { //or more complex pattern matching
            return true;
        }
        return false;
    }
}); 

Please note that this is basically a duplicate of Guava - How to remove from a list, based on a predicate, keeping track of what was removed?

How to edit the size of the submit button on a form?

<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">

Use this with your requirements.

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

td widths, not working?

Width and/or height in tables are not standard anymore; as Ianzz says, they are deprecated. Instead the best way to do this is to have a block element inside your table cell that will hold the cell open to your desired size:

<table>
    <tr>
        <td valign="top">
            <div class="left_menu">
                <div class="menu_item">
                    <a href="#">Home</a>
                </div>
            </div>
        </td>
        <td valign="top" class="content">Content</td>
    </tr>
</table>

CSS

.content {
    width: 1000px;
}

.left_menu {
    background: none repeat scroll 0 0 #333333;
    border-radius: 5px 5px 5px 5px;
    font-family: Arial,Helvetica,sans-serif;
    font-size: 12px;
    font-weight: bold;
    padding: 5px;
    width: 200px;
}

.menu_item {
    background: none repeat scroll 0 0 #CCCCCC;
    border-bottom: 1px solid #999999;
    border-radius: 5px 5px 5px 5px;
    border-top: 1px solid #FFFFCC;
    cursor: pointer;
    padding: 5px;
}

Styling multi-line conditions in 'if' statements?

Someone has to champion use of vertical whitespace here! :)

if (     cond1 == val1
     and cond2 == val2
     and cond3 == val3
   ):
    do_stuff()

This makes each condition clearly visible. It also allows cleaner expression of more complex conditions:

if (    cond1 == val1
     or 
        (     cond2_1 == val2_1
          and cond2_2 >= val2_2
          and cond2_3 != bad2_3
        )
   ):
    do_more_stuff()

Yes, we're trading off a bit of vertical real estate for clarity. Well worth it IMO.

How to call a button click event from another method

private void PictureBox1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Click Succes");
}

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        PictureBox1_Click(sender, e); //or try this one "this.PictureBox1_Click(sender, AcceptButton);"
    }
}

Where can I download mysql jdbc jar from?

Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.

Download zip file and extract it, with in that you will find mysql-connector-XXX.jar file

If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java

Select the version you want to use and add the dependency in your pom.xml file

jQuery: how to trigger anchor link's click event

Try the following:

$("#myanchor")[0].click()

As simple as that.

Selecting data from two different servers in SQL Server

I know this is an old question but I use synonyms. Supposedly the query is executed within database server A, and looks for a table in a database server B that does not exist on server A. Add then a synonym on A database that calls your table from server B. Your query doesn't have to include any schemas, or different database names, just call the table name per usual and it will work.

There's no need to link servers as synonyms per say are sort of linking.

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

Can we open pdf file using UIWebView on iOS?

An update to Martin Alléus's answer, to get the full screen whether it is a phone or a iPad without having to hard code:

CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];

NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Measure the time it takes to execute a t-sql query

even better, this will measure the average of n iterations of your query! Great for a more accurate reading.

declare @tTOTAL int = 0
declare @i integer = 0
declare @itrs integer = 100

while @i < @itrs
begin
declare @t0 datetime = GETDATE()

--your query here

declare @t1 datetime = GETDATE()

set @tTotal = @tTotal + DATEDIFF(MICROSECOND,@t0,@t1)

set @i = @i + 1
end

select @tTotal/@itrs

Resize Google Maps marker icon image

If you are using vue2-google-maps like me, the code to set the size looks like this:

<gmap-marker
  ..
  :icon="{
    ..
    anchor: { x: iconSize, y: iconSize },
    scaledSize: { height: iconSize, width: iconSize },
  }"
>

Using import fs from 'fs'

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

How to swap String characters in Java?

static String  string_swap(String str, int x, int y)
{

    if( x < 0 || x >= str.length() || y < 0 || y >= str.length())
    return "Invalid index";

    char arr[] = str.toCharArray();
    char tmp = arr[x];
    arr[x] = arr[y];
    arr[y] = tmp;

    return new String(arr);
}

NuGet auto package restore does not work with MSBuild

It took me some time to figure out the whole picture and I'd like to share here.

Visual Studio has two approaches to use package restore: Automatic Package Restore and MSBuild-Integrated package restore. The 'MSBuild-Integrated Package Restore' restores packages DURING the building process that might cause issues in some scenarios. The 'Automatic Package Restore' is the recommended approach by the NuGet team.

There are several steps to to make 'Automatic Package Restore' work:

  1. In Visual Studio, Tools -> Extensions and Updates, Upgrade NuGet if there is a newer version (Version 2.7 or later)

  2. If you use TFS, in your solution's .nuget folder, remove the NuGet.exe and NuGet.targes files. Then edit NuGet.Config to not check in NuGet packages:

    <configuration>  
      <solution>  
        <add key="disableSourceControlIntegration" value="true" />  
      </solution>  
    </configuration> 
    

    If you checked in the solution's packages folder to TFS before, delete the folder and check in the deletion of package folder deletion.

    If you don't use TFS, delete the .nuget folder.

  3. In each project file (.csproj or .vbproj) in your solution, remove the line that references NuGet.targets file. The reference looks like this:

    <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
    

    Remove this line in every project file in your solution.

  4. In Visual Studio menu, either through

    Tools -> Options -> Package Manager -> General or Tools -> NuGet Package Manager -> Package Manager Settings

    please enable the following two options 1) 'Allow NuGet to download missing packages' 2) 'Automatically check for missing packages during build in Visual Studio'

  5. Test your package restore configuration by the following steps

    • Save your solution and close Visual Studio
    • Delete your solution's packages folder
    • Start Visual Studio, open your solution and rebuild it.

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

This is still the top post when searching, but it's no longer valid. Best answer is here, but the TLDR is

<c-b>:resize-window -A

How can I autoformat/indent C code in vim?

I like to use the program Artistic Style. According to their website:

Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.

It runs in Window, Linux and Mac. It will do things like indenting, replacing tabs with spaces or vice-versa, putting spaces around operations however you like (converting if(x<2) to if ( x<2 ) if that's how you like it), putting braces on the same line as function definitions, or moving them to the line below, etc. All the options are controlled by command line parameters.

In order to use it in vim, just set the formatprg option to it, and then use the gq command. So, for example, I have in my .vimrc:

autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ -T4pb

so that whenever I open a .cpp file, formatprg is set with the options I like. Then, I can type gg to go to the top of the file, and gqG to format the entire file according to my standards. If I only need to reformat a single function, I can go to the top of the function, then type gq][ and it will reformat just that function.

The options I have for astyle, -T4pb, are just my preferences. You can look through their docs, and change the options to have it format the code however you like.

Here's a demo. Before astyle:

int main(){if(x<2){x=3;}}

float test()
{
if(x<2)
x=3;
}

After astyle (gggqG):

int main()
{
    if (x < 2)
    {
        x = 3;
    }
}

float test()
{
    if (x < 2)
        x = 3;
}

Hope that helps.

Git status shows files as changed even though contents are the same

I recently moved my local repo from one Windows x64 system to another. The first time I use it half my files appear to be changed. Thanks to Jacek Szybisz for sending me to Configuring Git to handle line endings where I found the following one-liner that removed all the no-change files from Gitkraken's change queue:

git config --global core.autocrlf true

How to check version of a CocoaPods framework

To check version of cocoapods from terminal:

For Sudoless:

gem which cocoapods

For Sudo:

sudo gem which cocoapods

Also note: If you want to edit podfile or podfile.lock don't edit it in editors. Open only with XCode.

How to join on multiple columns in Pyspark?

An alternative approach would be:

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))

df = df1.join(df2, ['x1','x2'])
df.show()

which outputs:

+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  2|  b|3.0|0.0|
+---+---+---+---+

With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.


Whenever the columns in the two tables have different names, (let's say in the example above, df2 has the columns y1, y2 and y4), you could use the following syntax:

df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])

How to override the path of PHP to use the MAMP path?

Everytime you save MAMP config (PHP section), it saves the current version of PHP on ~/.profile file and creates the alias for php, pear and pecl, to point to the current configured version. (Note: you need to check "Make this version available on the command line" option in MAMP)

However, you need to refresh your terminal (open another session) to get this file refreshed. You can also type source ~/.profile to refesh the aliases manually.

If you want to extract this curerent version in a PHP_VERSION variable - as commented above - for further use, you can do:

export PHP_VERSION=`grep "alias php" ~/.profile | cut -d"/" -f6 | cut -c4-`

And then you'll have $PHP_VERSION available with the current version of MAMP.

Finally, if you want to run your php using the current configured version on mamp, you just need to add to your ~/.bash_profile the following:

export PHP_VERSION=`grep "alias php" ~/.profile | cut -d"/" -f6 | cut -c4-`
export PHPRC="/Library/Application Support/appsolute/MAMP PRO/conf/" #point to your php.ini folder to use the same php settings
export PATH=/Applications/MAMP/bin/php/php$PHP_VERSION/bin:$PATH

Now, even script that relies on /usr/bin/env php will read the correct version from Mamp config.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Looks like the question has been long ago answered but the solution did not work for me. When I was getting that error, I was able to fix the problem by downloading PyWin32

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

MySQL INNER JOIN select only one row from second table

You can try this:

SELECT u.*, p.*
FROM users AS u LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY userid ORDER BY [Date] DESC) AS RowNo
    FROM payments  
) AS p ON u.userid = p.userid AND p.RowNo=1

Which type of folder structure should be used with Angular 2?

Maybe something like this structure:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- pages
              |-- home
              |-- home.component.ts|html|scss|spec
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- authentication
           |-- authentication.service.ts|spec.ts
       |-- footer
           |-- footer.component.ts|html|scss|spec.ts
       |-- guards
           |-- auth.guard.ts
           |-- no-auth-guard.ts
           |-- admin-guard.ts 
       |-- http
           |-- user
               |-- user.service.ts|spec.ts
           |-- api.service.ts|spec.ts
       |-- interceptors
           |-- api-prefix.interceptor.ts
           |-- error-handler.interceptor.ts
           |-- http.token.interceptor.ts
       |-- mocks
           |-- user.mock.ts
       |-- services
           |-- srv1.service.ts|spec.ts
           |-- srv2.service.ts|spec.ts
       |-- header
           |-- header.component.ts|html|scss|spec.ts
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |-- shared
          |-- components
              |-- loader
                  |-- loader.component.ts|html|scss|spec.ts
          |-- buttons
              |-- favorite-button
                  |-- favorite-button.component.ts|html|scss|spec.ts
              |-- collapse-button
                  |-- collapse-button.component.ts|html|scss|spec.ts
          |-- directives
              |-- auth.directive.ts|spec.ts
          |-- pipes
              |-- capitalize.pipe.ts
              |-- safe.pipe.ts
     |-- configs
         |-- app-settings.config.ts
         |-- dt-norwegian.config.ts
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
     |-- assets

WebSockets protocol vs HTTP

1) Why is the WebSockets protocol better?

WebSockets is better for situations that involve low-latency communication especially for low latency for client to server messages. For server to client data you can get fairly low latency using long-held connections and chunked transfer. However, this doesn't help with client to server latency which requires a new connection to be established for each client to server message.

Your 48 byte HTTP handshake is not realistic for real-world HTTP browser connections where there is often several kilobytes of data sent as part of the request (in both directions) including many headers and cookie data. Here is an example of a request/response to using Chrome:

Example request (2800 bytes including cookie data, 490 bytes without cookie data):

GET / HTTP/1.1
Host: www.cnn.com
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.68 Safari/537.17
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: [[[2428 byte of cookie data]]]

Example response (355 bytes):

HTTP/1.1 200 OK
Server: nginx
Date: Wed, 13 Feb 2013 18:56:27 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: CG=US:TX:Arlington; path=/
Last-Modified: Wed, 13 Feb 2013 18:55:22 GMT
Vary: Accept-Encoding
Cache-Control: max-age=60, private
Expires: Wed, 13 Feb 2013 18:56:54 GMT
Content-Encoding: gzip

Both HTTP and WebSockets have equivalent sized initial connection handshakes, but with a WebSocket connection the initial handshake is performed once and then small messages only have 6 bytes of overhead (2 for the header and 4 for the mask value). The latency overhead is not so much from the size of the headers, but from the logic to parse/handle/store those headers. In addition, the TCP connection setup latency is probably a bigger factor than the size or processing time for each request.

2) Why was it implemented instead of updating HTTP protocol?

There are efforts to re-engineer the HTTP protocol to achieve better performance and lower latency such as SPDY, HTTP 2.0 and QUIC. This will improve the situation for normal HTTP requests, but it is likely that WebSockets and/or WebRTC DataChannel will still have lower latency for client to server data transfer than HTTP protocol (or it will be used in a mode that looks a lot like WebSockets anyways).

Update:

Here is a framework for thinking about web protocols:

  • TCP: low-level, bi-directional, full-duplex, and guaranteed order transport layer. No browser support (except via plugin/Flash).
  • HTTP 1.0: request-response transport protocol layered on TCP. The client makes one full request, the server gives one full response, and then the connection is closed. The request methods (GET, POST, HEAD) have specific transactional meaning for resources on the server.
  • HTTP 1.1: maintains the request-response nature of HTTP 1.0, but allows the connection to stay open for multiple full requests/full responses (one response per request). Still has full headers in the request and response but the connection is re-used and not closed. HTTP 1.1 also added some additional request methods (OPTIONS, PUT, DELETE, TRACE, CONNECT) which also have specific transactional meanings. However, as noted in the introduction to the HTTP 2.0 draft proposal, HTTP 1.1 pipelining is not widely deployed so this greatly limits the utility of HTTP 1.1 to solve latency between browsers and servers.
  • Long-poll: sort of a "hack" to HTTP (either 1.0 or 1.1) where the server does not respond immediately (or only responds partially with headers) to the client request. After a server response, the client immediately sends a new request (using the same connection if over HTTP 1.1).
  • HTTP streaming: a variety of techniques (multipart/chunked response) that allow the server to send more than one response to a single client request. The W3C is standardizing this as Server-Sent Events using a text/event-stream MIME type. The browser API (which is fairly similar to the WebSocket API) is called the EventSource API.
  • Comet/server push: this is an umbrella term that includes both long-poll and HTTP streaming. Comet libraries usually support multiple techniques to try and maximize cross-browser and cross-server support.
  • WebSockets: a transport layer built-on TCP that uses an HTTP friendly Upgrade handshake. Unlike TCP, which is a streaming transport, WebSockets is a message based transport: messages are delimited on the wire and are re-assembled in-full before delivery to the application. WebSocket connections are bi-directional, full-duplex and long-lived. After the initial handshake request/response, there is no transactional semantics and there is very little per message overhead. The client and server may send messages at any time and must handle message receipt asynchronously.
  • SPDY: a Google initiated proposal to extend HTTP using a more efficient wire protocol but maintaining all HTTP semantics (request/response, cookies, encoding). SPDY introduces a new framing format (with length-prefixed frames) and specifies a way to layering HTTP request/response pairs onto the new framing layer. Headers can be compressed and new headers can be sent after the connection has been established. There are real world implementations of SPDY in browsers and servers.
  • HTTP 2.0: has similar goals to SPDY: reduce HTTP latency and overhead while preserving HTTP semantics. The current draft is derived from SPDY and defines an upgrade handshake and data framing that is very similar the the WebSocket standard for handshake and framing. An alternate HTTP 2.0 draft proposal (httpbis-speed-mobility) actually uses WebSockets for the transport layer and adds the SPDY multiplexing and HTTP mapping as an WebSocket extension (WebSocket extensions are negotiated during the handshake).
  • WebRTC/CU-WebRTC: proposals to allow peer-to-peer connectivity between browsers. This may enable lower average and maximum latency communication because as the underlying transport is SDP/datagram rather than TCP. This allows out-of-order delivery of packets/messages which avoids the TCP issue of latency spikes caused by dropped packets which delay delivery of all subsequent packets (to guarantee in-order delivery).
  • QUIC: is an experimental protocol aimed at reducing web latency over that of TCP. On the surface, QUIC is very similar to TCP+TLS+SPDY implemented on UDP. QUIC provides multiplexing and flow control equivalent to HTTP/2, security equivalent to TLS, and connection semantics, reliability, and congestion control equivalentto TCP. Because TCP is implemented in operating system kernels, and middlebox firmware, making significant changes to TCP is next to impossible. However, since QUIC is built on top of UDP, it suffers from no such limitations. QUIC is designed and optimised for HTTP/2 semantics.

References:

Laravel Eloquent: How to get only certain columns from joined tables

On Laravel 5.5, the cleanest way to do this is:

Theme::with('user:userid,name,address')->get()

You add a colon and the fields you wish to select separated by a comma and without a space between them.

How can I do GUI programming in C?

Use win APIs in your main function:

  1. RegisterClassEx() note: you have to provide a pointer to a function (usually called WndProc) which handles windows messages such as WM_CREATE, WM_COMMAND etc
  2. CreateWindowEx()
  3. ShowWindow()
  4. UpdateWindow()

Then write another function which handles win's messages (mentioned in #1). When you receive the message WM_CREATE you have to call CreateWindow(). The class is what control is that window, for example "edit" is a text box and "button" is a.. button :). You have to specify an ID for each control (of your choice but unique among all). CreateWindow() returns a handle to that control, which needs to be memorized. When the user clicks on a control you receive the WM_COMMAND message with the ID of that control. Here you can handle that event. You might find useful SetWindowText() and GetWindowText() which allows you to set/get the text of any control.
You will need only the win32 SDK. You can get it here.

Set NOW() as Default Value for datetime datatype?

`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Can be used to update the timestamp on update.

PHP Array to JSON Array using json_encode();

If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index

How to: "Separate table rows with a line"

There are several ways to do that. Using HTML alone, you can write

<table border=1 frame=void rules=rows>

or, if you want a border above the first row and below the last row too,

<table border=1 frame=hsides rules=rows>

This is rather inflexible, though; you cannot e.g. make the lines dotted this way, or thicker than one pixel. This is why in the past people used special separator rows, consisting of nothing but some content intended to produce a line (it gets somewhat dirty, especially when you need to make rows e.g. just a few pixels high, but it’s possible).

For the most of it, people nowadays use CSS border properties for the purpose. It’s fairly simple and cross-browser. But note that to make the lines continuous, you need to prevent spacing between cells, using either the cellspacing=0 attribute in the table tag or the CSS rule table { border-collapse: collapse; }. Removing such spacing may necessitate adding some padding (with CSS, preferably) inside the cells.

At the simplest, you could use

<style>
table {
  border-collapse: collapse;
}
tr { 
  border: solid;
  border-width: 1px 0;
}
</style>

This puts a border above the first row and below the last row too. To prevent that, add e.g. the following into the style sheet:

tr:first-child {
  border-top: none;
}
tr:last-child {
  border-bottom: none;
}

How to send and retrieve parameters using $state.go toParams and $stateParams?

The solution we came to having a state that took 2 parameters was changing:

.state('somestate', {
  url: '/somestate',
  views: {...}
}

to

.state('somestate', {
  url: '/somestate?id=:&sub=:',
  views: {...}
}

Return background color of selected cell

If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:

ActiveCell.DisplayFormat.Interior.Color

This also seems to work just fine on regular cells.

iOS 6 apps - how to deal with iPhone 5 screen size?

I have just finished updating and sending an iOS 6.0 version of one of my Apps to the store. This version is backwards compatible with iOS 5.0, thus I kept the shouldAutorotateToInterfaceOrientation: method and added the new ones as listed below.

I had to do the following:

Autorotation is changing in iOS 6. In iOS 6, the shouldAutorotateToInterfaceOrientation: method of UIViewController is deprecated. In its place, you should use the supportedInterfaceOrientationsForWindow: and shouldAutorotate methods. Thus, I added these new methods (and kept the old for iOS 5 compatibility):

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;    
}
  • Used the view controller’s viewWillLayoutSubviews method and adjust the layout using the view’s bounds rectangle.
  • Modal view controllers: The willRotateToInterfaceOrientation:duration:,
    willAnimateRotationToInterfaceOrientation:duration:, and
    didRotateFromInterfaceOrientation: methods are no longer called on any view controller that makes a full-screen presentation over
    itself
    —for example, presentViewController:animated:completion:.
  • Then I fixed the autolayout for views that needed it.
  • Copied images from the simulator for startup view and views for the iTunes store into PhotoShop and exported them as png files.
  • The name of the default image is: [email protected] and the size is 640×1136. It´s also allowed to supply 640×1096 for the same portrait mode (Statusbar removed). Similar sizes may also be supplied in landscape mode if your app only allows landscape orientation on the iPhone.
  • I have dropped backward compatibility for iOS 4. The main reason for that is because support for armv6 code has been dropped. Thus, all devices that I am able to support now (running armv7) can be upgraded to iOS 5.
  • I am also generation armv7s code to support the iPhone 5 and thus can not use any third party frameworks (as Admob etc.) until they are updated.

That was all but just remember to test the autorotation in iOS 5 and iOS 6 because of the changes in rotation.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

Depending on how much metadata you want, this is working for me: where could be the whole thing like Northwind.dbo.Products or just Products

SELECT c.name Field, 
    t.name Type,
    c.Precision, 
    c.Scale,
    c.is_nullable,
    c.collation_name 
FROM sys.columns c 
INNER JOIN sys.types t ON t.system_type_id=c.system_type_id
WHERE object_id=object_id('<table to inspect>')
ORDER BY column_id

What does 'var that = this;' mean in JavaScript?

Here is an example `

$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();

            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                    var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'. 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.

`$(document).ready(function() {
        var lastItem = null;
        $(".our-work-group > p > a").click(function(e) {
            e.preventDefault();
            var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
            if (item == lastItem) {
                lastItem = null;
                var that = this;
                $('.our-work-single-page').show();
            } else {
                lastItem = item;
                $('.our-work-single-page').each(function() {
                   ***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
                    var imgAlt = $(this).find('img').attr('alt'); 
                    if (imgAlt != item) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }

        });
    });`

.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.

How do I create a batch file timer to execute / call another batch throughout the day

For the timer part of your script i highly reccomend using:

echo.
echo Waiting For One Hour... 
TIMEOUT /T 3600 /NOBREAK
echo.
echo (Put some Other Processes Here)
echo.
pause >nul

This script waits for 1 hour (3600 seconds) and then continues on with the script and the user cannot press any buttons to bypass the timer (besides CTRL+C).

You can use

Timeout /t 3600 /nobreak >nul

If you don't want to see a countdown on the screen.

Laravel-5 'LIKE' equivalent (Eloquent)

If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.

Try this

BookingDates::where('email', Input::get('email'))
    ->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

Installing Tomcat 7 as Service on Windows Server 2008

its done through service.bat file in apache tomcat7

visit this blog .. install tomcat7 on windows

string decode utf-8

the core functions are getBytes(String charset) and new String(byte[] data). you can use these functions to do UTF-8 decoding.

UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String() is the byte array, which calling is equal to new String(bytes, "UTF-8")

Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.

The decoding sentence should be

String decoded = new String(encoded.getBytes("ISO-8859-1"));

MySQL - UPDATE query based on SELECT Query

UPDATE 
  receipt_invoices dest,
  (
    SELECT 
      `receipt_id`,
      CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat 
    FROM
      receipt 
    WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total 
      AND vat_percentage = 12
  ) src 
SET
  dest.price = src.witoutvat,
  dest.amount = src.witoutvat 
WHERE col_tobefixed = 1 
  AND dest.`receipt_id` = src.receipt_id ;

Hope this will help you in a case where you have to match and update between two tables.

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

Converting Pandas dataframe into Spark dataframe error

I received a similar error message once, in my case it was because my pandas dataframe contained NULLs. I will recommend to try & handle this in pandas before converting to spark (this resolved the issue in my case).

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

I am not sure if this is the best way to use GSON, but works for me. You can use some like this on the MainActivity:

 public void readJson() {
    dataArrayList = new ArrayList<>();
    String json = "[\n" + IOHelper.getData(this) + "\n]\n";
    Log.d(TAG, json);
    try{
        JSONArray channelSearchEnums = new JSONArray(json);

        for(int i=0; i< channelSearchEnums.length(); i++)
        {
            JSONObject enum = channelSearchEnums.getJSONObject(i);
            ChannelSearchEnum channel = new ChannelSearchEnum(
                   enum.getString("updated_at"), enum.getString("fetched_at"),
                   enum.getString("description"), enum.getString("language"),
                   enum.getString("title"), enum.getString("url"),
                   enum.getString("icon_url"), enum.getString("logo_url"),
                   enum.getString("id"), enum.getString("modified"))         

                   dataArrayList.add(channel);
        }

         //The code and place you want to show your data            

    }catch (Exception e)
    {
        Log.d(TAG, e.getLocalizedMessage());
    }
}

You only have strings, but if you would have doubles or int, you could put getDouble or getInt too.

The method of IOHelper class is the next (Here, the path is save on the internal Storage):

 public static String getData(Context context) {
    try {
        File f = new File(context.getFilesDir().getPath() + "/" + fileName);
        //check whether file exists
        FileInputStream is = new FileInputStream(f);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        return new String(buffer);
    } catch (IOException e) {
        Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
        return null;
    }
}

If you want more information about this, you can see this video, where I get the code of readJson(); and this thread where I get the code of getData().

What are the benefits of using C# vs F# or F# vs C#?

F# is not yet-another-programming-language if you are comparing it to C#, C++, VB. C#, C, VB are all imperative or procedural programming languages. F# is a functional programming language.

Two main benefits of functional programming languages (compared to imperative languages) are 1. that they don't have side-effects. This makes mathematical reasoning about properties of your program a lot easier. 2. that functions are first class citizens. You can pass functions as parameters to another functions just as easily as you can other values.

Both imperative and functional programming languages have their uses. Although I have not done any serious work in F# yet, we are currently implementing a scheduling component in one of our products based on C# and are going to do an experiment by coding the same scheduler in F# as well to see if the correctness of the implementation can be validated more easily than with the C# equivalent.

java.lang.NoClassDefFoundError: Could not initialize class XXX

I encounter the same problem. I inited a bean object in static block like below:

static {
    try{
        mqttConfiguration = SpringBootBeanUtils.<MqttConfiguration>getBean(MqttConfiguration.class);
    }catch (Throwable e){
        System.out.println(e);
    }
 }

Just because the process the my bean obejct inition caused a NPE, I get trouble into it. So I think you should check you static code block carefully.

Focus Next Element In Tab Index

I've never implemented this, but I've looked into a similar problem, and here's what I would try.

Try this first

First, I would see if you could simply fire a keypress event for the Tab key on the element that currently has focus. There may be a different way of doing this for different browsers.

If that doesn't work, you'll have to work harder…

Referencing the jQuery implementation, you must:

  1. Listen for Tab and Shift+Tab
  2. Know which elements are tab-able
  3. Understand how tab order works

1. Listen for Tab and Shift+Tab

Listening for Tab and Shift+Tab are probably well-covered elsewhere on the web, so I'll skip that part.

2. Know which elements are tab-able

Knowing which elements are tab-able is trickier. Basically, an element is tab-able if it is focusable and does not have the attribute tabindex="-1" set. So then we must ask which elements are focusable. The following elements are focusable:

  • input, select, textarea, button, and object elements that aren't disabled.
  • a and area elements that have an href or have a numerical value for tabindex set.
  • any element that has a numerical value for tabindex set.

Furthermore, an element is focusable only if:

  • None of its ancestors are display: none.
  • The computed value of visibility is visible. This means that the nearest ancestor to have visibility set must have a value of visible. If no ancestor has visibility set, then the computed value is visible.

More details are in another Stack Overflow answer.

3. Understand how tab order works

The tab order of elements in a document is controlled by the tabindex attribute. If no value is set, the tabindex is effectively 0.

The tabindex order for the document is: 1, 2, 3, …, 0.

Initially, when the body element (or no element) has focus, the first element in the tab order is the lowest non-zero tabindex. If multiple elements have the same tabindex, you then go in document order until you reach the last element with that tabindex. Then you move to the next lowest tabindex and the process continues. Finally, finish with those elements with a zero (or empty) tabindex.

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Python: How to create a unique file name?

If you want to make temporary files in Python, there's a module called tempfile in Python's standard libraries. If you want to launch other programs to operate on the file, use tempfile.mkstemp() to create files, and os.fdopen() to access the file descriptors that mkstemp() gives you.

Incidentally, you say you're running commands from a Python program? You should almost certainly be using the subprocess module.

So you can quite merrily write code that looks like:

import subprocess
import tempfile
import os

(fd, filename) = tempfile.mkstemp()
try:
    tfile = os.fdopen(fd, "w")
    tfile.write("Hello, world!\n")
    tfile.close()
    subprocess.Popen(["/bin/cat", filename]).wait()        
finally:
    os.remove(filename)

Running that, you should find that the cat command worked perfectly well, but the temporary file was deleted in the finally block. Be aware that you have to delete the temporary file that mkstemp() returns yourself - the library has no way of knowing when you're done with it!

(Edit: I had presumed that NamedTemporaryFile did exactly what you're after, but that might not be so convenient - the file gets deleted immediately when the temp file object is closed, and having other processes open the file before you've closed it won't work on some platforms, notably Windows. Sorry, fail on my part.)

How to find length of a string array?

Well, in this case the car variable will be null, so dereferencing it (as you do when you access car.length) will throw a NullPointerException.

In fact, you can't access that variable at all until some value has definitely been assigned to it - otherwise the compiler will complain that "variable car might not have been initialized".

What is it you're trying to do here (it's not clear to me exactly what "solution" you're looking for)?

How to save and extract session data in codeigniter

initialize the Session class in the constructor of controller using

$this->load->library('session');

for example :

 function __construct()
   {
    parent::__construct();
    $this->load->model('user','',TRUE);
    $this->load->model('user_activity','',TRUE);
    $this->load->library('session');
   }

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

Setting a divs background image to fit its size?

If you'd like to use CSS3, you can do it pretty simply using background-size, like so:

background-size: 100%;

It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.

VB.NET - Click Submit Button on Webbrowser page

I searched for any solution to not use the "SendKeys(CHR(13))" methode I ever used to submit stuff in Browser. In this case I was happy to see your

InvokeMember("click")

but dont know why you know that you have to write "click" in there. Anyway Thanks

Error: [ng:areq] from angular controller

Check the name of your angular module...what is the name of your module in your app.js?

In your TransportersController, you have:

angular.module('mean.transporters')

and in your TransportersService you have:

angular.module('transporterService', [])

You probably want to reference the same module in each:

angular.module('myApp')

What is a raw type and why shouldn't we use it?

A raw type is the name of a generic class or interface without any type arguments. For example, given the generic Box class:

public class Box<T> {
    public void set(T t) { /* ... */ }
    // ...
}

To create a parameterized type of Box<T>, you supply an actual type argument for the formal type parameter T:

Box<Integer> intBox = new Box<>();

If the actual type argument is omitted, you create a raw type of Box<T>:

Box rawBox = new Box();

Therefore, Box is the raw type of the generic type Box<T>. However, a non-generic class or interface type is not a raw type.

Raw types show up in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0. When using raw types, you essentially get pre-generics behavior — a Box gives you Objects. For backward compatibility, assigning a parameterized type to its raw type is allowed:

Box<String> stringBox = new Box<>();
Box rawBox = stringBox;               // OK

But if you assign a raw type to a parameterized type, you get a warning:

Box rawBox = new Box();           // rawBox is a raw type of Box<T>
Box<Integer> intBox = rawBox;     // warning: unchecked conversion

You also get a warning if you use a raw type to invoke generic methods defined in the corresponding generic type:

Box<String> stringBox = new Box<>();
Box rawBox = stringBox;
rawBox.set(8);  // warning: unchecked invocation to set(T)

The warning shows that raw types bypass generic type checks, deferring the catch of unsafe code to runtime. Therefore, you should avoid using raw types.

The Type Erasure section has more information on how the Java compiler uses raw types.

Unchecked Error Messages

As mentioned previously, when mixing legacy code with generic code, you may encounter warning messages similar to the following:

Note: Example.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

This can happen when using an older API that operates on raw types, as shown in the following example:

public class WarningDemo {
    public static void main(String[] args){
        Box<Integer> bi;
        bi = createBox();
    }

    static Box createBox(){
        return new Box();
    }
}

The term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety. The "unchecked" warning is disabled, by default, though the compiler gives a hint. To see all "unchecked" warnings, recompile with -Xlint:unchecked.

Recompiling the previous example with -Xlint:unchecked reveals the following additional information:

WarningDemo.java:4: warning: [unchecked] unchecked conversion
found   : Box
required: Box<java.lang.Integer>
        bi = createBox();
                      ^
1 warning

To completely disable unchecked warnings, use the -Xlint:-unchecked flag. The @SuppressWarnings("unchecked") annotation suppresses unchecked warnings. If you are unfamiliar with the @SuppressWarnings syntax, see Annotations.

Original source: Java Tutorials

How to revert the last migration?

If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake migrations.

./manage.py migrate <name> --ignore-ghost-migrations --merge --fake

For django version < 1.7 this will create entry in south_migrationhistory table, you need to delete that entry.

Now you'll be able to revert back the migration easily.

PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.

Configuring so that pip install can work from github

Clone target repository same way like you cloning any other project:

git clone [email protected]:myuser/foo.git

Then install it in develop mode:

cd foo
pip install -e .

You can change anything you wan't and every code using foo package will use modified code.

There 2 benefits ot this solution:

  1. You can install package in your home projects directory.
  2. Package includes .git dir, so it's regular Git repository. You can push to your fork right away.

Java system properties and environment variables

Retrieve Button value with jQuery

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {
            alert($(this).attr("value"));
        });
    });
</script>

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

How to fix "unable to write 'random state' " in openssl

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

How do you redirect to a page using the POST verb?

try this one

return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");

How to check if a string contains only digits in Java

You must allow for more than a digit (the + sign) as in:

String regex = "[0-9]+"; 
String data = "23343453"; 
System.out.println(data.matches(regex));

EC2 Instance Cloning

The easier way is through the web management console:

  1. go to the instance
  2. select the instance and click on instance action
  3. create image

Once you have an image you can launch another cloned instance, data and all. :)

How can I detect when an Android application is running in the emulator?

if (Build.BRAND.equalsIgnoreCase("generic")) {
    // Is the emulator
}

All BUILD references are build.prop values, so you have to consider that if you are going to put this into release code, you may have some users with root that have modified theirs for whatever reason. There are virtually no modifications that require using generic as the brand unless specifically trying to emulate the emulator.

Fingerprint is the build compile and kernel compile signature. There are builds that use generic, usually directly sourced from Google.

On a device that has been modified, the IMEI has a possibility of being zeroed out as well, so that is unreliable unless you are blocking modified devices altogether.

Goldfish is the base android build that all other devices are extended from. EVERY Android device has an init.goldfish.rc unless hacked and removed for unknown reasons.

C++ template constructor

template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;

the above helpers let you work with types as values.

class A {
  template<class T>
  A( tag<T> );
};

the tag<T> type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:

auto a = A(tag<int>{});

You can pass in more than one type:

class A {
  template<class T, class U, class V>
  A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

My resolution was kind of stupid.

  • I installed a copy of .net 3.5

  • Created another app pool and selected .net 3.5 (it says 2.0.5077 in the drop down)

  • Added my website to that app pool

  • Recycled the old and new pools and the site started working.

It came down to me not having 3.5 installed even though the turn on windows features said I did and creating another app pool to use. I hope this helps others.

Is there a way to delete all the data from a topic or delete the topic before every run?

Tested with kafka 0.10

1. stop zookeeper & Kafka server,
2. then go to 'kafka-logs' folder , there you will see list of kafka topic folders, delete folder with topic name
3. go to 'zookeeper-data' folder , delete data inside that.
4. start zookeeper & kafka server again.

Note : if you are deleting topic folder/s inside kafka-logs but not from zookeeper-data folder, then you will see topics are still there.

Joining Multiple Tables - Oracle

I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, and CROSS JOIN elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM clause and all the join conditions are put in the the WHERE clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.

I'd rewrite your query as:

SELECT bc.firstname,
       bc.lastname,
       b.title,
       TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
       p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
  ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN  book_order bo
  ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
  ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';

Share and enjoy.

Rename MySQL database

In case you need to do that from the command line, just copy, adapt & paste this snippet:

mysql -e "CREATE DATABASE \`new_database\`;"
for table in `mysql -B -N -e "SHOW TABLES;" old_database`
do 
  mysql -e "RENAME TABLE \`old_database\`.\`$table\` to \`new_database\`.\`$table\`"
done
mysql -e "DROP DATABASE \`old_database\`;"

How can I get zoom functionality for images?

You could also try out http://code.google.com/p/android-multitouch-controller/

The library is really great, although initially a little hard to grasp.

Link vs compile vs controller

this is a good sample for understand directive phases http://codepen.io/anon/pen/oXMdBQ?editors=101

var app = angular.module('myapp', [])

app.directive('slngStylePrelink', function() {
    return {
        scope: {
            drctvName: '@'
        },
        controller: function($scope) {
            console.log('controller for ', $scope.drctvName);
        },
        compile: function(element, attr) {
            console.log("compile for ", attr.name)
            return {
                post: function($scope, element, attr) {
                    console.log('post link for ', attr.name)
                },
                pre: function($scope, element, attr) {
                    $scope.element = element;
                    console.log('pre link for ', attr.name)
                        // from angular.js 1.4.1
                    function ngStyleWatchAction(newStyles, oldStyles) {
                        if (oldStyles && (newStyles !== oldStyles)) {
                            forEach(oldStyles, function(val, style) {
                                element.css(style, '');
                            });
                        }
                        if (newStyles) element.css(newStyles);
                    }

                    $scope.$watch(attr.slngStylePrelink, ngStyleWatchAction, true);

                    // Run immediately, because the watcher's first run is async
                    ngStyleWatchAction($scope.$eval(attr.slngStylePrelink));
                }
            };
        }
    };
});

html

<body ng-app="myapp">
    <div slng-style-prelink="{height:'500px'}" drctv-name='parent' style="border:1px solid" name="parent">
        <div slng-style-prelink="{height:'50%'}" drctv-name='child' style="border:1px solid red" name='child'>
        </div>
    </div>
</body>

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

How to show SVG file on React Native?

Use https://github.com/kristerkari/react-native-svg-transformer

In this package it is mentioned that .svg files are not supported in React Native v0.57 and lower so use .svgx extension for svg files.

For web or react-native-web use https://www.npmjs.com/package/@svgr/webpack


To render svg files using react-native-svg-uri with react-native version 0.57 and lower, you need to add following files to your root project

Note: change extension svg to svgx

step 1: add file transformer.js to project's root

// file: transformer.js

const cleanupSvg = require('./cleanup-svg');

const upstreamTransformer = require("metro/src/transformer");

// const typescriptTransformer = require("react-native-typescript-transformer");
// const typescriptExtensions = ["ts", "tsx"];

const svgExtensions = ["svgx"]

// function cleanUpSvg(text) {
//   text = text.replace(/width="([#0-9]+)px"/gi, "");
//    text = text.replace(/height="([#0-9]+)px"/gi, "");
//    return text;
// }

function fixRenderingBugs(content) {
  // content = cleanUpSvg(content); // cleanupSvg removes width and height attributes from svg
  return "module.exports = `" + content + "`";
}


module.exports.transform = function ({ src, filename, options }) {
  // if (typescriptExtensions.some(ext => filename.endsWith("." + ext))) {
  //  return typescriptTransformer.transform({ src, filename, options })
  // }

  if (svgExtensions.some(ext => filename.endsWith("." + ext))) {
    return upstreamTransformer.transform({
      src: fixRenderingBugs(src),
      filename,
      options
    })
  }

  return upstreamTransformer.transform({ src, filename, options });
}

step 2: add rn-cli.config.js to project's root

module.exports = {
    getTransformModulePath() {
      return require.resolve("./transformer");
    },
    getSourceExts() {
      return [/* "ts", "tsx", */ "svgx"];
    }
  };

The above mentioned solutions will work in production apps too ?

HTML character codes for this ? or this ?

There are several correct ways to display a down-pointing and upward-pointing triangle.

Method 1 : use decimal HTML entity

HTML :

&#9650;
&#9660;

Method 2 : use hexidecimal HTML entity

HTML :

&#x25B2;
&#x25BC;

Method 3 : use character directly

HTML :

?
?

Method 4 : use CSS

HTML :

<span class='icon-up'></span>
<span class='icon-down'></span>

CSS :

.icon-up:before {
    content: "\25B2";
}

.icon-down:before {
    content: "\25BC";
}

Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. &hearts; to display ?).

You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.

Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.

If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.


Background images

A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.

This following code is the base64 for and SVG version of the enter image description here icon :

/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=

When to use background-images or fonts

For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:

SVG images

  • They can have multiple colors
  • They can embed their own CSS and/or be styled by the HTML document
  • They can be loaded as a seperate file, embedded in CSS AND embedded in HTML
  • Each symbol is represented by XML code or base64 code. You cannot use the character directly within your code editor or use an HTML entity
  • Multiple uses of the same symbol implies duplication of the symbol when XML code is embedded in the HTML. Duplication is not required when embedding the file in the CSS or loading it as a seperate file
  • You can not use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.
  • You need some knowledge of SVG and/or base64 encoding
  • Limited or no support in old versions of IE

Icon fonts

  • An icon can have but one fill color, one background color, etc.
  • An icon can be embedded in CSS or HTML. In HTML, you can use the character directly or use an HTML entity to represent it.
  • Some symbols can be displayed without the use of a webfont. Most symbols cannot.
  • Multiple uses of the same symbol implies duplication of the symbol when your character embedded in the HTML. Duplication is not required when embedding the file in the CSS.
  • You can use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon
  • You need no special technical knowledge
  • Support in all major browsers, including old versions of IE

Personally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color, background-color and other color-related CSS rules for fonts.

The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.

Dynamically change color to lighter or darker by percentage CSS (Javascript)

As far as I know, there's no way you can do this in CSS.

But I think that a little server-side logic could easily do as you suggest. CSS stylesheets are normally static assets, but there is no reason they couldn't be dynamically generated by server-side code. Your server-side script would:

  1. Check a URL parameter to determine the user and therefore the user's chosen colour. Use a URL parameter rather than a session variable so that you can still cache the CSS.
  2. Break up the colour into its red, green and blue components
  3. Increment each of the three components by a set amount. Experiment with this to get the results you are after.
  4. Generate CSS incorporating the new colour

Links to this CSS-generating page would look something like:

<link rel="stylesheet" href="http://yoursite.com/custom.ashx?user=1231">

If you don't use the .css extension be sure to set the MIME-type correctly so that the browser knows to interpret the file as CSS.

(Note that to make colours lighter you have to raise each of the RGB values)

How to find the kafka version in linux

There is nothing like kafka --version at this point. So you should either check the version from your kafka/libs/ folder or you can run

find ./libs/ -name \*kafka_\* | head -1 | grep -o '\kafka[^\n]*'

from your kafka folder (and it will do the same for you). It will return you something like kafka_2.9.2-0.8.1.1.jar.asc where 0.8.1.1 is your kafka version.

NumPy array is not JSON serializable

Store as JSON a numpy.ndarray or any nested-list composition.

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]}, cls=NumpyEncoder)
print(json_dump)

Will output:

(2, 3)
{"a": [[1, 2, 3], [4, 5, 6]], "aa": [2, [2, 3, 4], [[1, 2, 3], [4, 5, 6]]], "bb": [2]}

To restore from JSON:

json_load = json.loads(json_dump)
a_restored = np.asarray(json_load["a"])
print(a_restored)
print(a_restored.shape)

Will output:

[[1 2 3]
 [4 5 6]]
(2, 3)

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to make an inline-block element fill the remainder of the line?

You can use calc (100% - 100px) on the fluid element, along with display:inline-block for both elements.

Be aware that there should not be any space between the tags, otherwise you will have to consider that space in your calc too.

.left{
    display:inline-block;
    width:100px;
}
.right{
    display:inline-block;
    width:calc(100% - 100px);
}


<div class=“left”></div><div class=“right”></div>

Quick example: http://jsfiddle.net/dw689mt4/1/

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

Where's the DateTime 'Z' format specifier?

When you use DateTime you are able to store a date and a time inside a variable.

The date can be a local time or a UTC time, it depend on you.

For example, I'm in Italy (+2 UTC)

var dt1 = new DateTime(2011, 6, 27, 12, 0, 0); // store 2011-06-27 12:00:00
var dt2 = dt1.ToUniversalTime()  // store 2011-06-27 10:00:00

So, what happen when I print dt1 and dt2 including the timezone?

dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 12:00:00 +2

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Compiler alert...
// Output: 06/27/2011 10:00:00 +2

dt1 and dt2 contain only a date and a time information. dt1 and dt2 don't contain the timezone offset.

So where the "+2" come from if it's not contained in the dt1 and dt2 variable?

It come from your machine clock setting.

The compiler is telling you that when you use the 'zzz' format you are writing a string that combine "DATE + TIME" (that are store in dt1 and dt2) + "TIMEZONE OFFSET" (that is not contained in dt1 and dt2 because they are DateTyme type) and it will use the offset of the server machine that it's executing the code.

The compiler tell you "Warning: the output of your code is dependent on the machine clock offset"

If i run this code on a server that is positioned in London (+1 UTC) the result will be completly different: instead of "+2" it will write "+1"

...
dt1.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 12:00:00 +1

dt2.ToString("MM/dd/yyyy hh:mm:ss z") 
// Output: 06/27/2011 10:00:00 +1

The right solution is to use DateTimeOffset data type in place of DateTime. It's available in sql Server starting from the 2008 version and in the .Net framework starting from the 3.5 version

What's the difference between map() and flatMap() methods in Java 8?

Simple answer.

The map operation can produce a Stream of Stream.EX Stream<Stream<Integer>>

flatMap operation will only produce Stream of something. EX Stream<Integer>

How can one display images side by side in a GitHub README.md?

This is the best way to make add images/screenshots of your app and keep your repository look clean.

Create a screenshot folder in your repository and add the images you want to display.

Now go to README.md and add this HTML code to form a table.

#### Flutter App Screenshots

<table>
  <tr>
    <td>First Screen Page</td>
     <td>Holiday Mention</td>
     <td>Present day in purple and selected day in pink</td>
  </tr>
  <tr>
    <td><img src="screenshots/Screenshot_1582745092.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745125.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745139.png" width=270 height=480></td>
  </tr>
 </table>

In the <td><img src="(COPY IMAGE PATH HERE)" width=270 height=480></td>

** To get the image path --> Go to the screenshot folder and open the image and on the right most side, you will find Copy path button.

You will get a table like this in your repository--->

enter image description here

Resolve build errors due to circular dependency amongst classes

Things to remember:

  • This won't work if class A has an object of class B as a member or vice versa.
  • Forward declaration is way to go.
  • Order of declaration matters (which is why you are moving out the definitions).
    • If both classes call functions of the other, you have to move the definitions out.

Read the FAQ:

How to specify the bottom border of a <tr>?

tr td 
{
    border-bottom: 2px solid silver;
}

or if you want the border inside the TR tag, you can do this:

tr td {
    box-shadow: inset 0px -2px 0px silver;
}

Send array with Ajax to PHP script

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

What is the difference between DSA and RSA?

Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.

HTML5 Canvas and Anti-aliasing

I haven't needed to turn on anti-alias because it's on by default but I have needed to turn it off. And if it can be turned off it can also be turned on.

ctx.imageSmoothingEnabled = true;

I usually shut it off when I'm working on my canvas rpg so when I zoom in the images don't look blurry.

What charset does Microsoft Excel use when saving files?

Russian Edition offers CSV, CSV (Macintosh) and CSV (DOS).

When saving in plain CSV, it uses windows-1251.

I just tried to save French word Résumé along with the Russian text, it saved it in HEX like 52 3F 73 75 6D 3F, 3F being the ASCII code for question mark.

When I opened the CSV file, the word, of course, became unreadable (R?sum?)

What permission do I need to access Internet from an Android application?

if just using internet then use-

<uses-permission android:name="android.permission.INTERNET" />

if you are getting the state of internet then use also -

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

just above the application tag.

Can a CSS class inherit one or more other classes?

You can add multiple classes to a single DOM element, e.g.

<div class="firstClass secondClass thirdclass fourthclass"></div>

Rules given in later classes (or which are more specific) override. So the fourthclass in that example kind of prevails.

Inheritance is not part of the CSS standard.

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

How to revert uncommitted changes including files and folders?

You can run these two commands:

# Revert changes to modified files.
git reset --hard

# Remove all untracked files and directories.
# '-f' is force, '-d' is remove directories.
git clean -fd

Get current url in Angular

other.component.ts

So final correct solution is :

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

    @Component({
      selector: 'app-other',
      templateUrl: './other.component.html',
      styleUrls: ['./other.component.css']
    })

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

        ngOnInit() {
            this.href = this.router.url;
            console.log(this.router.url);
        }
    }

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

How to get document height and width without using jquery

How to find out the document width and height very easily?

in HTML
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>

in javascript

     var c=document.querySelector('#hidden_placer');

     var r=c.getBoundingClientRect();
     r.right=document width
     r.bottom=document height`

You may update this on every window resize event, if needed.

How to use store and use session variables across pages?

Starting a Session:

Put below code at the top of file.

<?php session_start();?>

Storing a session variable:

<?php $_SESSION['id']=10; ?>

To Check if data stored in session variable:

<?php if(isset($_SESSION['id']) && !empty(isset($_SESSION['id'])))
echo “Session id “.$_SESSION['id'].” exist”;
else
echo “Session not set “;?>

?> detail here http://skillrow.com/sessions-in-php-4/

How to split a single column values to multiple column values?

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
      FROM somenames
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

How to echo out the values of this array?

you need the set key and value in foreach loop for that:

foreach($item AS $key -> $value) {
echo $value;
}

this should do the trick :)

calling a function from class in python - different way

class MathsOperations:
    def __init__ (self, x, y):
        self.a = x
        self.b = y
    def testAddition (self):
        return (self.a + self.b)

    def testMultiplication (self):
        return (self.a * self.b)

then

temp = MathsOperations()
print(temp.testAddition())

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)