Programs & Examples On #Xmla

XML for Analysis is an industry standard for data access in analytical systems, such as OLAP and data mining.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

Add transaction-manager to your <annotation-driven/> in spring-servlet.xml:

<tx:annotation-driven transaction-manager="yourTransactionBeanID"/>

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

As Artem Bilan said, this problem occures because MappingJackson2HttpMessageConverter supports response with application/json content-type only. If you can't change server code, but can change client code(I had such case), you can change content-type header with interceptor:

restTemplate.getInterceptors().add((request, body, execution) -> {
            ClientHttpResponse response = execution.execute(request,body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return response;
        });

Make Https call using HttpClient

When connect to https I got this error too, I add this line before HttpClient httpClient = new HttpClient(); and connect successfully:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I know it from This Answer and Another Similar Anwser and the comment mentions:

This is a hack useful in development so putting a #if DEBUG #endif statement around it is the least you should do to make this safer and stop this ending up in production

Besides, I didn't try the method in Another Answer that use new X509Certificate() or new X509Certificate2() to make a Certificate, I'm not sure simply create by new() will work or not.

EDIT: Some References:

Create a Self-Signed Server Certificate in IIS 7

Import and Export SSL Certificates in IIS 7

Convert .pfx to .cer

Best practices for using ServerCertificateValidationCallback

I find value of Thumbprint is equal to x509certificate.GetCertHashString():

Retrieve the Thumbprint of a Certificate

"The import org.springframework cannot be resolved."

This answer from here helped me:

You should take a look at the build path of your project to check whether the referenced libraries are still there. So right-click on your project, then "Properties -> Java Build Path -> Libraries" and check whether you still have the spring library JARs in the place that is mentioned there. If not, just re-add them to your classpath within this dialog.

http://forum.spring.io/forum/spring-projects/springsource-tool-suite/98653-springframework-cannot-be-resolved-error

Spring Test & Security: How to mock authentication?

Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser

@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
    mockMvc.perform(get("/someApi"))
        .andExpect(status().isOk());
}

Remember to add the following dependency to your project

'org.springframework.security:spring-security-test:4.2.3.RELEASE'

File inside jar is not visible for spring

I had the same issue, ended up using the much more convenient Guava Resources:

Resources.getResource("my.file")

Cannot find the declaration of element 'beans'

Make sure if all the spring jar file's version in your build path and the version mentioned in the xml file are same.

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Just do it in the Base, that way any child can be Serialized, less code cleaner code.

public abstract class XmlBaseClass  
{
  public virtual string Serialize()
  {
    this.SerializeValidation();

    XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    XmlWriterSettings XmlSettings = new XmlWriterSettings
    {
      Indent = true,
      OmitXmlDeclaration = true
    };

    StringWriter StringWriter = new StringWriter();

    XmlSerializer Serializer = new XmlSerializer(this.GetType());
    XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
    Serializer.Serialize(XmlWriter, this, XmlNamespaces);
    StringWriter.Flush();
    StringWriter.Close();

    return StringWriter.ToString();

  }

  protected virtual void SerializeValidation() {}
}

[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
  protected override void SerializeValidation()
  {
    //Add custom validation logic here or anything else you need to do
  }
}

This way you can call Serialize on the child class no matter the circumstance and still be able to do what you need to before object Serializes.

Mockito, JUnit and Spring

Here's my short summary.

If you want to write a unit test, don't use a Spring applicationContext because you don't want any real dependencies injected in the class you are unit testing. Instead use mocks, either with the @RunWith(MockitoJUnitRunner.class) annotation on top of the class, or with MockitoAnnotations.initMocks(this) in the @Before method.

If you want to write an integration test, use:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("yourTestApplicationContext.xml")

To set up your application context with an in-memory database for example. Normally you don't use mocks in integration tests, but you could do it by using the MockitoAnnotations.initMocks(this) approach described above.

I can't understand why this JAXB IllegalAnnotationException is thrown

This is happening be cause you have 2 classes with same name. For, example, I have 2 SOAP web-services named settings and settings2 both have the same class GetEmployee and this is ambiguous proving the error.

Annotation @Transactional. How to rollback?

You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

and note that:

please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

JAXB :Need Namespace Prefix to all the elements

marshaller.setProperty only works on the JAX-B marshaller from Sun. The question was regarding the JAX-B marshaller from SpringSource, which does not support setProperty.

Jaxb, Class has two properties of the same name

I had a service class with signature as below"

@WebMethod
public FetchIQAStatusResponseVO fetchIQAStatus(FetchIQAStatusRequest fetchIQAStatusRequest) {

On run I got the same error for FetchIQAStatusResponseVO fields. I just added a line on top of FetchIQAStatusResponseVO:

@XmlAccessorType(XmlAccessType.FIELD) //This line added
public class FetchIQAStatusResponseVO {

and this resolved the issue.

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]

The error was with :

 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

AND RESOLVED WITH :

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

Whenever you will face below error just follow it.

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)

Put a @Transactional annotation for each method of implementing classes.

Spring - applicationContext.xml cannot be opened because it does not exist

I got the same issue while working on a maven project, so I recreate the configuration file spring.xml in src/main/java and it worked for me.

Using Spring 3 autowire in a standalone Java application

A nice solution would be to do following,

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {

private static ApplicationContext context;

/**
 * Returns the Spring managed bean instance of the given class type if it exists.
 * Returns null otherwise.
 * @param beanClass
 * @return
 */
public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {

    // store ApplicationContext reference to access required beans later on
    SpringContext.context = context;
}
}

Then you can use it like:

YourClass yourClass = SpringContext.getBean(YourClass.class);

I found this very nice solution in the following website: https://confluence.jaytaala.com/pages/viewpage.action?pageId=18579463

FileNotFoundException..Classpath resource not found in spring?

This is due to spring-config.xml is not in classpath.

Add complete path of spring-config.xml to your classpath.

Also write command you execute to run your project. You can check classpath in command.

XSD - how to allow elements in any order any number of times?

The alternative formulation of the question added in a later edit seems still to be unanswered: how to specify that among the children of an element, there must be one named child3, one named child4, and any number named child1 or child2, with no constraint on the order in which the children appear.

This is a straightforwardly definable regular language, and the content model you need is isomorphic to a regular expression defining the set of strings in which the digits '3' and '4' each occur exactly once, and the digits '1' and '2' occur any number of times. If it's not obvious how to write this, it may help to think about what kind of finite state machine you would build to recognize such a language. It would have at least four distinct states:

  • an initial state in which neither '3' nor '4' has been seen
  • an intermediate state in which '3' has been seen but not '4'
  • an intermediate state in which '4' has been seen but not '3'
  • a final state in which both '3' and '4' have been seen

No matter what state the automaton is in, '1' and '2' may be read; they do not change the machine's state. In the initial state, '3' or '4' will also be accepted; in the intermediate states, only '4' or '3' is accepted; in the final state, neither '3' nor '4' is accepted. The structure of the regular expression is easiest to understand if we first define a regex for the subset of our language in which only '3' and '4' occur:

(34)|(43)

To allow '1' or '2' to occur any number of times at a given location, we can insert (1|2)* (or [12]* if our regex language accepts that notation). Inserting this expression at all available locations, we get

(1|2)*((3(1|2)*4)|(4(1|2)*3))(1|2)*

Translating this into a content model is straightforward. The basic structure is equivalent to the regex (34)|(43):

<xsd:complexType name="paul0">
  <xsd:choice>
    <xsd:sequence>
      <xsd:element ref="child3"/>
      <xsd:element ref="child4"/>
    </xsd:sequence>
    <xsd:sequence>
      <xsd:element ref="child4"/>
      <xsd:element ref="child3"/>
    </xsd:sequence>
  </xsd:choice>
</xsd:complexType>

Inserting a zero-or-more choice of child1 and child2 is straightforward:

<xsd:complexType name="paul1">
  <xsd:sequence>
    <xsd:choice minOccurs="0" maxOccurs="unbounded">
      <xsd:element ref="child1"/>
      <xsd:element ref="child2"/>
    </xsd:choice>      
    <xsd:choice>
      <xsd:sequence>
        <xsd:element ref="child3"/>
        <xsd:choice minOccurs="0" maxOccurs="unbounded">
          <xsd:element ref="child1"/>
          <xsd:element ref="child2"/>
        </xsd:choice>      
        <xsd:element ref="child4"/>
      </xsd:sequence>
      <xsd:sequence>
        <xsd:element ref="child4"/>
        <xsd:choice minOccurs="0" maxOccurs="unbounded">
          <xsd:element ref="child1"/>
          <xsd:element ref="child2"/>
        </xsd:choice>      
        <xsd:element ref="child3"/>
      </xsd:sequence>
    </xsd:choice>
    <xsd:choice minOccurs="0" maxOccurs="unbounded">
      <xsd:element ref="child1"/>
      <xsd:element ref="child2"/>
    </xsd:choice>      
  </xsd:sequence>
</xsd:complexType>

If we want to minimize the bulk a bit, we can define a named group for the repeating choices of child1 and child2:

<xsd:group name="onetwo">
  <xsd:choice>
    <xsd:element ref="child1"/>
    <xsd:element ref="child2"/>
  </xsd:choice>   
</xsd:group>

<xsd:complexType name="paul2">
  <xsd:sequence>
    <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:choice>
      <xsd:sequence>
        <xsd:element ref="child3"/>
        <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element ref="child4"/>
      </xsd:sequence>
      <xsd:sequence>
        <xsd:element ref="child4"/>
        <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element ref="child3"/>
      </xsd:sequence>
    </xsd:choice>  
    <xsd:group ref="onetwo" minOccurs="0" maxOccurs="unbounded"/>
  </xsd:sequence>
</xsd:complexType>

In XSD 1.1, some of the constraints on all-groups have been lifted, so it's possible to define this content model more concisely:

<xsd:complexType name="paul3">
  <xsd:all>
    <xsd:element ref="child1" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element ref="child2" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element ref="child3"/>
    <xsd:element ref="child4"/>      
  </xsd:all>
</xsd:complexType>

But as can be seen from the examples given earlier, these changes to all-groups do not in fact change the expressive power of the language; they only make the definition of certain kinds of languages more succinct.

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

Eclipse - java.lang.ClassNotFoundException

I solve that Bulit path--->libraries--->add library--->Junit check junit4

How to Deserialize XML document

The following snippet should do the trick (and you can ignore most of the serialization attributes):

public class Car
{
  public string StockNumber { get; set; }
  public string Make { get; set; }
  public string Model { get; set; }
}

[XmlRootAttribute("Cars")]
public class CarCollection
{
  [XmlElement("Car")]
  public Car[] Cars { get; set; }
}

...

using (TextReader reader = new StreamReader(path))
{
  XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
  return (CarCollection) serializer.Deserialize(reader);
}

How to determine if a decimal/double is an integer?

If upper and lower bound of Int32 matters:

public bool IsInt32(double value)
{
    return  value >= int.MinValue && value <= int.MaxValue && value == (int)value;
}

Set time to 00:00:00

java.time

Using the java.time framework built into Java 8 and later. See Tutorial.

import java.time.LocalTime;
import java.time.LocalDateTime;

LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224
# start of a day
now.with(LocalTime.MIN); # 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00

If you do not need time-of-day (hour, minute, second etc. parts) consider using LocalDate class.

LocalDate.now(); # 2015-11-19

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

CSS Circular Cropping of Rectangle Image

The approach is wrong, you need to apply the border-radius to the container div instead of the actual image.

This would work:

_x000D_
_x000D_
.image-cropper {
  width: 100px;
  height: 100px;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
}

img {
  display: inline;
  margin: 0 auto;
  height: 100%;
  width: auto;
}
_x000D_
<div class="image-cropper">
  <img src="https://via.placeholder.com/150" class="rounded" />
</div>
_x000D_
_x000D_
_x000D_

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

How to store phone numbers on MySQL databases?

varchar, Don't store separating characters you may want to format the phone numbers differently for different uses. so store (619) 123-4567 as 6191234567 I work with phone directory data and have found this to be the best practice.

How to change the MySQL root account password on CentOS7?

What version of mySQL are you using? I''m using 5.7.10 and had the same problem with logging on as root

There is 2 issues - why can't I log in as root to start with, and why can I not use 'mysqld_safe` to start mySQL to reset the root password.

I have no answer to setting up the root password during installation, but here's what you do to reset the root password

Edit the initial root password on install can be found by running

grep 'temporary password' /var/log/mysqld.log

http://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html


  1. systemd is now used to look after mySQL instead of mysqld_safe (which is why you get the -bash: mysqld_safe: command not found error - it's not installed)

  2. The user table structure has changed.

So to reset the root password, you still start mySQL with --skip-grant-tables options and update the user table, but how you do it has changed.

1. Stop mysql:
systemctl stop mysqld

2. Set the mySQL environment option 
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

3. Start mysql usig the options you just set
systemctl start mysqld

4. Login as root
mysql -u root

5. Update the root user password with these mysql commands
mysql> UPDATE mysql.user SET authentication_string = PASSWORD('MyNewPassword')
    -> WHERE User = 'root' AND Host = 'localhost';
mysql> FLUSH PRIVILEGES;
mysql> quit

*** Edit ***
As mentioned my shokulei in the comments, for 5.7.6 and later, you should use 
   mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
Or you'll get a warning

6. Stop mysql
systemctl stop mysqld

7. Unset the mySQL envitroment option so it starts normally next time
systemctl unset-environment MYSQLD_OPTS

8. Start mysql normally:
systemctl start mysqld

Try to login using your new password:
7. mysql -u root -p

Reference

As it says at http://dev.mysql.com/doc/refman/5.7/en/mysqld-safe.html,

Note

As of MySQL 5.7.6, for MySQL installation using an RPM distribution, server startup and shutdown is managed by systemd on several Linux platforms. On these platforms, mysqld_safe is no longer installed because it is unnecessary. For more information, see Section 2.5.10, “Managing MySQL Server with systemd”.

Which takes you to http://dev.mysql.com/doc/refman/5.7/en/server-management-using-systemd.html where it mentions the systemctl set-environment MYSQLD_OPTS= towards the bottom of the page.

The password reset commands are at the bottom of http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

The pipe ' ' could not be found angular2 custom pipe

I found the "cross module" answer above very helpful to my situation, but would want to expand on that, as there is another wrinkle to consider. If you have a submodule, it also can't see the pipes in the parent module in my testing. For that reason also, you may need to put pipes into there own separate module.

Here's a summary of the steps I took to address pipes not being visible in the submodule:

  1. Take pipes out of (parent) SharedModule and put into PipeModule
  2. In SharedModule, import PipeModule and export (for other parts of app dependent on SharedModule to automatically gain access to PipeModule)
  3. For Sub-SharedModule, import PipeModule, so it can gain access to PipeModule, without having to re-import SharedModule which would create a circular dependency issue, among other problems.

Another footnote to the above "cross module" answer: when I created the PipeModule I removed the forRoot static method and imported PipeModule without that in my shared module. My basic understanding is that forRoot is useful for scenarios like singletons, which don't apply to filters necessarily.

Logging request/response messages when using HttpClient

The easiest solution would be to use Wireshark and trace the HTTP tcp flow.

What is the regex for "Any positive integer, excluding 0"

This should only allow decimals > 0

^([0-9]\.\d+)|([1-9]\d*\.?\d*)$

Setting action for back button in navigation controller

I've implemented UIViewController-BackButtonHandler extension. It does not need to subclass anything, just put it into your project and override navigationShouldPopOnBackButton method in UIViewController class:

-(BOOL) navigationShouldPopOnBackButton {
    if(needsShowConfirmation) {
        // Show confirmation alert
        // ...
        return NO; // Ignore 'Back' button this time
    }
    return YES; // Process 'Back' button click and Pop view controler
}

Download sample app.

Does C have a string type?

C does not have its own String data type like Java.

Only we can declare String datatype in C using character array or character pointer For example :

 char message[10]; 
 or 
 char *message;

But you need to declare at least:

    char message[14]; 

to copy "Hello, world!" into message variable.

  • 13 : length of the "Hello, world!"
  • 1 : for '\0' null character that identifies end of the string

How can I convert a string to boolean in JavaScript?

another solution. jsFiddle

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

test cases run in node

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

Add following to your maven dependency

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.5</version>
    </dependency>

    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

angular 2 sort and filter

This isn't added out of the box because the Angular team wants Angular 2 to run minified. OrderBy runs off of reflection which breaks with minification. Check out Miško Heverey's response on the matter.

I've taken the time to create an OrderBy pipe that supports both single and multi-dimensional arrays. It also supports being able to sort on multiple columns of the multi-dimensional array.

<li *ngFor="let person of people | orderBy : ['-lastName', 'age']">{{person.firstName}} {{person.lastName}}, {{person.age}}</li>

This pipe does allow for adding more items to the array after rendering the page, and still sort the arrays with the new items correctly.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

EDIT: Added new demo to http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby

EDIT 2: Updated ngFor to new syntax

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

FlutterError: Unable to load asset

  1. you should start image path with assets word:

image: AssetImage('assets/images/pizza0.png')

  1. you must add each sub folder in a new line in pubspec.yaml

How do I parse JSON with Objective-C?

NSString* path  = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];

//????????????,????NSUTF8StringEncoding ????,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

//??????????
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];


for (int i=0; i<[allKeys count]; i++) {
    NSDictionary *arrayResult = [allKeys objectAtIndex:i];
    NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);

}

file:

 [
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "MLMember",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  },
  {
  "ID":1,
  "idSort" : 0,
  "deleted":0,
  "storyboardName" : "0.00",
  "dispalyTitle" : "76.360779",
  "rightLevel" : "10.010490",
  "showTabBar" : 1,
  "openWeb" : 0,
  "webUrl":""
  }
  ]

Understanding repr( ) function in Python

>>> x = 'foo'
>>> x
'foo'

So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

When we call eval("'foo'"), it's the same as we type 'foo' in the interpreter. It's as we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

If we call eval('foo'), it's the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

>>> str(5)
'5'

String representation of integer 5 is '5'.

>>> str('foo')
'foo'

And string representation of string 'foo' is the same string 'foo'.

How to get the Facebook user id using the access token

in FacebookSDK v2.1 (I can't check older version). We have

NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;

However according to the comment in FacebookSDK

@discussion This may not be populated for login behaviours such as the iOS system account.

So may be you should check if it is available, and then whether use it, or call the request to get the user id

How to echo (or print) to the js console with php

<?php  echo "<script>console.log({$yourVariable})</script>"; ?>

round a single column in pandas

You are very close. You applied the round to the series of values given by df.value1. The return type is thus a Series. You need to assign that series back to the dataframe (or another dataframe with the same Index).

Also, there is a pandas.Series.round method which is basically a short hand for pandas.Series.apply(np.round).

In[2]: 
    df.value1 = df.value1.round()
    print df

Out[2]:
    item  value1  value2
    0    a       1     1.3
    1    a       2     2.5
    2    a       0     0.0
    3    b       3    -1.0
    4    b       5    -1.0

JComboBox Selection Change Listener?

I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.

How do I get the previous or last item?

Rounding up to next power of 2

A variant of @YannDroneaud answer valid for x==1, only for x86 plateforms, compilers, gcc or clang:

__attribute__ ((const))
static inline uint32_t p2(uint32_t x)
{
#if 0
    assert(x > 0);
    assert(x <= ((UINT32_MAX/2) + 1));
#endif
  int clz;
  uint32_t xm1 = x-1;
  asm(
    "lzcnt %1,%0"
    :"=r" (clz)
    :"rm" (xm1)
    :"cc"
    );
    return 1 << (32 - clz);
}

How to remove decimal values from a value of type 'double' in Java

With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.

String newValue = ((int) percentageValue).toString();

How to set width of mat-table column in angular?

Just add style="width:5% !important;" to th and td

  <ng-container matColumnDef="username">
    <th style="width:5% !important;" mat-header-cell *matHeaderCellDef> Full Name </th>
    <td style="width:5% !important;" mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td>
  </ng-container>

Converting 'ArrayList<String> to 'String[]' in Java

We have following three ways for converting arraylist to array

  1. public T[] toArray(T[] a) - In this way we will create a array with size of list then put in method as String[] arr = new String[list.size()];

    arr = list.toArray(arr);

  2. Public get() method - In this way we iterate list and put element in array one by one

Reference : How to convert ArrayList To Array In Java

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

How add spaces between Slick carousel item

The slick-slide has inner wrapping div which you can use to create spacing between slides without breaking the design:

.slick-list {margin: 0 -5px;}
.slick-slide>div {padding: 0 5px;}

Remove an item from array using UnderscoreJS

Other answers create a new copy of the array, if you want to modify the array in place you can use:

arr.splice(_.findIndex(arr, { id: 3 }), 1);

But that assumes that the element will always be found inside the array (because if is not found it will still remove the last element). To be safe you can use:

var index = _.findIndex(arr, { id: 3 });
if (index > -1) {
    arr.splice(index, 1);
}

What is correct media query for IPad Pro?

Note that there are multiple iPad Pros, each with a different Viewports: When emulating an iPad Pro via the Chrome developer tools, the iPad Pro (12.9") is the default option. If you want to emulate one of the other iPad Pros (10.5" or 9.7") with a different viewport, you'll need to add a custom emulated device with the correct specs.

You can search devices, viewports, and their respective CSS media queries at: http://vizdevices.yesviz.com/devices.php.

For instance, the iPad Pro (12.9") would have the following media queries:

/* Landscape */ 
@media only screen and (min-width: 1366px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-width: 1024px) and (orientation: portrait) { /* Your Styles... */ }

Whereas the iPad Pro (10.5") will have:

/* Landscape */ 
@media only screen and (min-device-width: 1112px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-device-width: 834px) and (orientation: portrait) { /* Your Styles... */ }

Can anyone explain IEnumerable and IEnumerator to me?

A Minor contribution.

As many of them explain about 'when to use' and 'use with foreach'. I thought of adding Another States Difference here as requested in question about the difference between both IEnumerable an IEnumerator.

I created the below code sample based on the below discussion threads.

IEnumerable , IEnumerator vs foreach, when to use what What is the difference between IEnumerator and IEnumerable?

Enumerator preserves the state (iteration position) between function calls while iterations the other hand Enumerable does not.

Here is the tested example with comments to understand.

Experts please add/correct me.

static void EnumerableVsEnumeratorStateTest()
{
    IList<int> numList = new List<int>();

    numList.Add(1);
    numList.Add(2);
    numList.Add(3);
    numList.Add(4);
    numList.Add(5);
    numList.Add(6);

    Console.WriteLine("Using Enumerator - Remembers the state");
    IterateFrom1to3(numList.GetEnumerator());

    Console.WriteLine("Using Enumerable - Does not Remembers the state");
    IterateFrom1to3Eb(numList);

    Console.WriteLine("Using Enumerable - 2nd functions start from the item 1 in the collection");
}

static void IterateFrom1to3(IEnumerator<int> numColl)
{
    while (numColl.MoveNext())
    {
        Console.WriteLine(numColl.Current.ToString());

        if (numColl.Current > 3)
        {
            // This method called 3 times for 3 items (4,5,6) in the collection. 
            // It remembers the state and displays the continued values.
            IterateFrom3to6(numColl);
        }
    }
}

static void IterateFrom3to6(IEnumerator<int> numColl)
{
    while (numColl.MoveNext())
    {
        Console.WriteLine(numColl.Current.ToString());
    }
}

static void IterateFrom1to3Eb(IEnumerable<int> numColl)
{
    foreach (int num in numColl)
    {
        Console.WriteLine(num.ToString());

        if (num>= 5)
        {
            // The below method invokes for the last 2 items.
            //Since it doesnot persists the state it will displays entire collection 2 times.
            IterateFrom3to6Eb(numColl);
        }
    }
}

static void IterateFrom3to6Eb(IEnumerable<int> numColl)
{
    Console.WriteLine();
    foreach (int num in numColl)
    {
        Console.WriteLine(num.ToString());
    }
}

Android - How to achieve setOnClickListener in Kotlin?

First find the button, to prevent the cast from the View you can use the <> as follows :

val button = findViewById<Button>(R.id.button);

Once you have an instance of the Button, you can now attach the click listener as follows :

button.setOnClickListener {  
 // You code here
}

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

How to add custom html attributes in JSX

Depending on what version of React you are using, you may need to use something like this. I know Facebook is thinking about deprecating string refs in the somewhat near future.

var Hello = React.createClass({
    componentDidMount: function() {
        ReactDOM.findDOMNode(this.test).setAttribute('custom-attribute', 'some value');
    },
    render: function() {
        return <div>
            <span ref={(ref) => this.test = ref}>Element with a custom attribute</span>
        </div>;
    }
});

React.render(<Hello />, document.getElementById('container'));

Facebook's ref documentation

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

use your jsonsimpleobject direclty like below

JSONObject unitsObj = parser.parse(new FileReader("file.json");

How can I check if a program exists from a Bash script?

To use hash, as @lhunath suggests, in a Bash script:

hash foo &> /dev/null
if [ $? -eq 1 ]; then
    echo >&2 "foo not found."
fi

This script runs hash and then checks if the exit code of the most recent command, the value stored in $?, is equal to 1. If hash doesn't find foo, the exit code will be 1. If foo is present, the exit code will be 0.

&> /dev/null redirects standard error and standard output from hash so that it doesn't appear onscreen and echo >&2 writes the message to standard error.

Scroll to bottom of div?

You can try the code below:

function scrollToBottom (id) {
   var div = document.getElementById(id);
   div.scrollTop = div.scrollHeight - div.clientHeight;
}

To perform a smooth scroll with JQuery:

function scrollSmoothToBottom (id) {
   var div = document.getElementById(id);
   $('#' + id).animate({
      scrollTop: div.scrollHeight - div.clientHeight
   }, 500);
}

See the example on JSFiddle

Here's why this works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

Greyscale Background Css Images

Using current browsers you can use it like this:

img {
  -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
  filter: grayscale(100%);
}

and to remedy it:

img:hover{
   -webkit-filter: grayscale(0%); /* Chrome, Safari, Opera */
   filter: grayscale(0%);
}

worked with me and is much shorter. There is even more one can do within the CSS:

filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() |
        hue-rotate() | invert() | opacity() | saturate() | sepia() | url();

For more information and supporting browsers see this: http://www.w3schools.com/cssref/css3_pr_filter.asp

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

Reduce git repository size

In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.

What did the trick was:

bfg -b 100M  # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive

Then, you need to push force on your branch:

git push origin <your_branch_name> --force

Note: bfg is a tool that can be installed on Linux and macOS using brew:

brew install bfg

How do I execute a file in Cygwin?

gcc under cygwin does not generate a Linux executable output file of type " ELF 32-bit LSB executable," but it generates a windows executable of type "PE32 executable for MS Windows" which has a dependency on cygwin1.dll, so it needs to be run under cygwin shell. If u need to run it under dos prompt independently, they cygwin1.dll needs to be in your Windows PATH.

-AD.

Location of WSDL.exe

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools

MySQL equivalent of DECODE function in Oracle

The example translates directly to:

Select Name, CASE Age
       WHEN 13 then 'Thirteen' WHEN 14 then 'Fourteen' WHEN 15 then 'Fifteen' WHEN 16 then 'Sixteen'
       WHEN 17 then 'Seventeen' WHEN 18 then 'Eighteen' WHEN 19 then 'Nineteen'
       ELSE 'Adult' END AS AgeBracket
FROM Person

which you may prefer to format e.g. like this:

Select Name,
       CASE Age
         when 13 then 'Thirteen'
         when 14 then 'Fourteen'
         when 15 then 'Fifteen'
         when 16 then 'Sixteen'
         when 17 then 'Seventeen'
         when 18 then 'Eighteen'
         when 19 then 'Nineteen'
         else         'Adult'
       END AS AgeBracket
FROM Person

How does lock work exactly?

According to Microsoft's MSDN, the lock is equivalent to:

object __lockObj = x;
bool __lockWasTaken = false;
try
{
    System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
    // Your code...
}
finally
{
    if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
}

If you need to create locks in runtime, you can use open source DynaLock. You can create new locks in run-time and specify boundaries to the locks with context concept.

DynaLock is open-source and source code is available at GitHub

How to create EditText with rounded corners?

With the Material Components Library you can use the MaterialShapeDrawable to draw custom shapes.

With a EditText you can do:

    <EditText
        android:id="@+id/edittext"
        ../>

Then create a MaterialShapeDrawable:

float radius = getResources().getDimension(R.dimen.default_corner_radius);

EditText editText = findViewById(R.id.edittext);
//Apply the rounded corners 
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
                .toBuilder()
                .setAllCorners(CornerFamily.ROUNDED,radius)
                .build();

MaterialShapeDrawable shapeDrawable = 
            new MaterialShapeDrawable(shapeAppearanceModel);
//Apply a background color
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.white));
//Apply a stroke
shapeDrawable.setStroke(2.0f, ContextCompat.getColor(this,R.color.colorAccent));

ViewCompat.setBackground(editText,shapeDrawable);

enter image description here

It requires the version 1.1.0 of the library.

MySQL: How to add one day to datetime field in query

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");

Or, simplier:

date("Y-m-d H:i:s", time()+((60*60)*24));

How to load external webpage in WebView

Add below method in your activity class.Here browser is nothing but your webview object.

Now you can view web contain page wise easily.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
        browser.goBack();
        return true;
    }
    return false;
}

Learning Ruby on Rails

Ruby: I used Learn to program (in a weekend), Ruby Visual QuickStart (believe it or not this QS book was "off the hook" excellent). This took about a week.

Rails: I just went through Learn Rails in one "aggressive" week. Definitely feel I have the nuts and bolts. It's 2009 which I deemed important!

Now I plan to combine a more advanced book with a real project.

IDE: VIM with rails plugin is great if you're a vim addict. Otherwise, try any suggested above.

Of course railscast, etc., are useful for most up to date stuff.

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

What's the difference between .NET Core, .NET Framework, and Xamarin?

  1. .NET is the Ecosystem based on c# language
  2. .NET Standard is Standard (in other words, specification) of .NET Ecosystem .

.Net Core Class Library is built upon the .Net Standard. .NET Standard you can make only class-library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.If you want to implement a library that is portable to the .Net Framework, .Net Core and Xamarin, choose a .Net Standard Library

  1. .NET Framework is a framework based on .NET and it supports Windows and Web applications

(You can make executable project (like Console application, or ASP.NET application) with .NET Framework

  1. ASP.NET is a web application development technology which is built over the .NET Framework
  2. .NET Core also a framework based on .NET.

It is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux.

  1. Xamarin is a framework to develop a cross platform mobile application(iOS, Android, and Windows Mobile) using C#

Implementation support of .NET Standard[blue] and minimum viable platform for full support of .NET Standard (latest: [https://docs.microsoft.com/en-us/dotnet/standard/net-standard#net-implementation-support])

Python/Json:Expecting property name enclosed in double quotes

As it clearly says in error, names should be enclosed in double quotes instead of single quotes. The string you pass is just not a valid JSON. It should look like

{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}

How to get an object's methods?

var methods = [];
for (var key in foo.prototype) {
    if (typeof foo.prototype[key] === "function") {
         methods.push(key);
    }
}

You can simply loop over the prototype of a constructor and extract all methods.

remove space between paragraph and unordered list

I got pretty good results with my HTML mailing list by using the following:

p { margin-bottom: 0; }
ul { margin-top: 0; }

This does not reset all margin values but only those that create such a gap before ordered list, and still doesn't assume anything about default margin values.

Trying to embed newline in a variable in bash

var="a b c"
for i in $var
do
   p=`echo -e "$p"'\n'$i`
done
echo "$p"

The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.

Meaning of "referencing" and "dereferencing" in C

find the below explanation:

int main()
{
    int a = 10;// say address of 'a' is 2000;
    int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
    int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10. 
}

conclusion :

  1. & [address operator] is used for referencing.
  2. * [star operator] is used for de-referencing .

SQL Server - INNER JOIN WITH DISTINCT

select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

hope this helps

Facebook Graph API : get larger pictures in one request

Change the array of fields id,name,picture to id,name,picture.type(large)

https://graph.facebook.com/v2.8/me?fields=id,name,picture.type(large)&access_token=<the_token>

Result:

{
   "id": "130716224073524",
   "name": "Julian Mann",
   "picture": {
      "data": {
         "is_silhouette": false,
         "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15032818_133926070419206_3681208703790460208_n.jpg?oh=a288898d87420cdc7ed8db5602bbb520&oe=58CB5D16"
      }
   }
}

What does Ruby have that Python doesn't, and vice versa?

"Variables that start with a capital letter becomes constants and can't be modified"

Wrong. They can.

You only get a warning if you do.

Clear android application user data

To clear Application Data Please Try this way.

    public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null &amp;&amp; dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

How do I get the directory that a program is running from?

If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.

If you agree that some (portable) dependency on a near-standard lib is okay: Use Boost's filesystem library and ask for the initial_path().

IMHO that's as close as you can get, with good karma (Boost is a well-established high quality set of libraries)

Java Hashmap: How to get key from value?

My 2 cents. You can get the keys in an array and then loop through the array. This will affect performance of this code block if the map is pretty big , where in you are getting the keys in an array first which might consume some time and then you are looping. Otherwise for smaller maps it should be ok.

String[] keys =  yourMap.keySet().toArray(new String[0]);

for(int i = 0 ; i < keys.length ; i++){
    //This is your key    
    String key = keys[i];

    //This is your value
    yourMap.get(key)            
}

How to replace spaces in file names using a bash script

I use:

for f in *\ *; do mv "$f" "${f// /_}"; done

Though it's not recursive, it's quite fast and simple. I'm sure someone here could update it to be recursive.

The ${f// /_} part utilizes bash's parameter expansion mechanism to replace a pattern within a parameter with supplied string. The relevant syntax is ${parameter/pattern/string}. See: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html or http://wiki.bash-hackers.org/syntax/pe .

What do multiple arrow functions mean in javascript?

That is a curried function

First, examine this function with two parameters …

const add = (x, y) => x + y
add(2, 3) //=> 5

Here it is again in curried form …

const add = x => y => x + y

Here is the same1 code without arrow functions …

const add = function (x) {
  return function (y) {
    return x + y
  }
}

Focus on return

It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.

const f = someParam => returnValue

So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add

const add = x => (y => x + y)

In other words add of some number returns a function

add(2) // returns (y => 2 + y)

Calling curried functions

So in order to use our curried function, we have to call it a bit differently …

add(2)(3)  // returns 5

This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …

const add2 = add(2) // returns function(y) { return 2 + y }
add2(3)             // returns 5

Applying our new understanding to your code

related: ”What’s the difference between binding, partial application, and currying?”

OK, now that we understand how that works, let's look at your code

handleChange = field => e => {
  e.preventDefault()
  /// Do something here
}

We'll start by representing it without using arrow functions …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  };
};

However, because arrow functions lexically bind this, it would actually look more like this …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  }.bind(this)
}.bind(this)

Maybe now we can see what this is doing more clearly. The handleChange function is creating a function for a specified field. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange function, we can eliminate all the duplicated code that would result in setting up change listeners for each field. Cool!

1 Here I did not have to lexically bind this because the original add function does not use any context, so it is not important to preserve it in this case.


Even more arrows

More than two arrow functions can be sequenced, if necessary -

const three = a => b => c =>
  a + b + c

const four = a => b => c => d =>
  a + b + c + d

three (1) (2) (3) // 6

four (1) (2) (3) (4) // 10

Curried functions are capable of surprising things. Below we see $ defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -

_x000D_
_x000D_
const $ = x => k =>_x000D_
  $ (k (x))_x000D_
  _x000D_
const add = x => y =>_x000D_
  x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
  x * y_x000D_
  _x000D_
$ (1)           // 1_x000D_
  (add (2))     // + 2 = 3_x000D_
  (mult (6))    // * 6 = 18_x000D_
  (console.log) // 18_x000D_
  _x000D_
$ (7)            // 7_x000D_
  (add (1))      // + 1 = 8_x000D_
  (mult (8))     // * 8 = 64_x000D_
  (mult (2))     // * 2 = 128_x000D_
  (mult (2))     // * 2 = 256_x000D_
  (console.log)  // 256
_x000D_
_x000D_
_x000D_

Partial application

Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -

const partial = (f, ...a) => (...b) =>
  f (...a, ...b)

const add3 = (x, y, z) =>
  x + y + z

partial (add3) (1, 2, 3)   // 6

partial (add3, 1) (2, 3)   // 6

partial (add3, 1, 2) (3)   // 6

partial (add3, 1, 2, 3) () // 6

partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3

Here's a working demo of partial you can play with in your own browser -

_x000D_
_x000D_
const partial = (f, ...a) => (...b) =>_x000D_
  f (...a, ...b)_x000D_
  _x000D_
const preventDefault = (f, event) =>_x000D_
  ( event .preventDefault ()_x000D_
  , f (event)_x000D_
  )_x000D_
  _x000D_
const logKeypress = event =>_x000D_
  console .log (event.which)_x000D_
  _x000D_
document_x000D_
  .querySelector ('input[name=foo]')_x000D_
  .addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
_x000D_
_x000D_

How can I set a cookie in react?

A very simple solution is using the sfcookies package. You just have to install it using npm for example: npm install sfcookies --save

Then you import on the file:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

create a cookie key:

const cookie_key = 'namedOFCookie';

on your submit function, you create the cookie by saving data on it just like this:

bake_cookie(cookie_key, 'test');

to delete it just do

delete_cookie(cookie_key);

and to read it:

read_cookie(cookie_key)

Simple and easy to use.

Commenting code in Notepad++

Try the following shortcut:

Ctrl+K.

How can I enter latitude and longitude in Google Maps?

It's actually fairly easy, just enter it as a latitude,longitude pair, ie 46.38S,115.36E (which is in the middle of the ocean). You'll want to convert it to decimal though (divide the minutes portion by 60 and add it to the degrees [I've done that with your example]).

Mongoose limit/offset and count query

After having to tackle this issue myself, I would like to build upon user854301's answer.

Mongoose ^4.13.8 I was able to use a function called toConstructor() which allowed me to avoid building the query multiple times when filters are applied. I know this function is available in older versions too but you'll have to check the Mongoose docs to confirm this.

The following uses Bluebird promises:

let schema = Query.find({ name: 'bloggs', age: { $gt: 30 } });

// save the query as a 'template'
let query = schema.toConstructor();

return Promise.join(
    schema.count().exec(),
    query().limit(limit).skip(skip).exec(),

    function (total, data) {
        return { data: data, total: total }
    }
);

Now the count query will return the total records it matched and the data returned will be a subset of the total records.

Please note the () around query() which constructs the query.

Validate select box

Perhaps there is a shorter way but this works for me.

<script language='JavaScript' type='text/javascript'>
    function validateThisFrom(thisForm) {
        if (thisForm.FIELDNAME.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME.focus();
            return false;
        }
        if (thisForm.FIELDNAME2.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME2.focus();
            return false;
        }
    }
</script>
<form onSubmit="return validateThisFrom (this);">
    <select name="FIELDNAME" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
    <select name="FIELDNAME2" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
</form>

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

Example to get the last input element:

document.querySelector(".groups-container >div:last-child input")

Using jQuery To Get Size of Viewport

To get the width and height of the viewport:

var viewportWidth = $(window).width();
var viewportHeight = $(window).height();

resize event of the page:

$(window).resize(function() {

});

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Checking for an empty field with MySQL

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";

$res = mysql_query($sql);

while ($row = mysql_fetch_assoc($res)) {

    foreach($row as $key => $field) {  

        echo "<br>";

        if(empty($row[$key])){

            echo $key." : empty field :"."<br>"; 

        }else{

        echo $key." =" . $field."<br>";     

        }
    }
}

Check if $_POST exists

I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

if(sizeof($_POST) !== 0){
// Code...
}

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values. $_POST['value'] may not exist, thus throwing an "undefined index" error.

How does Trello access the user's clipboard?

I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.

I find three bugs with Trello's approach, which I know because I've faced them myself :)

The copy doesn't work in these scenarios:

  1. If you already have Ctrl pressed and then hover a link and hit C, the copy doesn't work.
  2. If your cursor is in some other text field in the page, the copy doesn't work.
  3. If your cursor is in the address bar, the copy doesn't work.

I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.

I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.

I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).

Adding event listeners to dynamically added elements using jQuery

When adding new element with jquery plugin calls, you can do like the following:

$('<div>...</div>').hoverCard(function(){...}).appendTo(...)

Height equal to dynamic width (CSS fluid layout)

Extremely simple method jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}

Using OR operator in a jquery if statement

Think about what

if ((state != 10) || (state != 15) || (state != 19) || (state != 22) || (state != 33) || (state != 39) || (state != 47) || (state != 48) || (state != 49) || (state != 51))

means. || means "or." The negation of this is (by DeMorgan's Laws):

state == 10 && state == 15 && state == 19...

In other words, the only way that this could be false if if a state equals 10, 15, and 19 (and the rest of the numbers in your or statement) at the same time, which is impossible.

Thus, this statement will always be true. State 15 will never equal state 10, for example, so it's always true that state will either not equal 10 or not equal 15.

Change || to &&.

Also, in most languages, the following:

if (x) {
  return true;
}
else {
  return false;
}

is not necessary. In this case, the method returns true exactly when x is true and false exactly when x is false. You can just do:

return x;

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

Creating random numbers with no duplicates

//random numbers are 0,1,2,3 
ArrayList<Integer> numbers = new ArrayList<Integer>();   
Random randomGenerator = new Random();
while (numbers.size() < 4) {

    int random = randomGenerator .nextInt(4);
    if (!numbers.contains(random)) {
        numbers.add(random);
    }
}

How do you determine what SQL Tables have an identity column programmatically

This worked for SQL Server 2005, 2008, and 2012. I found that the sys.identity_columns did not contain all my tables with identity columns.

SELECT a.name AS TableName, b.name AS IdentityColumn
FROM sys.sysobjects a 
JOIN sys.syscolumns b 
ON a.id = b.id
WHERE is_identity = 1
ORDER BY name;

Looking at the documentation page the status column can also be utilized. Also you can add the four part identifier and it will work across different servers.

SELECT a.name AS TableName, b.name AS IdentityColumn
FROM [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.sysobjects a 
JOIN [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.syscolumns b 
ON a.id = b.id
WHERE is_identity = 1
ORDER BY name;

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

C++ Matrix Class

For a matrix class, you want to stay away from overloading the [] operator.
See C++ FAQ 13.10

Also, search the web for some freeware Matrix classes. Worst case, they can give you guidance. Best case, less software that you have to write and debug.

push multiple elements to array

You can use Array.concat:

var result = a.concat(b);

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

Twitter Bootstrap button click to toggle expand/collapse text section above button

Based on the doc

<div class="row">
    <div class="span4 collapse-group">
        <h2>Heading</h2>
        <p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>
$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('.collapse');
    $collapse.collapse('toggle');
});

Working demo.

How to get rid of blank pages in PDF exported from SSRS

It is better to do this on the design surface (Visual Studio 2012 is shown but can be done in other versions) first before calculating any maths when editing an SSRS document.

Below the following numbers in red circles that map to these following steps:

  1. In the design surface, sometimes the editor will create a page which is larger than the actual controls; hence the ghost area being printed.
  2. Resize to the controls. Visually look at the width/height and see if you can't bring in the page on the design surface to size it to the space actually needed by the controls and no more.
  3. Then try to create a PDF and see if that fixes it.
  4. If #3 does not resolve the issue, then there are controls requiring too much of the actual page size and going over in either length/width. So one will need to make the size of the controls smaller to accommodate a smaller page size.

Steps to manually remediate


Also in some circumstances one can just change a property of the report page by setting ConsumeContainerWhitespace to true to automatically consume the spaces.

setting y-axis limit in matplotlib

Your code works also for me. However, another workaround can be to get the plot's axis and then change only the y-values:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))

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

In addition to previous answers, if your menu items are Categories and you want to highlight them when navigating through posts, check also for current-post-ancestor:

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

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

How do I change the root directory of an Apache server?

Applies to Ubuntu 14.04 and later releases. Make sure to backup following files before making any changes.

1.Open /etc/apache2/apache2.conf and search for <Directory /var/www/> directive and replace path with /home/<USERNAME>/public_html. You can use * instead of .

2.Open /etc/apache2/sites-available/000-default.conf and replace DocumentRoot value property from /var/www/html to /home/<USERNAME>/public_html. Also <Directory /var/www/html> to <Directory /home/<USERNAME>/public_html.

3.Open /etc/mods-available/php7.1.conf. Find and comment following code

<IfModule mod_userdir.c>
    <Directory /home/*/public_html>
        php_admin_flag engine Off
    </Directory>
</IfModule>

Do not turn ON php_admin_flag engine OFF flag as reason is mentioned in comment above Directive code. Also php version can be 5.0, 7.0 or anything which you have installed.

Create public_html directory in home/<USERNAME>.

Restart apache service by executing command sudo service apache2 restart.

Test by running sample script on server.

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

How to convert View Model into JSON object in ASP.NET MVC?

Andrew had a great response but I wanted to tweek it a little. The way this is different is that I like my ModelViews to not have overhead data in them. Just the data for the object. It seem that ViewData fits the bill for over head data, but of course I'm new at this. I suggest doing something like this.

Controller

virtual public ActionResult DisplaySomeWidget(int id)
{
    SomeModelView returnData = someDataMapper.getbyid(1);
    var serializer = new JavaScriptSerializer();
    ViewData["JSON"] = serializer.Serialize(returnData);
    return View(myview, returnData);
}

View

//create base js object;
var myWidget= new Widget(); //Widget is a class with a public member variable called data.
myWidget.data= <%= ViewData["JSON"] %>;

What This does for you is it gives you the same data in your JSON as in your ModelView so you can potentially return the JSON back to your controller and it would have all the parts. This is similar to just requesting it via a JSONRequest however it requires one less call so it saves you that overhead. BTW this is funky for Dates but that seems like another thread.

Cannot get a text value from a numeric cell “Poi”

As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING) to get the string value of a numeric cell, as you'll loose all the formatting

Instead, as the javadocs explain, you should use DataFormatter

What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.

So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:

 // Create a formatter, do this once
 DataFormatter formatter = new DataFormatter(Locale.US);

 .....

 for (int i=1; i <= sheet.getLastRowNum(); i++) {
        Row r = sheet.getRow(i);
        if (r == null) { 
           // empty row, skip
        } else {
           String j_username = formatter.formatCellValue(row.getCell(0));
           String j_password =  formatter.formatCellValue(row.getCell(1));

           // Use these
        }
 }

The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell

Rotating videos with FFmpeg

This script that will output the files with the directory structure under "fixedFiles". At the moment is fixed to MOV files and will execute a number of transformations depending on the original "rotation" of the video. Works with iOS captured videos on a Mac running Mavericks, but should be easily exportable. Relies on having installed both exiftool and ffmpeg.

#!/bin/bash

# rotation of 90 degrees. Will have to concatenate.
#ffmpeg -i <originalfile> -metadata:s:v:0 rotate=0 -vf "transpose=1" <destinationfile>
#/VLC -I dummy -vvv <originalfile> --sout='#transcode{width=1280,vcodec=mp4v,vb=16384,vfilter={canvas{width=1280,height=1280}:rotate{angle=-90}}}:std{access=file,mux=mp4,dst=<outputfile>}\' vlc://quit

#Allowing blanks in file names
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

#Bit Rate
BR=16384

#where to store fixed files
FIXED_FILES_DIR="fixedFiles"
#rm -rf $FIXED_FILES_DIR
mkdir $FIXED_FILES_DIR

# VLC
VLC_START="/Applications/VLC.app/Contents/MacOS/VLC -I dummy -vvv"
VLC_END="vlc://quit"


#############################################
# Processing of MOV in the wrong orientation
for f in `find . -regex '\./.*\.MOV'` 
do
  ROTATION=`exiftool "$f" |grep Rotation|cut -c 35-38`
  SHORT_DIMENSION=`exiftool "$f" |grep "Image Size"|cut -c 39-43|sed 's/x//'`
  BITRATE_INT=`exiftool "$f" |grep "Avg Bitrate"|cut -c 35-38|sed 's/\..*//'`
  echo Short dimension [$SHORT_DIMENSION] $BITRATE_INT

  if test "$ROTATION" != ""; then
    DEST=$(dirname ${f})
    echo "Processing $f with rotation $ROTATION in directory $DEST"
    mkdir -p $FIXED_FILES_DIR/"$DEST"

    if test "$ROTATION" == "0"; then
      cp "$f" "$FIXED_FILES_DIR/$f"

    elif test "$ROTATION" == "180"; then
#      $(eval $VLC_START \"$f\" "--sout="\'"#transcode{vfilter={rotate{angle=-"$ROTATION"}},vcodec=mp4v,vb=$BR}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
      $(eval ffmpeg -i \"$f\" -vf hflip,vflip -r 30 -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\")

    elif test "$ROTATION" == "270"; then
      $(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=2,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )

    else
#      $(eval $VLC_START \"$f\" "--sout="\'"#transcode{scale=1,width=$SHORT_DIMENSION,vcodec=mp4v,vb=$BR,vfilter={canvas{width=$SHORT_DIMENSION,height=$SHORT_DIMENSION}:rotate{angle=-"$ROTATION"}}}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
      echo ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" 
      $(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )

    fi

  fi

echo 
echo ==================================================================
sleep 1
done

#############################################
# Processing of AVI files for my Panasonic TV
# Use ffmpegX + QuickBatch. Bitrate at 16384. Camera res 640x424
for f in `find . -regex '\./.*\.AVI'` 
do
  DEST=$(dirname ${f})
  DEST_FILE=`echo "$f" | sed 's/.AVI/.MOV/'`
  mkdir -p $FIXED_FILES_DIR/"$DEST"
  echo "Processing $f in directory $DEST"
  $(eval ffmpeg -i \"$f\" -r 20 -acodec libvo_aacenc -b:a 128k -vcodec mpeg4 -b:v 8M -flags +aic+mv4 \"$FIXED_FILES_DIR/$DEST_FILE\" )
echo 
echo ==================================================================

done

IFS=$SAVEIFS

What is the difference between Cygwin and MinGW?

Wikipedia Says:

MinGW forked from version 1.3.3 of Cygwin. Although both Cygwin and MinGW can be used to port UNIX software to Windows, they have different approaches: Cygwin aims to provide a complete POSIX layer that provides emulations of several system calls and libraries that exist on Linux, UNIX, and the BSD variants. The POSIX layer runs on top of Windows, sacrificing performance where necessary for compatibility. Accordingly, this approach requires Windows programs written with Cygwin to run on top of a copylefted compatibility library that must be distributed with the program, along with the program's source code. MinGW aims to provide native functionality and performance via direct Windows API calls. Unlike Cygwin, MinGW does not require a compatibility layer DLL and thus programs do not need to be distributed with source code.

Because MinGW is dependent upon Windows API calls, it cannot provide a full POSIX API; it is unable to compile some UNIX applications that can be compiled with Cygwin. Specifically, this applies to applications that require POSIX functionality like fork(), mmap() or ioctl() and those that expect to be run in a POSIX environment. Applications written using a cross-platform library that has itself been ported to MinGW, such as SDL, wxWidgets, Qt, or GTK+, will usually compile as easily in MinGW as they would in Cygwin.

The combination of MinGW and MSYS provides a small, self-contained environment that can be loaded onto removable media without leaving entries in the registry or files on the computer. Cygwin Portable provides a similar feature. By providing more functionality, Cygwin becomes more complicated to install and maintain.

It is also possible to cross-compile Windows applications with MinGW-GCC under POSIX systems. This means that developers do not need a Windows installation with MSYS to compile software that will run on Windows without Cygwin.

PHP mysql insert date format

HTML:

<div class="form-group">
  <label for="pt_date" class="col-2 col-form-label">Date</label>
  <input class="form-control" type="date" value=<?php echo  date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>

SQL

$pt_date = $_POST['pt_date'];

$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";

How do I hide an element on a click event anywhere outside of the element?

If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.

How to draw a line with matplotlib?

This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)

x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.

x2 and y2 are the same for the other line.

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

enter image description here

I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.

What if I don't want line segments?

There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.

As follows:

import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()

enter image description here

javac error: Class names are only accepted if annotation processing is explicitly requested

chandan@cmaster:~/More$ javac New.java
chandan@cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error

So if you by mistake after compiling again use javac for running a program.

How do I test a website using XAMPP?

Just make a new folder inside C:\xampp\htdocs like C:\xampp\htdocs\test and place your index.php or whatever file in it. Access it by browsing localhost/test/

Good luck!

Hibernate-sequence doesn't exist

Just in case someone pulls their hair out with this problem like I did today, I couldn't resolve this error until I changed

spring.jpa.hibernate.dll-auto=create

to

spring.jpa.properties.hibernate.hbm2ddl.auto=create

HtmlSpecialChars equivalent in Javascript?

function htmlEscape(str){
    return str.replace(/[&<>'"]/g,x=>'&#'+x.charCodeAt(0)+';')
}

This solution uses the numerical code of the characters, for example < is replaced by &#60;.

Although its performance is slightly worse than the solution using a map, it has the advantages:

  • Not dependent on a library or DOM
  • Pretty easy to remember (you don't need to memorize the 5 HTML escape characters)
  • Little code
  • Reasonably fast (it's still faster than 5 chained replace)

Static image src in Vue.js template

@Pantelis answer somehow steered me to a solution for a similar misunderstanding. A message board project I'm working on needs to show an optional image. I was having fits trying to get the src=imagefile to concatenate a fixed path and variable filename string until I saw the quirky use of "''" quotes :-)

<template id="symp-tmpl">
  <div>
    <div v-for="item in items" style="clear: both;">
      <div v-if="(item.imagefile !== '[none]')">
        <img v-bind:src="'/storage/userimages/' + item.imagefile">
      </div>
      sub: <span>@{{ item.subject }}</span>
      <span v-if="(login == item.author)">[edit]</span>
      <br>@{{ item.author }}
      <br>msg: <span>@{{ item.message }}</span>
    </div>
  </div>
</template>

jquery: get id from class selector

Use "attr" method in jquery.

$('.test').click(function(){
    var id = $(this).attr('id');
});

How to use Class<T> in Java?

Just use the beef class:

public <T> T beefmarshal( Class<beef> beefClass, InputBeef inputBeef )
     throws JAXBException {
     String packageName = docClass.getPackage().getBeef();
     JAXBContext beef = JAXBContext.newInstance( packageName );
     Unmarshaller u = beef.createBeef();
     JAXBElement<T> doc = (JAXBElement<T>)u.beefmarshal( inputBeef );
     return doc.getBeef();
}

Check if Key Exists in NameValueCollection

You could use the Get method and check for null as the method will return null if the NameValueCollection does not contain the specified key.

See MSDN.

jQuery and TinyMCE: textarea value doesn't submit

When you run ajax on your form, you need to tell TinyMCE to update your textarea first:

// TinyMCE will now save the data into textarea
tinyMCE.triggerSave(); 
// now grap the data
var form_data = form.serialize(); 

How to increase code font size in IntelliJ?

The font used in menus, dialogs and tool windows can be changed in Settings > Appearance & Behavior > Use custom font.Setting dialog

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) Function in Android:

  1. When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity.

  2. When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity.

  3. After Orientation changed then onCreate(Bundle savedInstanceState) will call and recreate the activity and load all data from savedInstanceState.

  4. Basically Bundle class is used to stored the data of activity whenever above condition occur in app.

  5. onCreate() is not required for apps. But the reason it is used in app is because that method is the best place to put initialization code.

  6. You could also put your initialization code in onStart() or onResume() and when you app will load first, it will work same as in onCreate().

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

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

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

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

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

ValueError: unconverted data remains: 02:05

Well it was very simple. I was missing the format of the date in the json file, so I should write :

st = datetime.strptime(st, '%A %d %B %H %M')

because in the json file the date was like :

"start": "Friday 06 December 02:05",

Manually install Gradle and use it in Android Studio

1.Download the Gradle form gradle distribution

2.Extract file to some location

3.Open Android Studio : File > Settings > Gradle > Use local gradle distribution navigate the path where you have extracted the gradle.

4.click apply and ok

Done

How to change TextField's height and width?

To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.

How to input a regex in string.replace?

replace method of string objects does not accept regular expressions but only fixed strings (see documentation: http://docs.python.org/2/library/stdtypes.html#str.replace).

You have to use re module:

import re
newline= re.sub("<\/?\[[0-9]+>", "", line)

Spring boot - Not a managed type

I am using spring boot 2.0 and I fixed this by replacing @ComponentScan with @EntityScan

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Solution to the problem

as mentioned by Uberfuzzy [ real cause of problem ]

If you look at the PHP constant [PATH_SEPARATOR][1], you will see it being ":" for you.

If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts

  • . (this means the current directory your code is in)
  • /usr/share/pear
  • /usr/share/ph

Any attempts to include()/require() things, will look in these directories, in this order.

It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()

That was the cause of error.

Now coming to solution

  1. Step 1 : Find you php.ini file using command php --ini ( in my case : /etc/php5/cli/php.ini )
  2. Step 2 : find include_path in vi using esc then press /include_path then enter
  3. Step 3 : uncomment that line if commented and include your server directory, your path should look like this include_path = ".:/usr/share/php:/var/www/<directory>/"
  4. Step 4 : Restart apache sudo service apache2 restart

This is it. Hope it helps.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

Python: How exactly can you take a string, split it, reverse it and join it back together again?

You mean this?

from string import punctuation, digits

takeout = punctuation + digits

turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis

BackgroundWorker vs background Thread

Pretty much what Matt Davis said, with the following additional points:

For me the main differentiator with BackgroundWorker is the automatic marshalling of the completed event via the SynchronizationContext. In a UI context this means the completed event fires on the UI thread, and so can be used to update UI. This is a major differentiator if you are using the BackgroundWorker in a UI context.

Tasks executed via the ThreadPool cannot be easily cancelled (this includes ThreadPool. QueueUserWorkItem and delegates execute asyncronously). So whilst it avoids the overhead of thread spinup, if you need cancellation either use a BackgroundWorker or (more likely outside of the UI) spin up a thread and keep a reference to it so you can call Abort().

How to prevent favicon.ico requests?

You could use

<link rel="shortcut icon" href="http://localhost/" />

That way it won't actually be requested from the server.

Add timestamp column with default NOW() for new rows only

You need to add the column with a default of null, then alter the column to have default now().

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();

Difference between __getattr__ vs __getattribute__

In reading through Beazley & Jones PCB, I have stumbled on an explicit and practical use-case for __getattr__ that helps answer the "when" part of the OP's question. From the book:

"The __getattr__() method is kind of like a catch-all for attribute lookup. It's a method that gets called if code tries to access an attribute that doesn't exist." We know this from the above answers, but in PCB recipe 8.15, this functionality is used to implement the delegation design pattern. If Object A has an attribute Object B that implements many methods that Object A wants to delegate to, rather than redefining all of Object B's methods in Object A just to call Object B's methods, define a __getattr__() method as follows:

def __getattr__(self, name):
    return getattr(self._b, name)

where _b is the name of Object A's attribute that is an Object B. When a method defined on Object B is called on Object A, the __getattr__ method will be invoked at the end of the lookup chain. This would make code cleaner as well, since you do not have a list of methods defined just for delegating to another object.

How to quickly edit values in table in SQL Server Management Studio?

Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200".

jQuery: Can I call delay() between addClass() and such?

Delay operates on a queue. and as far as i know css manipulation (other than through animate) is not queued.

Check if a class is derived from a generic class

(Reposted due to a massive rewrite)

JaredPar's code answer is fantastic, but I have a tip that would make it unnecessary if your generic types are not based on value type parameters. I was hung up on why the "is" operator would not work, so I have also documented the results of my experimentation for future reference. Please enhance this answer to further enhance its clarity.

TIP:

If you make certain that your GenericClass implementation inherits from an abstract non-generic base class such as GenericClassBase, you could ask the same question without any trouble at all like this:

typeof(Test).IsSubclassOf(typeof(GenericClassBase))

IsSubclassOf()

My testing indicates that IsSubclassOf() does not work on parameterless generic types such as

typeof(GenericClass<>)

whereas it will work with

typeof(GenericClass<SomeType>)

Therefore the following code will work for any derivation of GenericClass<>, assuming you are willing to test based on SomeType:

typeof(Test).IsSubclassOf(typeof(GenericClass<SomeType>))

The only time I can imagine that you would want to test by GenericClass<> is in a plug-in framework scenario.


Thoughts on the "is" operator

At design-time C# does not allow the use of parameterless generics because they are essentially not a complete CLR type at that point. Therefore, you must declare generic variables with parameters, and that is why the "is" operator is so powerful for working with objects. Incidentally, the "is" operator also can not evaluate parameterless generic types.

The "is" operator will test the entire inheritance chain, including interfaces.

So, given an instance of any object, the following method will do the trick:

bool IsTypeof<T>(object t)
{
    return (t is T);
}

This is sort of redundant, but I figured I would go ahead and visualize it for everybody.

Given

var t = new Test();

The following lines of code would return true:

bool test1 = IsTypeof<GenericInterface<SomeType>>(t);

bool test2 = IsTypeof<GenericClass<SomeType>>(t);

bool test3 = IsTypeof<Test>(t);

On the other hand, if you want something specific to GenericClass, you could make it more specific, I suppose, like this:

bool IsTypeofGenericClass<SomeType>(object t)
{
    return (t is GenericClass<SomeType>);
}

Then you would test like this:

bool test1 = IsTypeofGenericClass<SomeType>(t);

How to escape double quotes in a title attribute

Here's a snippet of the HTML escape characters taken from a cached page on archive.org:

&#060   |   <   less than sign
&#064   |   @   at sign
&#093   |   ]   right bracket
&#123   |   {   left curly brace
&#125   |   }   right curly brace
&#133   |   …   ellipsis
&#135   |   ‡   double dagger
&#146   |   ’   right single quote
&#148   |   ”   right double quote
&#150   |   –   short dash
&#153   |   ™   trademark
&#162   |   ¢   cent sign
&#165   |   ¥   yen sign
&#169   |   ©   copyright sign
&#172   |   ¬   logical not sign
&#176   |   °   degree sign
&#178   |   ²   superscript 2
&#185   |   ¹   superscript 1
&#188   |   ¼   fraction 1/4
&#190   |   ¾   fraction 3/4
&#247   |   ÷   division sign
&#8221  |   ”   right double quote
&#062   |   >   greater than sign
&#091   |   [   left bracket
&#096   |   `   back apostrophe
&#124   |   |   vertical bar
&#126   |   ~   tilde
&#134   |   †   dagger
&#145   |   ‘   left single quote
&#147   |   “   left double quote
&#149   |   •   bullet
&#151   |   —   longer dash
&#161   |   ¡   inverted exclamation point
&#163   |   £   pound sign
&#166   |   ¦   broken vertical bar
&#171   |   «   double left than sign
&#174   |   ®   registered trademark sign
&#177   |   ±   plus or minus sign
&#179   |   ³   superscript 3
&#187   |   »   double greater-than sign
&#189   |   ½   fraction 1/2
&#191   |   ¿   inverted question mark
&#8220  |   “   left double quote
&#8212  |   —   dash

How to simulate key presses or a click with JavaScript?

For simulating keyboard events in Chrome:

There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for it is posted in this SO answer.

linking jquery in html

Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.

What does the "yield" keyword do?

For those who prefer a minimal working example, meditate on this interactive Python session:

>>> def f():
...   yield 1
...   yield 2
...   yield 3
... 
>>> g = f()
>>> for i in g:
...   print(i)
... 
1
2
3
>>> for i in g:
...   print(i)
... 
>>> # Note that this time nothing was printed

Twitter Bootstrap 3 Sticky Footer

Here's the Sticky Footer simplified code as of today because they're always optimizing it and this is GOOD:

HTML

<!DOCTYPE html>
<html lang="en">
  <head></head>

  <body>

    <!-- Fixed navbar -->
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li class="divider"></li>
                <li class="dropdown-header">Nav header</li>
                <li><a href="#">Separated link</a></li>
                <li><a href="#">One more separated link</a></li>
              </ul>
            </li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </div>

    <!-- Begin page content -->
    <div class="container">
      <div class="page-header">
        <h1>Sticky footer with fixed navbar</h1>
      </div>
      <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added with <code>padding-top: 60px;</code> on the <code>body > .container</code>.</p>
      <p>Back to <a href="../sticky-footer">the default sticky footer</a> minus the navbar.</p>
    </div>

    <footer>
      <div class="container">
        <p class="text-muted">Place sticky footer content here.</p>
      </div>
    </footer>

  </body>
</html>

CSS

/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

Force IE compatibility mode off using tags

This is due to the setting within IE Compatibility settings which says that all Intranet sites should run in compatibility mode. You can untick this via a group policy (or just plain unticking it in IE), or you can set the following:

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

Apparently it is not possible to change the compatibility view settings as a group policy but it is something that can perhaps be changed in the registry, this meta tag works fine for me, I had to make the required attribute work as part of a html form, it worked in chrome and firefox but not IE.

Here is a nice visual of what browsers support each individual html 5 element.

http://html5readiness.com/

Notice the one common denominator Google Chrome, it supports everything. Hope this is of help

How do I solve this "Cannot read property 'appendChild' of null" error?

For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.

<html>
    <head>
        <script>
                var div, container = document.getElementById("container")
                for(var i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);
                    };
                    container.appendChild(div);
                }
            </script>

    </head>
    <body>
        <div id="container"></div>
    </body>
 </html>

https://codepen.io/pcwanderer/pen/MMEREr

Looking at the error in the console for the above code.

Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.

<html>
    <head>
        <style>
        #container{
            height: 200px;
            width: 700px;
            background-color: red;
            margin: 10px;
        }


        div{
            height: 100px;
            width: 100px;
            background-color: purple;
            margin: 20px;
            display: inline-block;
        }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script>
                var div, container = document.getElementById("container")
                for(let i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);
                    };
                    container.appendChild(div);
                }
            </script>
    </body>
</html>

https://codepen.io/pcwanderer/pen/pXWBQL

I hope this helps. :)

How to install a specific version of package using Composer?

In your composer.json, you can put:

{
    "require": {
        "vendor/package": "version"
    }
}

then run composer install or composer update from the directory containing composer.json. Sometimes, for me, composer is hinky, so I'll start with composer clear-cache; rm -rf vendor; rm composer.lock before composer install to make sure it's getting fresh stuff.


Of course, as the other answers point out you can run the following from the terminal:

composer require vendor/package:version

And on versioning:
- Composer's official versions article
- Ecosia Search

Android: set view style programmatically

This is quite old question but solution that worked for me now is to use 4th parameter of constructor defStyleRes - if available.. on view... to set style

Following works for my purposes (kotlin):

val textView = TextView(context, null, 0, R.style.Headline1)

Android Studio emulator does not come with Play Store for API 23

As of now, Installing the apks to the /system directory seems to be working using adb push command.

Some hidden service was automatically remounting the /system directory in read-only mode.

Any way I was able to install the Play store in a normal virtual-machine ( Ie, non-Google-Api virtual machine ) by simply mounting the system.img file from my OS and by copying over the files.

# To be executed as root user in your Unix based OS
mkdir sys_temp
mount $SDK_HOME/system-images/android-23/default/x86/system.img sys_temp -o loop
cp Phonesky.apk GmsCore.apk GoogleLoginService.apk GoogleServicesFramework.apk ./sys_temp/priv-app/
umount sys_temp
rmdir sys_temp

The APK files can be pulled from any real Android device running Google Apps by using adb pull command

[ To get the exact path of the apks, we can use command pm list packages -f inside the adb shell ]

Making a PowerShell POST request if a body param starts with '@'

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

Gson: Is there an easier way to serialize a map

Default

The default Gson implementation of Map serialization uses toString() on the key:

Gson gson = new GsonBuilder()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will give:

{
  "java.awt.Point[x\u003d1,y\u003d2]": "a",
  "java.awt.Point[x\u003d3,y\u003d4]": "b"
}


Using enableComplexMapKeySerialization

If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:

Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

Will return:

[
  [
    {
      "x": 1,
      "y": 2
    },
    "a"
  ],
  [
    {
      "x": 3,
      "y": 4
    },
    "b"
  ]
]

More details can be found here.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

AngularJS: How do I manually set input to $valid in controller?

to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.

delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

Just copied file: org.apache.http.legacy.jar from Android/Sdk/platforms/android-23/optional folder into project folder app/libs.

Worked like charm for 23.1.1.

Detecting attribute change of value of an attribute I made

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

This really should be a comment to Brad Rippe's answer, but alas, not enough rep. That answer got me 90% of the way there. In my case, the installation and configuration of the databases put entries in the tnsnames.ora file for the databases I was running. First, I was able to connect to the database by setting the environment variables (Windows):

set ORACLE_SID=mydatabase
set ORACLE_HOME=C:\Oracle\product\11.2.0\dbhome_1

and then connecting using

sqlplus / as sysdba

Next, running the command from Brad Rippe's answer:

select value from v$parameter where name='service_names';

showed that the names didn't match exactly. The entries as created using Oracle's Database Configuration Assistant where originally:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase.mydomain.com)
    )
  ) 

The service name from the query was just mydatabase rather than mydatabase.mydomain.com. I edited the tnsnames.ora file to just the base name without the domain portion so they looked like this:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase)
    )
  ) 

I restarted the TNS Listener service (I often use lsnrctl stop and lsnrctl start from an administrator command window [or Windows Powershell] instead of the Services control panel, but both work.) After that, I was able to connect.

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

Applying same filter in HTML with multiple columns, just example:

 variable = (array | filter : {Lookup1Id : subject.Lookup1Id, Lookup2Id : subject.Lookup2Id} : true)

Sql Query to list all views in an SQL Server 2005 database

Necromancing.

Since you said ALL views, technically, all answers to date are WRONG.
Here is how to get ALL views:

SELECT 
     sch.name AS view_schema 
    ,sysv.name AS view_name 
    ,ISNULL(sysm.definition, syssm.definition) AS view_definition 
    ,create_date 
    ,modify_date 
FROM sys.all_views AS sysv 

INNER JOIN sys.schemas AS sch 
    ON sch.schema_id = sysv.schema_id 

LEFT JOIN sys.sql_modules AS sysm 
    ON sysm.object_id = sysv.object_id 

LEFT JOIN sys.system_sql_modules AS syssm 
    ON syssm.object_id = sysv.object_id 

-- INNER JOIN sys.objects AS syso ON syso.object_id = sysv.object_id 

WHERE (1=1) 
AND (sysv.type = 'V') -- seems unnecessary, but who knows
-- AND sch.name = 'INFORMATION_SCHEMA' 
/*
AND sysv.is_ms_shipped = 0  
AND NOT EXISTS 
(
    SELECT * FROM sys.extended_properties AS syscrap
    WHERE syscrap.major_id = sysv.object_id
    AND syscrap.minor_id = 0 
    AND syscrap.class = 1 
    AND syscrap.name = N'microsoft_database_tools_support' 
)  
*/

ORDER BY 
     view_schema 
    ,view_name 

javascript - match string against the array of regular expressions

You could use .test() which returns a boolean value when is find what your looking for in another string:

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);  
if (FoundIt) { /* DO STUFF */ }

How to get multiple counts with one SQL query?

For MySQL, this can be shortened to:

SELECT distributor_id,
    COUNT(*) total,
    SUM(level = 'exec') ExecCount,
    SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

Using request.setAttribute in a JSP page

Correct me if wrong...I think request does persist between consecutive pages..

Think you traverse from page 1--> page 2-->page 3.

You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".

I mean something like this in page 2 fails:

Where as the same thing has worked in case of page 1 like:

So I think I would need to proceed with either of the two options suggested by Phill.

AngularJS ngClass conditional

Your first attempt was almost right, It should work without the quotes.

{test: obj.value1 == 'someothervalue'}

Here is a plnkr.

The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here. If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

Just to complement: You can also use logical operators to form logical expressions like

ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"

How to check if $_GET is empty?

Just to provide some variation here: You could check for

if ($_SERVER["QUERY_STRING"] == null)

it is completely identical to testing $_GET.

assign function return value to some variable using javascript

AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status is undefined when it is returned.

Effectively, your code works as follows:

function doSomething(someargums) {
     return status;
}

var response = doSomething();

And then some time later, your AJAX request is completing; but it's already too late

You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.

Where you previously may have had

var response = doSomething();

alert(response);

You should do:

function doSomething() {  
    $.ajax({
           url:'action.php',
           type: "POST",
           data: dataString,
           success: function (txtBack) { 
            alert(txtBack);
           })
    }); 
};

Using Python String Formatting with Lists

The same as @neobot's answer but a little more modern and succinct.

>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'

C++ class forward declaration

In order for new T to compile, T must be a complete type. In your case, when you say new tile_tree_apple inside the definition of tile_tree::tick, tile_tree_apple is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.

Something like:

class A
{
    void f1();
    void f2();
};
class B
{
   void f3();
   void f4();
};

inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}

When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Adding text to a cell in Excel using VBA

You can also use the cell property.

Cells(1, 1).Value = "Hey, what's up?"

Make sure to use a . before Cells(1,1).Value as in .Cells(1,1).Value, if you are using it within With function. If you are selecting some sheet.

how to read a long multiline string line by line in python

What about using .splitlines()?

for line in textData.splitlines():
    print(line)
    lineResult = libLAPFF.parseLine(line)

How to fix 'Notice: Undefined index:' in PHP form action

Assuming you only copy/pasted the relevant code and your form includes <form method="POST">


if(isset($_POST['filename'])){
    $filename = $_POST['filename'];
}
if(isset($filename)){ 
    echo $filename;
}

If _POST is not set the filename variable won't be either in the above example.

An alternative way:

$filename = false;
if(isset($_POST['filename'])){
    $filename = $_POST['filename'];
 } 
    echo $filename; //guarenteed to be set so isset not needed

In this example filename is set regardless of the situation with _POST. This should demonstrate the use of isset nicely.

More information here: http://php.net/manual/en/function.isset.php

Remove values from select list based on condition

Removing an option

$("#val option[value='A']").remove();

Unit testing with Spring Security

Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:

@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
    String message = messageService.getMessage();
    ...
}

There is also the option to use @WithUserDetails to emulate a UserDetails returned from the UserDetailsService, e.g.

@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
    String message = messageService.getMessage();
    ...
}

More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)

How to delete a cookie using jQuery?

Try this

 $.cookie('_cookieName', null, { path: '/' });

The { path: '/' } do the job for you

Openssl : error "self signed certificate in certificate chain"

If you're running Charles and trying to build a container then you'll most likely get this error.

Make sure to disable Charles (macos) proxy under proxy -> macOS proxy

Charles is an

HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.

So anything similar may cause the same issue.

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I noticed I had accidentally deleted var window:UIWindow? line from AppDelegate. Introducing it again fixed the issue for me!

What is <scope> under <dependency> in pom.xml for?

Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

cannot redeclare block scoped variable (typescript)

For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.

Just add:

export {};

at the top of your code.

Credit to EUGENE MURAVITSKY

How to make an autocomplete address field with google maps api?

Drifting a bit, but it would be relatively easy to autofill the US City/State or CA City/Provence when the user enters her postal code using a lookup table.

Here's how you could do it if you could force people to bend to your will:

  1. User enters: postal (zip) code

    You fill: state, city (province, for Canada)

  2. User starts to enter: streetname

    You: autofill

  3. You display: a range of allowed address numbers

    User: enters the number

Done.

Here's how it is natural for people to do it:

  1. User enters: address number

    You: do nothing

  2. User starts to enter: street name

    You: autofill, drawing from a massive list of every street in the country

  3. User enters: city

    You: autofill

  4. User enters: state/provence

    You: is it worth autofilling a few chars?

  5. You: autofill postal (zip) code, if you can (because some codes straddle cities).


Now you know why people charge $$$ to do this. :)

For the street address, consider there are two parts: numeric and streetname. If you have the zip code, then you can narrow down the available streets, but most people enter the numeric part first, which is backwa

How to force remounting on React components?

I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.

import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';

const LifeActionCreate = () => {
  let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();

  const onCreate = e => {
    const db = firebase.firestore();

    db.collection('actions').add({
      label: newLifeActionLabel
    });
    alert('New Life Insurance Added');
    setNewLifeActionLabel('');
  };

  return (
    <Card style={{ padding: '15px' }}>
      <form onSubmit={onCreate}>
        <label>Name</label>
        <input
          value={newLifeActionLabel}
          onChange={e => {
            setNewLifeActionLabel(e.target.value);
          }}
          placeholder={'Name'}
        />

        <Button onClick={onCreate}>Create</Button>
      </form>
    </Card>
  );
};

Some React Hooks in there

How to create python bytes object from long hex string?

Works in Python 2.7 and higher including python3:

result = bytearray.fromhex('deadbeef')

Note: There seems to be a bug with the bytearray.fromhex() function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown:

>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str`

Return datetime object of previous month

Here is some code to do just that. Haven't tried it out myself...

def add_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month earlier.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> add_one_month(datetime.date(2010, 1, 31))
        datetime.date(2010, 2, 28)
    """
    import datetime
    one_day = datetime.timedelta(days=1)
    one_month_later = t + one_day
    while one_month_later.month == t.month:  # advance to start of next month
        one_month_later += one_day
    target_month = one_month_later.month
    while one_month_later.day < t.day:  # advance to appropriate day
        one_month_later += one_day
        if one_month_later.month != target_month:  # gone too far
            one_month_later -= one_day
            break
    return one_month_later

def subtract_one_month(t):
    """Return a `datetime.date` or `datetime.datetime` (as given) that is
    one month later.

    Note that the resultant day of the month might change if the following
    month has fewer days:

        >>> subtract_one_month(datetime.date(2010, 3, 31))
        datetime.date(2010, 2, 28)
    """
    import datetime
    one_day = datetime.timedelta(days=1)
    one_month_earlier = t - one_day
    while one_month_earlier.month == t.month or one_month_earlier.day > t.day:
        one_month_earlier -= one_day
    return one_month_earlier

Python syntax for "if a or b or c but not all of them"

What about: (unique condition)

if (bool(a) + bool(b) + bool(c) == 1):

Notice, if you allow two conditions too you could do that

if (bool(a) + bool(b) + bool(c) in [1,2]):

Java: How to convert List to Map

I like Kango_V's answer, but I think it's too complex. I think this is simpler - maybe too simple. If inclined, you could replace String with a Generic marker, and make it work for any Key type.

public static <E> Map<String, E> convertListToMap(Collection<E> sourceList, ListToMapConverterInterface<E> converterInterface) {
    Map<String, E> newMap = new HashMap<String, E>();
    for( E item : sourceList ) {
        newMap.put( converterInterface.getKeyForItem( item ), item );
    }
    return newMap;
}

public interface ListToMapConverterInterface<E> {
    public String getKeyForItem(E item);
}

Used like this:

        Map<String, PricingPlanAttribute> pricingPlanAttributeMap = convertListToMap( pricingPlanAttributeList,
                new ListToMapConverterInterface<PricingPlanAttribute>() {

                    @Override
                    public String getKeyForItem(PricingPlanAttribute item) {
                        return item.getFullName();
                    }
                } );

How to check if any value is NaN in a Pandas DataFrame

Depending on the type of data you're dealing with, you could also just get the value counts of each column while performing your EDA by setting dropna to False.

for col in df:
   print df[col].value_counts(dropna=False)

Works well for categorical variables, not so much when you have many unique values.

How to remove a key from HashMap while iterating over it?

To remove specific key and element from hashmap use

hashmap.remove(key)

full source code is like

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

Source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap

Extract a single (unsigned) integer from a string

preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

Validation of file extension before uploading file

$(function () {
    $('input[type=file]').change(function () {
        var val = $(this).val().toLowerCase(),
            regex = new RegExp("(.*?)\.(docx|doc|pdf|xml|bmp|ppt|xls)$");

        if (!(regex.test(val))) {
            $(this).val('');
            alert('Please select correct file format');
        }
    });
});

Getting request payload from POST request in Java servlet

You only need

request.getParameterMap()

for getting the POST and GET - Parameters.

The Method returns a Map<String,String[]>.

You can read the parameters in the Map by

Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
    String[] paramValues = map.get(paramName);

    //Get Values of Param Name
    for(String valueOfParam:paramValues) {
        //Output the Values
        System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
    }
}

How to retrieve checkboxes values in jQuery

A much easier and shorted way which I am using to accomplish the same, using answer from another post, is like this:

var checkedCities = $('input[name=city]:checked').map(function() {
    return this.value;
}).get();

Originally the cities are retrieved from a MySQL database, and looped in PHP while loop:

while ($data = mysql_fetch_assoc($all_cities)) {
<input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?><br />
<?php } ?>

Now, using the above jQuery code, I get all the city_id values, and submit back to the database using $.get(...)

This has made my life so easy since now the code is fully dynamic. In order to add more cities, all I need to do is to add more cities in my database, and no worries on PHP or jQuery end.

What does the PHP error message "Notice: Use of undefined constant" mean?

Am not sure if there is any difference am using code igniter and i use "" for the names and it works great.

$department = mysql_real_escape_string($_POST["department"]);
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$message = mysql_real_escape_string($_POST["message"]);

regards,

Jorge.

Sum a list of numbers in Python

Question 2: To sum a list of integers:

a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18

If the list contains integers as strings:

a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)

iFrame src change event detection?

Answer based on JQuery < 3

$('#iframeid').load(function(){
    alert('frame has (re)loaded');
});

As mentioned by subharb, as from JQuery 3.0 this needs to be changed to:

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');
});

https://jquery.com/upgrade-guide/3.0/#breaking-change-load-unload-and-error-removed

find without recursion

I think you'll get what you want with the -maxdepth 1 option, based on your current command structure. If not, you can try looking at the man page for find.

Relevant entry (for convenience's sake):

-maxdepth levels
          Descend at most levels (a non-negative integer) levels of direc-
          tories below the command line arguments.   `-maxdepth  0'  means
          only  apply the tests and actions to the command line arguments.

Your options basically are:

# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f

Or:

#  DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f

Python urllib2, basic HTTP authentication, and tr.im

This seems to work really well (taken from another thread)

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

How to install Openpyxl with pip

It worked for me by executing "python37 -m pip install openpyxl"

Use .htaccess to redirect HTTP to HTTPs

It works for me:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !on           
RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Difference between == and === in JavaScript

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false

How to use null in switch

switch (String.valueOf(value)){
    case "null":
    default: 
}

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

1.Click on Configure

2.Then Choose Project Defaults

3.Click on Project Structure

4.Set android sdk path

You will find here "C:\User\YourPcname\AppData\Local\SDK"

Note: Sometime AppData may hidden if it will not show then enable show hidden content.

5.Apply Changes

6.Then Select Sdk From Configure option

7.Then Android sdk manager page is open

8.In bottom you will see Install packages option

9.Install them and enjoy.

How do I fix a Git detached head?

HEAD is a pointer, and it points — directly or indirectly — to a particular commit:

Attached  HEAD means that it is attached to some branch (i.e. it points to a branch).
Detached HEAD means that it is not attached to any branch, i.e. it points directly to some commit.

enter image description here

In other words:

  • If it points to a commit directly, the HEAD is detached.
  • If it points to a commit indirectly, (i.e. it points to a branch, which in turn points to a commit), the HEAD is attached.

To better understand situations with attached / detached HEAD, let's show the steps leading to the quadruplet of pictures above.

We begin with the same state of the repository (pictures in all quadrants are the same):

enter image description here


Now we want to perform git checkout — with different targets in the individual pictures (commands on top of them are dimmed to emphasize that we are only going to apply those commands):

enter image description here


This is the situation after performing those commands:

enter image description here

As you can see, the HEAD points to the target of the git checkout command — to a branch (first 3 images of the quadruplet), or (directly) to a commit (the last image of the quadruplet).

The content of the working directory is changed, too, to be in accordance with the appropriate commit (snapshot), i.e. with the commit pointed (directly or indirectly) by the HEAD.


So now we are in the same situation as in the start of this answer:

enter image description here

Deploying Java webapp to Tomcat 8 running in Docker container

You are trying to copy the war file to a directory below webapps. The war file should be copied into the webapps directory.

Remove the mkdir command, and copy the war file like this:

COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

Tomcat will extract the war if autodeploy is turned on.

SQLAlchemy IN clause

An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below:

id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()

Hope everything works for you.

How to perform mouseover function in Selenium WebDriver using Java?

Check this example how we could implement this.

enter image description here

public class HoverableDropdownTest {

    private WebDriver driver;
    private Actions action;

    //Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
    Consumer < By > hover = (By by) -> {
        action.moveToElement(driver.findElement(by))
              .perform();
    };

    @Test
    public void hoverTest() {
        driver.get("https://www.bootply.com/render/6FC76YQ4Nh");

        hover.accept(By.linkText("Dropdown"));
        hover.accept(By.linkText("Dropdown Link 5"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
        hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
    }

    @BeforeTest
    public void setupDriver() {
        driver = new FirefoxDriver();
        action = new Actions(driver);
    }

    @AfterTest
    public void teardownDriver() {
        driver.quit();
    }

}

For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/