Programs & Examples On #Durable duplex

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

In my case was facing the same issue, especially the first pull request trying after remotely adding a Git repository. The following error was facing.

fatal: refusing to merge unrelated histories on every try

Use the --allow-unrelated-histories command. It works perfectly.

git pull origin branchname --allow-unrelated-histories

Nested ifelse statement

Using the SQL CASE statement with the dplyr and sqldf packages:

Data

df <-structure(list(idnat = structure(c(2L, 2L, 2L, 1L), .Label = c("foreign", 
"french"), class = "factor"), idbp = structure(c(3L, 1L, 4L, 
2L), .Label = c("colony", "foreign", "mainland", "overseas"), class = "factor")), .Names = c("idnat", 
"idbp"), class = "data.frame", row.names = c(NA, -4L))

sqldf

library(sqldf)
sqldf("SELECT idnat, idbp,
        CASE 
          WHEN idbp IN ('colony', 'overseas') THEN 'overseas' 
          ELSE idbp 
        END AS idnat2
       FROM df")

dplyr

library(dplyr)
df %>% 
mutate(idnat2 = case_when(.$idbp == 'mainland' ~ "mainland", 
                          .$idbp %in% c("colony", "overseas") ~ "overseas", 
                         TRUE ~ "foreign"))

Output

    idnat     idbp   idnat2
1  french mainland mainland
2  french   colony overseas
3  french overseas overseas
4 foreign  foreign  foreign

What precisely does 'Run as administrator' do?

Windows 7 requires that you intentionally ask for certain privileges so that a malicious program can't do bad things to you. If the free calculator you downloaded needed to be run as an administrator, you would know something is up. There are OS commands to elevate the privilege of your application (which will request confirmation from the user).

A good description can be found at:

http://msdn.microsoft.com/en-us/magazine/cc163486.aspx#S4

Basic HTTP and Bearer Token Authentication

With nginx you can send both tokens like this (even though it's against the standard):

Authorization: Basic basic-token,Bearer bearer-token

This works as long as the basic token is first - nginx successfully forwards it to the application server.

And then you need to make sure your application can properly extract the Bearer from the above string.

WooCommerce return product object by id

Use this method:

$_product = wc_get_product( $id );

Official API-docs: wc_get_product

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

First of all you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):

  • empty statement
  • var statement
  • expression statement
  • do-while statement
  • continue statement
  • break statement
  • return statement
  • throw statement

The concrete rules of ASI, are described in the specification §11.9.1 Rules of Automatic Semicolon Insertion

Three cases are described:

  1. When an offending token is encountered that is not allowed by the grammar, a semicolon is inserted before it if:
  • The token is separated from the previous token by at least one LineTerminator.
  • The token is }

e.g.:

    { 1
    2 } 3

is transformed to

    { 1
    ;2 ;} 3;

The NumericLiteral 1 meets the first condition, the following token is a line terminator.
The 2 meets the second condition, the following token is }.

  1. When the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete Program, then a semicolon is automatically inserted at the end of the input stream.

e.g.:

    a = b
    ++c

is transformed to:

    a = b;
    ++c;
  1. This case occurs when a token is allowed by some production of the grammar, but the production is a restricted production, a semicolon is automatically inserted before the restricted token.

Restricted productions:

    UpdateExpression :
        LeftHandSideExpression [no LineTerminator here] ++
        LeftHandSideExpression [no LineTerminator here] --
    
    ContinueStatement :
        continue ;
        continue [no LineTerminator here] LabelIdentifier ;
    
    BreakStatement :
        break ;
        break [no LineTerminator here] LabelIdentifier ;
    
    ReturnStatement :
        return ;
        return [no LineTerminator here] Expression ;
    
    ThrowStatement :
        throw [no LineTerminator here] Expression ; 

    ArrowFunction :
        ArrowParameters [no LineTerminator here] => ConciseBody

    YieldExpression :
        yield [no LineTerminator here] * AssignmentExpression
        yield [no LineTerminator here] AssignmentExpression

The classic example, with the ReturnStatement:

    return 
      "something";

is transformed to

    return;
      "something";

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

How do I add a simple jQuery script to WordPress?

Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever.

No. You should never just add a link to an external script like this in WordPress. Enqueuing them through the functions.php file ensures that scripts are loaded in the correct order.

Failure to enqueue them may result in your script not working, although it is written correctly.

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

Using regular expression in css?

I usually use * when I want to get all the strings that contain the wanted characters.

* used in regex, replaces all characters.

Used in SASS or CSS would be something like [id*="s"] and it will get all DOM elements with id "s......".

/* add red color to all div with id s .... elements */

div[id^="s"] {
    color: red;
}

How to ORDER BY a SUM() in MySQL?

Don'y forget that if you are mixing grouped (ie. SUM) fields and non-grouped fields, you need to GROUP BY one of the non-grouped fields.

Try this:

SELECT SUM(something) AS fieldname
FROM tablename
ORDER BY fieldname

OR this:

SELECT Field1, SUM(something) AS Field2
FROM tablename
GROUP BY Field1
ORDER BY Field2

And you can always do a derived query like this:

SELECT
   f1, f2
FROM
    (
        SELECT SUM(x+y) as f1, foo as F2
        FROM tablename 
        GROUP BY f2
    ) as table1
ORDER BY 
    f1

Many possibilities!

Return in Scala

I don't program Scala, but I use another language with implicit returns (Ruby). You have code after your if (elem.isEmpty) block -- the last line of code is what's returned, which is why you're not getting what you're expecting.

EDIT: Here's a simpler way to write your function too. Just use the boolean value of isEmpty and count to return true or false automatically:

def balanceMain(elem: List[Char]): Boolean =
{
    elem.isEmpty && count == 0
}

Execute a stored procedure in another stored procedure in SQL server

Procedure example:

Create  PROCEDURE SP_Name
     @UserName nvarchar(200),
     @Password nvarchar(200)
AS
BEGIN
    DECLARE  @loginID  int

    --Statements for this Store Proc
  --
  -- 
  --

  --execute second store procedure
  --below line calling sencond Store Procedure Exec is used for execute Store Procedure.
    **Exec SP_Name_2 @params** (if any) 


END

Uploading Images to Server android

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

ABOVE CODE TO SELECT IMAGE FROM GALLERY

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();

            String filePath = getPath(selectedImage);
            String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
            image_name_tv.setText(filePath);

            try {
                if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                    //FINE
                } else {
                    //NOT IN REQUIRED FORMAT
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

public String getPath(Uri uri) {
    String[] projection = {MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    column_index = cursor
            .getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    imagePath = cursor.getString(column_index);

    return cursor.getString(column_index);
}

NOW POST THE DATA USING MULTIPART FORM DATA

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");

Multipart FORM DATA

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
    File file = new File(filePath);
    Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
    Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
    mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}

FINALLY POST DATA TO SERVER

httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

Can a CSS class inherit one or more other classes?

I think this one is a better solution:

[class*=“button-“] {
  /* base button properties */
}
.button-primary { ... }
.button-plain { ... }

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

Store text file content line by line into array

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

ASP.NET MVC Html.DropDownList SelectedValue

The code in the previous MVC 3 post does not work but it is a good start. I will fix it. I have tested this code and it works in MVC 3 Razor C# This code uses the ViewModel pattern to populate a property that returns a List<SelectListItem>.

The Model class

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

The ViewModel class

using System.Web.Mvc;

public class ProductListviewModel
{
    public List<SelectListItem> Products { get; set; }
}

The Controller Method

public ViewResult List()
{
    var productList = new List<SelectListItem>();

    foreach (Product p in Products)
    {
        productList.Add(new SelectListItem
        {
            Value = p.ProductId.ToString(),
            Text = "Product: " + p.Name + " " + p.Price.ToString(),
            // To set the selected item use the following code 
            // Note: you should not set every item to selected
            Selected = true
        });
    }

    ProductListViewModel productListVM = new ProductListViewModeld();

    productListVM.Products = productList;

    return View(productListVM);
}

The view

@model MvcApp.ViewModels.ProductListViewModel

@using (Html.BeginForm())
{
    @Html.DropDownList("Products", Model.Products)
}

The HTML output will be something like

<select id="Products" name="Products">
    <option value="3">Product: Widget 10.00</option>
    <option value="4">Product: Gadget 5.95</option>
</select>

depending on how you format the output. I hope this helps. The code does work.

What does the Excel range.Rows property really do?

Range.Rows, Range.Columns and Range.Cells are Excel.Range objects, according to the VBA Type() functions:

?TypeName(Selection.rows)
Range
However, that's not the whole story: those returned objects are extended types that inherit every property and method from Excel::Range - but .Columns and .Rows have a special For... Each iterator, and a special .Count property that aren't quite the same as the parent Range object's iterator and count.

So .Cells is iterated and counted as a collection of single-cell ranges, just like the default iterator of the parent range.

But .Columns is iterated and counted as a collection of vertical subranges, each of them a single column wide;

...And .Rows is iterated and counted as a collection of horizontal subranges, each of them a single row high.

The easiest way to understand this is to step through this code and watch what's selected:

Public Sub Test() 
Dim SubRange As Range Dim ParentRange As Range
Set ParentRange = ActiveSheet.Range("B2:E5")

For Each SubRange In ParentRange.Cells SubRange.Select Next
For Each SubRange In ParentRange.Rows SubRange.Select Next
For Each SubRange In ParentRange.Columns SubRange.Select Next
For Each SubRange In ParentRange SubRange.Select Next
End Sub
Enjoy. And try it with a couple of merged cells in there, just to see how odd merged ranges can be.

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

Codeigniter LIKE with wildcard(%)

  $this->db->like('title', 'match', 'before'); 
 // Produces: WHERE title LIKE '%match' 

 $this->db->like('title', 'match', 'after'); 
// Produces: WHERE title LIKE 'match%' 

$this->db->like('title', 'match', 'both'); 
// Produces: WHERE title LIKE '%match%'

A Simple, 2d cross-platform graphics library for c or c++?

What about SDL?

Perhaps it's a bit too complex for your needs, but it's certainly cross-platform.

How to check if iframe is loaded or it has a content?

I got a trick working as follows: [have not tested cross-browser!]

Define iframe's onload event handler defined as

_x000D_
_x000D_
$('#myIframe').on('load', function() {_x000D_
    setTimeout(function() {_x000D_
        try {_x000D_
            console.log($('#myIframe')[0].contentWindow.document);_x000D_
        } catch (e) {_x000D_
            console.log(e);_x000D_
            if (e.message.indexOf('Blocked a frame with origin') > -1 || e.message.indexOf('from accessing a cross-origin frame.') > -1) {_x000D_
                alert('Same origin Iframe error found!!!');_x000D_
                //Do fallback handling if you want here_x000D_
            }_x000D_
        }_x000D_
    }, 1000);_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

Disclaimer: It works only for SAME ORIGIN IFRAME documents.

Using "Object.create" instead of "new"

Sometimes you cannot create an object with NEW but are still able to invoke the CREATE method.

For example: if you want to define a Custom Element it must derive from HTMLElement.

proto = new HTMLElement  //fail :(
proto = Object.create( HTMLElement.prototype )  //OK :)
document.registerElement( "custom-element", { prototype: proto } )

How to put a List<class> into a JSONObject and then read that object?

This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).

 Type collectionType = new TypeToken<List<Class>>() {
                } // end new
                        .getType();

                String gsonString = 
                new Gson().toJson(objList, collectionType);

Disable form auto submit on button click

Buttons like <button>Click to do something</button> are submit buttons.

Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).

Linq style "For Each"

There isn't anything built-in, but you can easily create your own extension method to do it:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}

Google Maps JS API v3 - Simple Multiple Marker Example

Here is a nearly complete example javascript function that will allow multiple markers defined in a JSONObject.

It will only display the markers that are with in the bounds of the map.

This is important so you are not doing extra work.

You can also set a limit to the markers so you are not showing an extreme amount of markers (if there is a possibility of a thing in your usage);

it will also not display markers if the center of the map has not changed more than 500 meters.
This is important because if a user clicks on the marker and accidentally drags the map while doing so you don't want the map to reload the markers.

I attached this function to the idle event listener for the map so markers will show only when the map is idle and will redisplay the markers after a different event.

In action screen shot there is a little change in the screen shot showing more content in the infowindow. enter image description here pasted from pastbin.com

_x000D_
_x000D_
<script src="//pastebin.com/embed_js/uWAbRxfg"></script>
_x000D_
_x000D_
_x000D_

How to dynamic new Anonymous Class?

Of cause it's possible to create dynamic classes using very cool ExpandoObject class. But recently I worked on project and faced that Expando Object is serealized in not the same format on xml as an simple Anonymous class, it was pity =( , that is why I decided to create my own class and share it with you. It's using reflection and dynamic directive , builds Assembly, Class and Instance truly dynamicly. You can add, remove and change properties that is included in your class on fly Here it is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static YourNamespace.DynamicTypeBuilderTest;

namespace YourNamespace
{

    /// This class builds Dynamic Anonymous Classes

    public class DynamicTypeBuilderTest
    {    
        ///   
        /// Create instance based on any Source class as example based on PersonalData
        ///
        public static object CreateAnonymousDynamicInstance(PersonalData personalData, Type dynamicType, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            var obj = Activator.CreateInstance(dynamicType);

            var propInfos = dynamicType.GetProperties();

            classDescriptionList.ForEach(x => SetValueToProperty(obj, propInfos, personalData, x));

            return obj;
        }

        private static void SetValueToProperty(object obj, PropertyInfo[] propInfos, PersonalData aisMessage, ClassDescriptorKeyValue description)
        {
            propInfos.SingleOrDefault(x => x.Name == description.Name)?.SetValue(obj, description.ValueGetter(aisMessage), null);
        }

        public static dynamic CreateAnonymousDynamicType(string entityName, List<ClassDescriptorKeyValue> classDescriptionList)
        {
            AssemblyName asmName = new AssemblyName();
            asmName.Name = $"{entityName}Assembly";
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule($"{asmName.Name}Module");

            TypeBuilder typeBuilder = moduleBuilder.DefineType($"{entityName}Dynamic", TypeAttributes.Public);

            classDescriptionList.ForEach(x => CreateDynamicProperty(typeBuilder, x));

            return typeBuilder.CreateTypeInfo().AsType();
        }

        private static void CreateDynamicProperty(TypeBuilder typeBuilder, ClassDescriptorKeyValue description)
        {
            CreateDynamicProperty(typeBuilder, description.Name, description.Type);
        }

        ///
        ///Creation Dynamic property (from MSDN) with some Magic
        ///
        public static void CreateDynamicProperty(TypeBuilder typeBuilder, string name, Type propType)
        {
            FieldBuilder fieldBuider = typeBuilder.DefineField($"{name.ToLower()}Field",
                                                            propType,
                                                            FieldAttributes.Private);

            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name,
                                                             PropertyAttributes.HasDefault,
                                                             propType,
                                                             null);

            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName |
                    MethodAttributes.HideBySig;

            MethodBuilder methodGetBuilder =
                typeBuilder.DefineMethod($"get_{name}",
                                           getSetAttr,
                                           propType,
                                           Type.EmptyTypes);

            ILGenerator methodGetIL = methodGetBuilder.GetILGenerator();

            methodGetIL.Emit(OpCodes.Ldarg_0);
            methodGetIL.Emit(OpCodes.Ldfld, fieldBuider);
            methodGetIL.Emit(OpCodes.Ret);

            MethodBuilder methodSetBuilder =
                typeBuilder.DefineMethod($"set_{name}",
                                           getSetAttr,
                                           null,
                                           new Type[] { propType });

            ILGenerator methodSetIL = methodSetBuilder.GetILGenerator();

            methodSetIL.Emit(OpCodes.Ldarg_0);
            methodSetIL.Emit(OpCodes.Ldarg_1);
            methodSetIL.Emit(OpCodes.Stfld, fieldBuider);
            methodSetIL.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodGetBuilder);
            propertyBuilder.SetSetMethod(methodSetBuilder);

        }

        public class ClassDescriptorKeyValue
        {
            public ClassDescriptorKeyValue(string name, Type type, Func<PersonalData, object> valueGetter)
            {
                Name = name;
                ValueGetter = valueGetter;
                Type = type;
            }

            public string Name;
            public Type Type;
            public Func<PersonalData, object> ValueGetter;
        }

        ///
        ///Your Custom class description based on any source class for example
        /// PersonalData
        public static IEnumerable<ClassDescriptorKeyValue> GetAnonymousClassDescription(bool includeAddress, bool includeFacebook)
        {
            yield return new ClassDescriptorKeyValue("Id", typeof(string), x => x.Id);
            yield return new ClassDescriptorKeyValue("Name", typeof(string), x => x.FirstName);
            yield return new ClassDescriptorKeyValue("Surname", typeof(string), x => x.LastName);
            yield return new ClassDescriptorKeyValue("Country", typeof(string), x => x.Country);
            yield return new ClassDescriptorKeyValue("Age", typeof(int?), x => x.Age);
            yield return new ClassDescriptorKeyValue("IsChild", typeof(bool), x => x.Age < 21);

            if (includeAddress)
                yield return new ClassDescriptorKeyValue("Address", typeof(string), x => x?.Contacts["Address"]);
            if (includeFacebook)
                yield return new ClassDescriptorKeyValue("Facebook", typeof(string), x => x?.Contacts["Facebook"]);
        }

        ///
        ///Source Data Class for example
        /// of cause you can use any other class
        public class PersonalData
        { 
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Country { get; set; }
            public int Age { get; set; }

            public Dictionary<string, string> Contacts { get; set; }
        }

    }
}

It is also very simple to use DynamicTypeBuilder, you just need put few lines like this:

    public class ExampleOfUse
    {
        private readonly bool includeAddress;
        private readonly bool includeFacebook;
        private readonly dynamic dynamicType;
        private readonly List<ClassDescriptorKeyValue> classDiscriptionList;
        public ExampleOfUse(bool includeAddress = false, bool includeFacebook = false)
        {
            this.includeAddress = includeAddress;
            this.includeFacebook = includeFacebook;
            this.classDiscriptionList = DynamicTypeBuilderTest.GetAnonymousClassDescription(includeAddress, includeFacebook).ToList();
            this.dynamicType = DynamicTypeBuilderTest.CreateAnonymousDynamicType("VeryPrivateData", this.classDiscriptionList);
        }

        public object Map(PersonalData privateInfo)
        {
            object dynamicObject = DynamicTypeBuilderTest.CreateAnonymousDynamicInstance(privateInfo, this.dynamicType, classDiscriptionList);

            return dynamicObject;
        }

    }

I hope that this code snippet help somebody =) Enjoy!

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

How to set username and password for SmtpClient object in .NET?

Use NetworkCredential

Yep, just add these two lines to your code.

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;

:touch CSS pseudo-class or something similar?

Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color is the fastest to respond (subjective).

Add the following to your body and your links will have a tap effect.

body {
    -webkit-tap-highlight-color: #ccc;
}

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Web application context, specified by the WebApplicationContext interface, is a Spring application context for a web applications. It has all the properties of a regular Spring application context, given that the WebApplicationContext interface extends the ApplicationContext interface, and add a method for retrieving the standard Servlet API ServletContext for the web application.

In addition to the standard Spring bean scopes singleton and prototype, there are three additional scopes available in a web application context:

  • request - scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition
  • session - scopes a single bean definition to the lifecycle of an HTTP Session
  • application - scopes a single bean definition to the lifecycle of a ServletContext

How to Convert unsigned char* to std::string in C++?

If has access to CryptoPP

Readable Hex String to unsigned char

std::string& hexed = "C23412341324AB";
uint8_t      buffer[64] = {0};
StringSource ssk(hexed, true,
            new HexDecoder(new ArraySink(buffer,sizeof(buffer))));

And back

std::string hexed;
uint8_t val[32]  = {0};
StringSource ss(val, sizeof(val), true,new HexEncoder(new StringSink(hexed));
// val == buffer

Binary Search Tree - Java Implementation

According to Collections Framework Overview you have two balanced tree implementations:

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

You can use require with the path to the global module directory as an argument.

require('/path/to/global/node_modules/the_module');

On my mac, I use this:

require('/usr/local/lib/node_modules/the_module');

How to find where your global modules are? --> Where does npm install packages?

Where do I find the Instagram media ID of a image

If you add ?__a=1 at the end of Instagram public URLs, you get the data of the public URL in JSON.

For the media ID of an image from post URL, simply add the JSON request code at the post URL:

http://instagram.com/p/Y7GF-5vftL/?__a=1

The response will look like this below. You can easily recover the image ID from the "id" parameter in the reply...

{
"graphql": {
"shortcode_media": {
"__typename": "GraphImage",
"id": "448979387270691659",
"shortcode": "Y7GF-5vftL",
"dimensions": {
"height": 612,
"width": 612
},
"gating_info": null,
"fact_check_information": null,
"media_preview": null,
"display_url": "https://scontent-cdt1-1.cdninstagram.com/vp/6d4156d11e92ea1731377ef53324ce28/5E4D451A/t51.2885-15/e15/11324452_400723196800905_116356150_n.jpg?_nc_ht=scontent-cdt1-1.cdninstagram.com&_nc_cat=109",
"display_resources": [

Get int value from enum in C#

will give you the a list with all the integer values of the enum :

List enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

tensorflow 1.3 does not support cuda 9.0 yet. I degrade to cuda 8.0, then it works.

How do I create a link to add an entry to a calendar?

To add to squarecandy's google calendar contribution, here the brand new

OUTLOOK CALENDAR format (Without a need to create .ics) !!

<a href="https://bay02.calendar.live.com/calendar/calendar.aspx?rru=addevent&dtstart=20151119T140000Z&dtend=20151119T160000Z&summary=Summary+of+the+event&location=Location+of+the+event&description=example+text.&allday=false&uid=">add to Outlook calendar</a>

test it

Best would be to url_encode the summary, location and description variable's values.

For the sake of knowledge,

YAHOO CALENDAR format

<a href="https://calendar.yahoo.com/?v=60&view=d&type=20&title=Summary+of+the+event&st=20151119T090000&et=20151119T110000&desc=example+text.%0A%0AThis+is+the+text+entered+in+the+event+description+field.&in_loc=Location+of+the+event&uid=">add to Yahoo calendar</a>

test it

Doing it without a third party holds a lot of advantages for example using it in emails.

Place API key in Headers or URL

It is better to use API Key in header, not in URL.

URLs are saved in browser's history if it is tried from browser. It is very rare scenario. But problem comes when the backend server logs all URLs. It might expose the API key.

In two ways, you can use API Key in header

Basic Authorization:

Example from stripe:

curl https://api.stripe.com/v1/charges -u sk_test_BQokikJOvBiI2HlWgH4olfQ2:

curl uses the -u flag to pass basic auth credentials (adding a colon after your API key will prevent it from asking you for a password).

Custom Header

curl -H "X-API-KEY: 6fa741de1bdd1d91830ba" https://api.mydomain.com/v1/users

How to secure RESTful web services?

HTTP Basic + HTTPS is one common method.

Live video streaming using Java?

You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.

ASP.Net which user account running Web Service on IIS 7?

You have to find the right user that needs to use temp folder. In my computer I follow the above link and find the special folder c:\inetpub, that iis use to execute her web services. I check what users could use these folder and find something like these: computername\iis_isusrs

The main issue comes when you try to add it to all permit on temp folder I was going to properties, security tab, edit button, add user button then i put iis_isusrs

and "check names" button

It doesn´t find anything The reason is the in my case it looks ( windows 2008 r2 iis 7 ) on pdgs.local location You have to go to "Select Users or Groups" form, click on Advanced button, click on Locations button and will see a specific hierarchy

  • computername
  • Entire Directory
    • pdgs.local

So when you try to add an user, its search name on pdgs.local. You have to select computername and click ok, Click on "Find Now"

Look for IIS_IUSRS on Name(RDN) column, click ok. So we go back to "Select Users or Groups" form with new and right user underline

click ok, allow full control, and click ok again.

That´s all folks, Hope it helps,

Jose from Moralzarzal ( Madrid )

Questions every good Java/Java EE Developer should be able to answer?

  1. Explain the various access modifiers used in Java. I have had lots of people struggle with this, especially default access.
  2. If you could change one thing about the Java language or platform what would it be? Good developers will have an answer here while those who aren't really interested in development probably don't care.
  3. If their CV says something like they use EJB2.1 then ask about EJB3 to see what they know about it. The best developers will keep up with the latest developments even if they don't use the newer versions.

Flask ImportError: No Module Named Flask

Even i too suggest u virtualenv, This might also solve ur problem.

sudo apt install python-flask

If u want to deploy in productionserver then go ahead with above solution else use virtualenv.

How to trigger checkbox click event even if it's checked through Javascript code?

You can use the jQuery .trigger() method. See http://api.jquery.com/trigger/

E.g.:

$('#foo').trigger('click');

Best Way to Refresh Adapter/ListView on Android

You should use adapter.notifyDataSetChanged(). What does the logs says when you use that?

AngularJS: How to clear query parameters in the URL?

I can replace all query parameters with this single line: $location.search({});
Easy to understand and easy way to clear them out.

Git diff between current branch and master but not including unmerged master commits

As also noted by John Szakmeister and VasiliNovikov, the shortest command to get the full diff from master's perspective on your branch is:

git diff master...

This uses your local copy of master.

To compare a specific file use:

git diff master... filepath

Output example:

Example usage

Change Text Color of Selected Option in a Select Box

<html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>

How can I check if a value is of type Integer?

Here is the function for to check is String is Integer or not ?

public static boolean isStringInteger(String number ){
    try{
        Integer.parseInt(number);
    }catch(Exception e ){
        return false;
    }
    return true;
}

React: how to update state.item[1] in state using setState?

Use array map with arrow function, in one line

this.setState({
    items: this.state.items.map((item, index) =>
      index === 1 ? { ...item, name: 'newName' } : item,
   )
})

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

Laravel Eloquent limit and offset

Laravel 8 (This is worked for the version 7.16)

$art->products->skip($offset*$limit)->take($limit)->all();

https://laravel.com/docs/8.x/collections#method-take

Drawing rotated text on a HTML5 canvas

Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.

First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.

Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.

You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.

Why resize the canvas? I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display. For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);).

IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.

Hope this helps!

_x000D_
_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
_x000D_
_x000D_

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Mailjet

SMTP SETTINGS

Port: 25 or 587 (some providers block port 25)

I work by changing the port after deploying the app to the server.

  • In Debug it worked for me: $mail->Port = 25;
  • In Release it worked for me: $mail->Port = 587;

GL

How do I exclude Weekend days in a SQL Server query?

When dealing with day-of-week calculations, it's important to take account of the current DATEFIRST settings. This query will always correctly exclude weekend days, using @@DATEFIRST to account for any possible setting for the first day of the week.

SELECT *
FROM your_table
WHERE ((DATEPART(dw, date_created) + @@DATEFIRST) % 7) NOT IN (0, 1)

Get first date of current month in java

Joda Time

If I am understanding the question correctly, it can be done very easily by using joda time

LocalDate fromDate = new LocalDate().withDayOfMonth(1);
LocalDate toDate = new LocalDate().minusDays(1);

Does overflow:hidden applied to <body> work on iPhone Safari?

Simply change body height < 300px (height of mobile viewport on landspace is around 300px to 500px)

JS

$( '.offcanvas-toggle' ).on( 'click', function() {
    $( 'body' ).toggleClass( 'offcanvas-expanded' );
});

CSS

.offcanvas-expended { /* this is class added to body on click */
    height: 200px;
}
.offcanvas {
    height: 100%;
}

ORA-00054: resource busy and acquire with NOWAIT specified

Thanks for the info user 'user712934'

You can also look up the sql,username,machine,port information and get to the actual process which holds the connection

SELECT O.OBJECT_NAME, S.SID, S.SERIAL#, P.SPID, S.PROGRAM,S.USERNAME,
S.MACHINE,S.PORT , S.LOGON_TIME,SQ.SQL_FULLTEXT 
FROM V$LOCKED_OBJECT L, DBA_OBJECTS O, V$SESSION S, 
V$PROCESS P, V$SQL SQ 
WHERE L.OBJECT_ID = O.OBJECT_ID 
AND L.SESSION_ID = S.SID AND S.PADDR = P.ADDR 
AND S.SQL_ADDRESS = SQ.ADDRESS;

Detect click event inside iframe

I'm not sure, but you may be able to just use

$("#filecontainer #choose_pic").click(function() {
    // do something here
});

Either that or you could just add a <script> tag into the iframe (if you have access to the code inside), and then use window.parent.DoSomething() in the frame, with the code

function DoSomething() {
    // do something here
}

in the parent. If none of those work, try window.postMessage. Here is some info on that.

Should I use the Reply-To header when sending emails as a service to others?

You may want to consider placing the customer's name in the From header and your address in the Sender header:

From: Company A <[email protected]>
Sender: [email protected]

Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.

Signed versus Unsigned Integers

(in answer to the second question) By only using a sign bit (and not 2's complement), you can end up with -0. Not very pretty.

IE prompts to open or save json result from server

Is above javascript code the one you're using in your web application ? If so - i would like to point few errors in it: firstly - it has an additional '{' sign in definition of 'success' callback function secondly - it has no ')' sign after definition of ajax callback. Valid code should look like:

$.ajax({
        type:'POST',
        data: 'args',
        url: '@Url.Action("PostBack")',
        success: function (data, textStatus, jqXHR) {
                alert(data.message);
            }
    });

try using above code - it gave me 'Yay' alert on all 3 IE versions ( 7,8,9 ).

Center Div inside another (100% width) div

Just add margin: 0 auto; to the inside div.

Set Page Title using PHP

The problem is that $title is being referenced on line 5 before it's being assigned on line 58. Rearranging your code isn't easy, because the data is both retrieved and output at the same time. Just to test, how does something like this work?

Because you're only retrieving one row, you don't need to use a while loop, but I left it with hopes that it'll make it easier for you to relate to your current code. All I've done is removed the actual output from your data retrieval, and added variables for category and category name which are then referred to as usual later on. Also, I haven't tested this. :)

'dependencies.dependency.version' is missing error, but version is managed in parent

If anyone finds their way here with the same problem I was having, my problem was that I was missing the <dependencyManagement> tags around dependencies I had copied from the child pom.

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

JBoss debugging in Eclipse

You need to define a Remote Java Application in the Eclipse debug configurations:

Open the debug configurations (select project, then open from menu run/debug configurations) Select Remote Java Application in the left tree and press "New" button On the right panel select your web app project and enter 8787 in the port field. Here is a link to a detailed description of this process.

When you start the remote debug configuration Eclipse will attach to the JBoss process. If successful the debug view will show the JBoss threads. There is also a disconnect icon in the toolbar/menu to stop remote debugging.

Show history of a file?

The main question for me would be, what are you actually trying to find out? Are you trying to find out, when a certain set of changes was introduced in that file?

You can use git blame for this, it will anotate each line with a SHA1 and a date when it was changed. git blame can also tell you when a certain line was deleted or where it was moved if you are interested in that.

If you are trying to find out, when a certain bug was introduced, git bisect is a very powerfull tool. git bisect will do a binary search on your history. You can use git bisect start to start bisecting, then git bisect bad to mark a commit where the bug is present and git bisect good to mark a commit which does not have the bug. git will checkout a commit between the two and ask you if it is good or bad. You can usually find the faulty commit within a few steps.

Since I have used git, I hardly ever found the need to manually look through patch histories to find something, since most often git offers me a way to actually look for the information I need.

If you try to think less of how to do a certain workflow, but more in what information you need, you will probably many workflows which (in my opinion) are much more simple and faster.

How do I use WPF bindings with RelativeSource?

It's worthy of note that for those stumbling across this thinking of Silverlight:

Silverlight offers a reduced subset only, of these commands

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

Correct way to initialize HashMap and can HashMap hold different value types?

This is a change made with Java 1.5. What you list first is the old way, the second is the new way.

By using HashMap you can do things like:

HashMap<String, Doohickey> ourMap = new HashMap<String, Doohickey>();

....

Doohickey result = ourMap.get("bob");

If you didn't have the types on the map, you'd have to do this:

Doohickey result = (Doohickey) ourMap.get("bob");

It's really very useful. It helps you catch bugs and avoid writing all sorts of extra casts. It was one of my favorite features of 1.5 (and newer).

You can still put multiple things in the map, just specify it as Map, then you can put any object in (a String, another Map, and Integer, and three MyObjects if you are so inclined).

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

How to properly seed random number generator

OK why so complex!

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed( time.Now().UnixNano())
    var bytes int

    for i:= 0 ; i < 10 ; i++{ 
        bytes = rand.Intn(6)+1
        fmt.Println(bytes)
        }
    //fmt.Println(time.Now().UnixNano())
}

This is based off the dystroy's code but fitted for my needs.

It's die six (rands ints 1 =< i =< 6)

func randomInt (min int , max int  ) int {
    var bytes int
    bytes = min + rand.Intn(max)
    return int(bytes)
}

The function above is the exactly same thing.

I hope this information was of use.

how to call a onclick function in <a> tag?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.

Example:

function newwin() {              
 myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}

See how to call it from your anchor tag

<a onclick='newwin()'>Anchor</a>

Update

Visit this jsbin

http://jsbin.com/icUTUjI/1/edit

May be this will help you a lot to understand your problem.

How to merge a transparent png image with another image using PIL

from PIL import Image

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

First parameter to .paste() is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.

Check the docs.

Floating point inaccuracy examples

Show them that the base-10 system suffers from exactly the same problem.

Try to represent 1/3 as a decimal representation in base 10. You won't be able to do it exactly.

So if you write "0.3333", you will have a reasonably exact representation for many use cases.

But if you move that back to a fraction, you will get "3333/10000", which is not the same as "1/3".

Other fractions, such as 1/2 can easily be represented by a finite decimal representation in base-10: "0.5"

Now base-2 and base-10 suffer from essentially the same problem: both have some numbers that they can't represent exactly.

While base-10 has no problem representing 1/10 as "0.1" in base-2 you'd need an infinite representation starting with "0.000110011..".

Print JSON parsed object?

Just use

console.info("CONSOLE LOG : ")
console.log(response);
console.info("CONSOLE DIR : ")
console.dir(response);

and you will get this in chrome console :

CONSOLE LOG : 
facebookSDK_JS.html:56 Object {name: "Diego Matos", id: "10155988777540434"}
facebookSDK_JS.html:57 CONSOLE DIR : 
facebookSDK_JS.html:58 Objectid: "10155988777540434"name: "Diego Matos"__proto__: Object

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

change type of input field with jQuery

heres a DOM solution

myInput=document.getElementById("myinput");
oldHtml=myInput.outerHTML;
text=myInput.value;
newHtml=oldHtml.replace("password","text");
myInput.outerHTML=newHtml;
myInput=document.getElementById("myinput");
myInput.value=text;

How do I access refs of a child component in the parent component

I think this guide explains it pretty well https://github.com/yannickcr/eslint-plugin-react/issues/678

class Field extends Component {
  const { inputRef } = this.props;
  render() {
    return (
      <input type="text" ref={inputRef} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.focus();
  }

  render() {
    return (
      <div>
        Hello, <Field inputRef={node => this.inputNode = node} />
      </div>
    )
  }
}

How to Apply Mask to Image in OpenCV?

You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.

Groovy - How to compare the string?

The shortest way (will print "not same" because String comparison is case sensitive):

def compareString = {
   it == "india" ? "same" : "not same"
}    

compareString("India")

C - casting int to char and append char to char

int i = 100;
char c = (char)i;

There is no way to append one char to another. But you can create an array of chars and use it.

How to add additional fields to form before submit?

Try this:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

iOS 9 not opening Instagram app with URL SCHEME

Facebook sharing from a share dialog fails even with @Matthieu answer (which is 100% correct for the rest of social URLs). I had to add a set of URL i reversed from Facebook SDK.

<array>
        <string>fbapi</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
        <string>fb-messenger-api</string>
        <string>twitter</string>
        <string>whatsapp</string>
        <string>wechat</string>
        <string>line</string>
        <string>instagram</string>
        <string>kakaotalk</string>
        <string>mqq</string>
        <string>vk</string>
        <string>comgooglemaps</string>
        <string>fbapi20130214</string>                                                    
        <string>fbapi20130410</string>                                                     
        <string>fbapi20130702</string>                                                    
        <string>fbapi20131010</string>                                                    
        <string>fbapi20131219</string>                                                    
        <string>fbapi20140410</string>                                                     
        <string>fbapi20140116</string>                                                     
        <string>fbapi20150313</string>                                                     
        <string>fbapi20150629</string>
    </array>

SQL Sum Multiple rows into one

You should group by the field you want the SUM apply to, and not include in SELECT any field other than multiple rows values, like COUNT, SUM, AVE, etc, because if you include Bill field like in this case, only the first value in the set of rows will be displayed, being almost meaningless and confusing.

This will return the sum of bills per account number:

SELECT SUM(Bill) FROM Table1 GROUP BY AccountNumber

You could add more clauses like WHERE, ORDER BY etc as needed.

JSON to pandas DataFrame

#Use the small trick to make the data json interpret-able
#Since your data is not directly interpreted by json.loads()

>>> import json
>>> f=open("sampledata.txt","r+")
>>> data = f.read()
>>> for x in data.split("\n"):
...     strlist = "["+x+"]"
...     datalist=json.loads(strlist)
...     for y in datalist:
...             print(type(y))
...             print(y)
...
...
<type 'dict'>
{u'0': [[10.8, 36.0], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'1': [[10.8, 36.1], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'2': [[10.8, 36.2], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'3': [[10.8, 36.300000000000004], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'4': [[10.8, 36.4], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'5': [[10.8, 36.5], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'6': [[10.8, 36.6], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'7': [[10.8, 36.7], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'8': [[10.8, 36.800000000000004], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'9': [[10.8, 36.9], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}


How would you count occurrences of a string (actually a char) within a string?

**to count char or string **

 string st = "asdfasdfasdfsadfasdf/asdfasdfas/dfsdfsdafsdfsd/fsadfasdf/dff";
        int count = 0;
        int location = 0;
       
        while (st.IndexOf("/", location + 1) > 0)
        {
                count++;
                location = st.IndexOf("/", location + 1);
        }
        MessageBox.Show(count.ToString());

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

HTML5 required attribute seems not working

Absence of Submit field element in the form also causes this error. In the case of "button" field handled by JS to submit form lacks the necessity of Submit button hence Required doesn't Work

How can I access my localhost from my Android device?

Using a USB cable:

(for example, if you use WAMP server):

1) Install your Android drivers on your PC and download portable Android Tethering Reverse Tool and connect your Android device through the Reverse Tool application.

2) Click on WAMP icon > Put Online (after restarting).

3) Open your IP in the Android browser (i.e. http://192.168.1.22 OR http://164.92.124.42 )

To find your local IP address, click Start>Run>cmd and type ipconfig and your IP address will show up in the output.

That's all. Now you can access (open) localhost from Android.

Python speed testing - Time Difference - milliseconds

Here is a custom function that mimic's Matlab's/Octave's tic toc functions.

Example of use:

time_var = time_me(); # get a variable with the current timestamp

... run operation ...

time_me(time_var); # print the time difference (e.g. '5 seconds 821.12314 ms')

Function :

def time_me(*arg):
    if len(arg) != 0: 
        elapsedTime = time.time() - arg[0];
        #print(elapsedTime);
        hours = math.floor(elapsedTime / (60*60))
        elapsedTime = elapsedTime - hours * (60*60);
        minutes = math.floor(elapsedTime / 60)
        elapsedTime = elapsedTime - minutes * (60);
        seconds = math.floor(elapsedTime);
        elapsedTime = elapsedTime - seconds;
        ms = elapsedTime * 1000;
        if(hours != 0):
            print ("%d hours %d minutes %d seconds" % (hours, minutes, seconds)) 
        elif(minutes != 0):
            print ("%d minutes %d seconds" % (minutes, seconds))
        else :
            print ("%d seconds %f ms" % (seconds, ms))
    else:
        #print ('does not exist. here you go.');
        return time.time()

Marquee text in Android

For setting Marquee programatically

TextView textView = (TextView) this.findViewById(R.id.textview_marquee);  
textView.setEllipsize(TruncateAt.MARQUEE);
textView.setMarqueeRepeatLimit(-1);
textView.setText("General Information... general information... General Information");
textView.setSelected(true);
textView.setSingleLine(true);

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

General error: 1364 Field 'user_id' doesn't have a default value

Use database column nullble() in Laravel. You can choose the default value or nullable value in database.

Focusable EditText inside ListView

This saved my life--->

  1. set this line

    ListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

  2. Then in your manifest in activity tag type this-->

    <activity android:windowSoftInputMode="adjustPan">

Your usual intent

Send POST request with JSON data using Volley

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

refer

What does int argc, char *argv[] mean?

argv and argc are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments.

Try the following program:

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}

Running it with ./test a1 b2 c3 will output

Have 4 arguments:
./test
a1
b2
c3

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

How to install a previous exact version of a NPM package?

If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install [email protected]

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view <package> versions

And npm view can be used for viewing other things about a package too. https://docs.npmjs.com/cli/view

Build a basic Python iterator

Include the following code in your class code.

 def __iter__(self):
        for x in self.iterable:
            yield x

Make sure that you replace self.iterablewith the iterable which you iterate through.

Here's an example code

class someClass:
    def __init__(self,list):
        self.list = list
    def __iter__(self):
        for x in self.list:
            yield x


var = someClass([1,2,3,4,5])
for num in var: 
    print(num) 

Output

1
2
3
4
5

Note: Since strings are also iterable, they can also be used as an argument for the class

foo = someClass("Python")
for x in foo:
    print(x)

Output

P
y
t
h
o
n

Overriding the java equals() method - not working?

Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;

import lombok.EqualsAndHashCode;

@EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
public class ErrorMessage{

    private long        errorNumber;
    private int         numberOfParameters;
    private Level       loggingLevel;
    private String      messageCode;

See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.14.8</version>
    <scope>provided</scope>
</dependency>

PDO Prepared Inserts multiple rows in single query

You can insert multiple rows in a single query with this function:

function insertMultiple($query,$rows) {
    if (count($rows)>0) {
        $args = array_fill(0, count($rows[0]), '?');

        $params = array();
        foreach($rows as $row)
        {
            $values[] = "(".implode(',', $args).")";
            foreach($row as $value)
            {
                $params[] = $value;
            }
        }

        $query = $query." VALUES ".implode(',', $values);
        $stmt = $PDO->prepare($query);
        $stmt->execute($params);
    }
}

$row is an array of arrays of values. In your case you would call the function with

insertMultiple("INSERT INTO tbl (`key1`,`key2`)",array(array('r1v1','r1v2'),array('r2v1','r2v2')));

This has the benefit that you use prepared statements, while inserting multiple rows with a single query. Security!

Finding the max value of an attribute in an array of objects

// Here is very simple way to go:

// Your DataSet.

let numberArray = [
  {
    "x": "8/11/2009",
    "y": 0.026572007
  },
  {
    "x": "8/12/2009",
    "y": 0.025057454
  },
  {
    "x": "8/13/2009",
    "y": 0.024530916
  },
  {
    "x": "8/14/2009",
    "y": 0.031004457
  }
]

// 1. First create Array, containing all the value of Y
let result = numberArray.map((y) => y)
console.log(result) // >> [0.026572007,0.025057454,0.024530916,0.031004457]

// 2.
let maxValue = Math.max.apply(null, result)
console.log(maxValue) // >> 0.031004457

Android: Tabs at the BOTTOM

This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :

ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...

maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.

How to copy from CSV file to PostgreSQL table with headers in CSV file?

This worked. The first row had column names in it.

COPY wheat FROM 'wheat_crop_data.csv' DELIMITER ';' CSV HEADER

Excel Formula to SUMIF date falls in particular month

Try this instead:

  =SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))

It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.

Here's how the formula works.

  1. MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
    {1, 1, 1, 2, 2}.
  2. Then the comparison {1, 1, 1, 2, 2}= 1 produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}, which comprises the condition for the IF statement.
  3. The IF statement then returns an array of values, with {430, 96, 400.. for the values of the sum ranges where the month value equals 1 and ..0,0} where the month value does not equal 1.
  4. That array {430, 96, 400, 0, 0} is then summed to get the answer you are looking for.

This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.

It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)--also works.

Heads up: This does not work in Google Spreadsheets

Jquery - How to get the style display attribute "none / block"

//animated show/hide

function showHide(id) {
      var hidden= ("none" == $( "#".concat(id) ).css("display"));
      if(hidden){
          $( "#".concat(id) ).show(1000);
      }else{
          $("#".concat(id) ).hide(1000);
      }
  }

DLL References in Visual C++

You need to do a couple of things to use the library:

  1. Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2

  2. Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.

  3. You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.

After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)

Cheers!

EDIT

Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.

How to change file encoding in NetBeans?

This link answer your question: http://wiki.netbeans.org/FaqI18nProjectEncoding

You can change the sources encoding or runtime encoding.

Foreign keys in mongo?

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

Subtract two variables in Bash

You can use:

((count = FIRSTV - SECONDV))

to avoid invoking a separate process, as per the following transcript:

pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5

IE8 css selector

OK so, it isn't css hack, but out of frustration for not being able to find ways to target ie8 from css, and due to policy of not having ie specific css files, I had to do following, which I assume someone else might find useful:

if (jQuery.browser.version==8.0) {
   $(results).css({
         'left':'23px',
         'top':'-253px'
      });
}

fileReader.readAsBinaryString to upload files

The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.

If you specifically want to send it as multipart/form-data, you can use a FormData object:

var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data
xmlHttpRequest.send(formData);

You can also send the data directly, instead of using multipart/form-data. See the documentation. Of course, this will need a server-side change as well.

// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);

xmlHttpRequest.setRequestHeader("Content-Type", file.type);

// Send the binary data.
// Since a File is a Blob, we can send it directly.
xmlHttpRequest.send(file);

For browser support, see: http://caniuse.com/#feat=xhr2 (most browsers, including IE 10+).

Differences between Lodash and Underscore.js

Lodash is inspired by Underscore.js, but nowadays it is a superior solution. You can make your custom builds, have a higher performance, support AMD and have great extra features. Check this Lodash vs. Underscore.js benchmarks on jsperf and... this awesome post about Lodash:

One of the most useful feature when you work with collections, is the shorthand syntax:

var characters = [
  { 'name': 'barney', 'age': 36, 'blocked': false },
  { 'name': 'fred',   'age': 40, 'blocked': true }
];

// Using "_.filter" callback shorthand
_.filter(characters, { 'age': 36 });

// Using Underscore.js
_.filter(characters, function(character) { return character.age === 36; } );

// ? [{ 'name': 'barney', 'age': 36, 'blocked': false }]

(taken from Lodash documentation)

How to find third or n?? maximum salary from salary table?

Try this one...

SELECT MAX(salary) FROM employee WHERE salary NOT IN (SELECT * FROM employee ORDERBY salary DESC LIMIT n-1)

Warning: implode() [function.implode]: Invalid arguments passed

It happens when $ret hasn't been defined. The solution is simple. Right above $tags = get_tags();, add the following line:

$ret = array();

Removing character in list of strings

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]

msg = filter(lambda x : x != "8", lst)

print msg

EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

To make this (kinda work?) with how the intent of the question was we could perform something similar to this

msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
  • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

This would result in a data type that looks like this

msg = [["a", "a", "a", "a"], ["b", "b"]...]

So finally to wrap that up we would have to map it to bring them all back into the same type roughly

msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))

I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

How can I change the image displayed in a UIImageView programmatically?

If you have an IBOutlet to a UIImageView already, then all you have to do is grab an image and call setImage on the receiver (UIImageView). Two examples of grabbing an image are below. One from the Web, and one you add to your Resources folder in Xcode.

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];

or

UIImage *image = [UIImage imageNamed: @"cell.png"];

Once you have an Image you can then set UIImageView:

[imageView setImage:image];

The line above assumes imageView is your IBOutlet.

That's it! If you want to get fancy you can add the image to an UIView and then add transitions.

P.S. Memory management not included.

SQL Inner-join with 3 tables?

SELECT * 
FROM 
    PersonAddress a, 
    Person b,
    PersonAdmin c
WHERE a.addressid LIKE '97%' 
    AND b.lastname LIKE 'test%'
    AND b.genderid IS NOT NULL
    AND a.partyid = c.partyid 
    AND b.partyid = c.partyid;

Count number of occurences for each unique value

Perhaps table is what you are after?

dummyData = rep(c(1,2, 2, 2), 25)

table(dummyData)
# dummyData
#  1  2 
# 25 75

## or another presentation of the same data
as.data.frame(table(dummyData))
#    dummyData Freq
#  1         1   25
#  2         2   75

Bootstrap 4 responsive tables won't take up 100% width

None of these answers are working (date today 9th Dec 2018). The correct resolution here is to add .table-responsive-sm to your table:

<table class='table table-responsive-sm'>
[Your table]
</table>

This applies the responsiveness aspect only to the SM view (mobile). So in mobile view you get the scrolling as desired and in larger views the table is not responsive and thus displayed full width, as desired.

Docs: https://getbootstrap.com/docs/4.0/content/tables/#breakpoint-specific

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

ASP.net page without a code behind

There are two very different types of pages in SharePoint: Application Pages and Site Pages.

If you are going to use your page as an Application Page, you can safely use inline code or code behind in your page, as Application pages live on the file system.

If it's going to be a Site page, you can safely write inline code as long as you have it like that in the initial deployment. However if your site page is going to be customized at some point in the future, the inline code will no longer work because customized site pages live in the database and are executed in asp.net's "no compile" mode.

Bottom line is - you can write aspx pages with inline code. The only problem is with customized Site pages... which will no longer care for your inline code.

Pandas DataFrame to List of Lists

This is very simple:

import numpy as np

list_of_lists = np.array(df)

How can I exit from a javascript function?

I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..

function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
  return Browser.msgBox("something");
  }
}

This way you not only exit the function, but show a message saying why it stopped. Hope it helps.

Difficulty with ng-model, ng-repeat, and inputs

I just updated AngularJs to 1.1.2 and have no problem with it. I guess this bug was fixed.

http://ci.angularjs.org/job/angular.js-pete/57/artifact/build/angular.js

Reference an Element in a List of Tuples

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.

This is a quick rudimentary example that I came up with:

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

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6

How to detect if a string contains at least a number?

Use this:

SELECT * FROM Table WHERE Column LIKE '%[0-9]%'

MSDN - LIKE (Transact-SQL)

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Inserting values to SQLite table in Android

Seems odd to be inserting a value into an automatically incrementing field.

Also, have you tried the insert() method instead of execSQL?

ContentValues insertValues = new ContentValues();
insertValues.put("Description", "Electricity");
insertValues.put("Amount", 500);
insertValues.put("Trans", 1);
insertValues.put("EntryDate", "04/06/2011");
db.insert("CashData", null, insertValues);

A quick and easy way to join array elements with a separator (the opposite of split) in Java

You can use replace and replaceAll with regular expressions.

String[] strings = {"a", "b", "c"};

String result = Arrays.asList(strings).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ",");

Because Arrays.asList().toString() produces: "[a, b, c]", we do a replaceAll to remove the first and last brackets and then (optionally) you can change the ", " sequence for "," (your new separator).

A stripped version (fewer chars):

String[] strings = {"a", "b", "c"};

String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "").replace(", ", "," );

Regular expressions are very powerful, specially String methods "replaceFirst" and "replaceAll". Give them a try.

Bind a function to Twitter Bootstrap Modal Close

I've seen many answers regarding the bootstrap events such as hide.bs.modal which triggers when the modal closes.

There's a problem with those events: any popups in the modal (popovers, tooltips, etc) will trigger that event.

There is another way to catch the event when a modal closes.

$(document).on('hidden','#modal:not(.in)', function(){} );

Bootstrap uses the in class when the modal is open. It is very important to use the hidden event since the class in is still defined when the event hideis triggered.

This solution will not work in IE8 since IE8 does not support the Jquery :not() selector.

List of Timezone IDs for use with FindTimeZoneById() in C#?

Here's a full listing of a program and its results.

The code:

using System;

namespace TimeZoneIds
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
            {
                Console.WriteLine(z.Id);
            }
        }
    }
}

The TimeZoneId results on my Windows 7 workstation:

Dateline Standard Time

UTC-11

Samoa Standard Time

Hawaiian Standard Time

Alaskan Standard Time

Pacific Standard Time (Mexico)

Pacific Standard Time

US Mountain Standard Time

Mountain Standard Time (Mexico)

Mountain Standard Time

Central America Standard Time

Central Standard Time

Central Standard Time (Mexico)

Canada Central Standard Time

SA Pacific Standard Time

Eastern Standard Time

US Eastern Standard Time

Venezuela Standard Time

Paraguay Standard Time

Atlantic Standard Time

Central Brazilian Standard Time

SA Western Standard Time

Pacific SA Standard Time

Newfoundland Standard Time

E. South America Standard Time

Argentina Standard Time

SA Eastern Standard Time

Greenland Standard Time

Montevideo Standard Time

UTC-02

Mid-Atlantic Standard Time

Azores Standard Time

Cape Verde Standard Time

Morocco Standard Time

UTC

GMT Standard Time

Greenwich Standard Time

W. Europe Standard Time

Central Europe Standard Time

Romance Standard Time

Central European Standard Time

W. Central Africa Standard Time

Namibia Standard Time

Jordan Standard Time

GTB Standard Time

Middle East Standard Time

Egypt Standard Time

Syria Standard Time

South Africa Standard Time

FLE Standard Time

Israel Standard Time

E. Europe Standard Time

Arabic Standard Time

Arab Standard Time

Russian Standard Time

E. Africa Standard Time

Iran Standard Time

Arabian Standard Time

Azerbaijan Standard Time

Mauritius Standard Time

Georgian Standard Time

Caucasus Standard Time

Afghanistan Standard Time

Ekaterinburg Standard Time

Pakistan Standard Time

West Asia Standard Time

India Standard Time

Sri Lanka Standard Time

Nepal Standard Time

Central Asia Standard Time

Bangladesh Standard Time

N. Central Asia Standard Time

Myanmar Standard Time

SE Asia Standard Time

North Asia Standard Time

China Standard Time

North Asia East Standard Time

Singapore Standard Time

W. Australia Standard Time

Taipei Standard Time

Ulaanbaatar Standard Time

Tokyo Standard Time

Korea Standard Time

Yakutsk Standard Time

Cen. Australia Standard Time

AUS Central Standard Time

E. Australia Standard Time

AUS Eastern Standard Time

West Pacific Standard Time

Tasmania Standard Time

Vladivostok Standard Time

Central Pacific Standard Time

New Zealand Standard Time

UTC+12

Fiji Standard Time

Kamchatka Standard Time

Tonga Standard Time

Digital Certificate: How to import .cer file in to .truststore file using?

Instead of using sed to filter out the certificate, you can also pipe the openssl s_client output through openssl x509 -out certfile.txt, for example:

echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt

Xampp-mysql - "Table doesn't exist in engine" #1932

For me I removed whole data folder from xampp\mysql\ and pasted data folder of previous one here which solved my problem...

Node.js Hostname/IP doesn't match certificate's altnames

I had the same issue using the request module to proxy POST request from somewhere else and it was because I left the host property in the header (I was copying the header from the original request).

How to make connection to Postgres via Node.js

We can also use postgresql-easy. It is built on node-postgres and sqlutil. Note: pg_connection.js & your_handler.js are in the same folder. db.js is in the config folder placed.

pg_connection.js

const PgConnection = require('postgresql-easy');
const dbConfig = require('./config/db');
const pg = new PgConnection(dbConfig);
module.exports = pg;

./config/db.js

module.exports =  {
  database: 'your db',
  host: 'your host',
  port: 'your port',
  user: 'your user',
  password: 'your pwd',
}

your_handler.js

  const pg_conctn = require('./pg_connection');

  pg_conctn.getAll('your table')
    .then(res => {
         doResponseHandlingstuff();
      })
    .catch(e => {
         doErrorHandlingStuff()     
      })

how to change default python version?

Change the "default" Python by putting it ahead of the system Python on your path, for instance:

export PATH=/usr/local/bin:$PATH

Can I restore a single table from a full mysql mysqldump file?

sed -n -e '/-- Table structure for table `my_table_name`/,/UNLOCK TABLES/p' database_file.sql > table_file.sql

This is a better solution than some of the others above because not all SQL dumps contain a DROP TABLE statement. This one will work will all kinds of dumps.

How do I restart a program based on user input?

Here's a fun way to do it with a decorator:

def restartable(func):
    def wrapper(*args,**kwargs):
        answer = 'y'
        while answer == 'y':
            func(*args,**kwargs)
            while True:
                answer = raw_input('Restart?  y/n:')
                if answer in ('y','n'):
                    break
                else:
                    print "invalid answer"
    return wrapper

@restartable
def main():
    print "foo"

main()

Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y' and keep running the code until the answer isn't 'y'.

How to set Internet options for Android emulator?

Hi me also faced same issue , solved using below steps:

cause 1:

Add internet permission in your android application

cause 2:

Check the manually your default application is able access internet or not if not its problem of your emulator , check in your internet connection in your pc

try below method to connect net in your pc

try explicitly specifying DNS server settings, this worked for me.

In Eclipse:

Window>Preferences>Android>Launch

Default emulator options: -dns-server 8.8.8.8,8.8.4.4**

cause 3:

check : check if you are using more than one internet connection to your pc like one is LAN second one is Modem , so disable all lan or modem .

ERROR: Sonar server 'http://localhost:9000' can not be reached

For me the issue was that the maven sonar plugin was using proxy servers defined in the maven settings.xml. I was trying to access the sonarque on another (not localhost alias) and so it was trying to use the proxy server to access it. Just added my alias to nonProxyHosts in settings.xml and it is working now. I did not face this issue in maven sonar plugin 3.2, only after i upgraded it.

<proxy>
  <id>proxy_id</id>
  <active>true</active>
  <protocol>http</protocol>
  <host>your-proxy-host/host>
  <port>your-proxy-host</port>
  <nonProxyHosts>localhost|127.0.*|other-non-proxy-hosts</nonProxyHosts>
</proxy>enter code here

grant remote access of MySQL database from any IP address

  • START MYSQL using admin user
    • mysql -u admin-user -p (ENTER PASSWORD ON PROMPT)
  • Create a new user:
    • CREATE USER 'newuser'@'%' IDENTIFIED BY 'password'; (% -> anyhost)
  • Grant Privileges:
    • GRANT SELECT,DELETE,INSERT,UPDATE ON db_name.* TO 'newuser'@'%';
    • FLUSH PRIVILEGES;

If you are running EC2 instance don't forget to add the inbound rules in security group with MYSQL/Aurura.

How can building a heap be O(n) time complexity?

Basically, work is done only on non-leaf nodes while building a heap...and the work done is the amount of swapping down to satisfy heap condition...in other words (in worst case) the amount is proportional to the height of the node...all in all the complexity of the problem is proportional to the sum of heights of all the non-leaf nodes..which is (2^h+1 - 1)-h-1=n-h-1= O(n)

Sharing a variable between multiple different threads

Using static will not help your case.

Using synchronize locks a variable when it is in use by another thread.

You should use volatile keyword to keep the variable updated among all threads.

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.

Apply vs transform on a group object

you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.

from scipy.stats import zscore

columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],     
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)

standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)

results=df[outliersC | outliersD]
print(results)

   #Dataframe results
   A      B         C         D
   0  foo    one  0.162003  0.087469
   1  bar    one -1.156319 -1.526272
   2  foo    two  0.833892 -1.666304
   3  bar  three -2.026673 -0.322057
   4  foo    two  0.411452 -0.954371
   5  bar    two  0.765878 -0.095968
   6  foo    one -0.654890  0.678091
   7  foo  three -1.789842 -1.130922
 #C and D transformed Z score
           C         D
 0  0.398046  0.801292
 1 -0.300518 -1.398845
 2  1.121882 -1.251188
 3 -1.046514  0.519353
 4  0.666781 -0.417997
 5  1.347032  0.879491
 6 -0.482004  1.492511
 7 -1.704704 -0.624618

 #filtering using arbitrary ranges -1 and 1 for the z-score
      A      B         C         D
 1  bar    one -1.156319 -1.526272
 2  foo    two  0.833892 -1.666304
 5  bar    two  0.765878 -0.095968
 6  foo    one -0.654890  0.678091
 7  foo  three -1.789842 -1.130922


 >>>>>>>>>>>>> Part 2

 splitting = df.groupby('A')

 #look at how the data is grouped
 for group_name, group in splitting:
     print(group_name)

 def column_difference(gr):
      return gr['C']-gr['D']

 grouped=splitting.apply(column_difference)
 print(grouped)

 A     
 bar  1    0.369953
      3   -1.704616
      5    0.861846
 foo  0    0.074534
      2    2.500196
      4    1.365823
      6   -1.332981
      7   -0.658920

Entity framework code-first null foreign key

I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.

enter image description here

Guide link below:

https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN

How to dispatch a Redux action with a timeout?

The appropriate way to do this is using Redux Thunk which is a popular middleware for Redux, as per Redux Thunk documentation:

"Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters".

So basically it returns a function, and you can delay your dispatch or put it in a condition state.

So something like this is going to do the job for you:

import ReduxThunk from 'redux-thunk';

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {
  return {
    type: INCREMENT_COUNTER
  };
}

function incrementAsync() {
  return dispatch => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 5000);
  };
}

How to get nth jQuery element

If you want to fetch particular element/node or tag in loop for e.g.

<p class="weekday" data-today="monday">Monday</p>
<p class="weekday" data-today="tuesday">Tuesday</p>
<p class="weekday" data-today="wednesday">Wednesday</p>
<p class="weekday" data-today="thursday">Thursday</p>

So, from above code loop is executed and we want particular field to select for that we have to use jQuery selection that can select only expecting element from above loop so, code will be

$('.weekdays:eq(n)');

e.g.

$('.weekdays:eq(0)');

as well as by other method

$('.weekday').find('p').first('.weekdays').next()/last()/prev();

but first method is more efficient when HTML <tag> has unique class name.

NOTE:Second method is use when their is no class name in target element or node.

for more follow https://api.jquery.com/eq/

How to use UIScrollView in Storyboard

The key is the contentSize.

This is often missing and not indicated when adding a UIScrollView.

Select the UIScrollView and select the Identity Inspector.

Add a contentSize keyPath as a size to the scrollView in the Identity Inspector and setting it to (320, 1000).

Scroll away.

How can I declare dynamic String array in Java

What your looking for is the DefaultListModel - Dynamic String List Variable.

Here is a whole class that uses the DefaultListModel as though it were the TStringList of Delphi. The difference is that you can add Strings to the list without limitation and you have the same ability at getting a single entry by specifying the entry int.

FileName: StringList.java

package YOUR_PACKAGE_GOES_HERE;

//This is the StringList Class by i2programmer
//You may delete these comments
//This code is offered freely at no requirements
//You may alter the code as you wish
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

public class StringList {

    public static String OutputAsString(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static Object OutputAsObject(DefaultListModel list, int entry) {
        return GetEntry(list, entry);
    }

    public static int OutputAsInteger(DefaultListModel list, int entry) {
        return Integer.parseInt(list.getElementAt(entry).toString());
    }

    public static double OutputAsDouble(DefaultListModel list, int entry) {
        return Double.parseDouble(list.getElementAt(entry).toString());
    }

    public static byte OutputAsByte(DefaultListModel list, int entry) {
        return Byte.parseByte(list.getElementAt(entry).toString());
    }

    public static char OutputAsCharacter(DefaultListModel list, int entry) {
        return list.getElementAt(entry).toString().charAt(0);
    }

    public static String GetEntry(DefaultListModel list, int entry) {
        String result = "";
        result = list.getElementAt(entry).toString();
        return result;
    }

    public static void AddEntry(DefaultListModel list, String entry) {
        list.addElement(entry);
    }

    public static void RemoveEntry(DefaultListModel list, int entry) {
        list.removeElementAt(entry);
    }

    public static DefaultListModel StrToList(String input, String delimiter) {
        DefaultListModel dlmtemp = new DefaultListModel();
        input = input.trim();
        delimiter = delimiter.trim();
        while (input.toLowerCase().contains(delimiter.toLowerCase())) {
            int index = input.toLowerCase().indexOf(delimiter.toLowerCase());
            dlmtemp.addElement(input.substring(0, index).trim());
            input = input.substring(index + delimiter.length(), input.length()).trim();
        }
        return dlmtemp;
    }

    public static String ListToStr(DefaultListModel list, String delimiter) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result = list.getElementAt(i).toString() + delimiter;
        }
        result = result.trim();
        return result;
    }

    public static String LoadFile(String inputfile) throws IOException {
        int len;
        char[] chr = new char[4096];
        final StringBuffer buffer = new StringBuffer();
        final FileReader reader = new FileReader(new File(inputfile));
        try {
            while ((len = reader.read(chr)) > 0) {
                buffer.append(chr, 0, len);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static void SaveFile(String outputfile, String outputstring) {
        try {
            FileWriter f0 = new FileWriter(new File(outputfile));
            f0.write(outputstring);
            f0.flush();
            f0.close();
        } catch (IOException ex) {
            Logger.getLogger(StringList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

OutputAs methods are for outputting an entry as int, double, etc... so that you don't have to convert from string on the other side.

SaveFile & LoadFile are to save and load strings to and from files.

StrToList & ListToStr are to place delimiters between each entry.

ex. 1<>2<>3<>4<> if "<>" is the delimiter and 1 2 3 & 4 are the entries.

AddEntry & GetEntry are to add and get strings to and from the DefaultListModel.

RemoveEntry is to delete a string from the DefaultListModel.

You use the DefaultListModel instead of an array here like this:

DefaultListModel list = new DefaultListModel();
//now that you have a list, you can run it through the above class methods.

How to use activity indicator view on iPhone?

Using Storyboard-

Create-

  • Go to main.storyboard (This can be found in theProject Navigator on the left hand side of your Xcode) and drag and drop the "Activity Indicator View" from the Object Library.

Activity Indicator View from Object Library

  • Go to the header file and create an IBOutlet for the UIActivityIndicatorView-

     @interface ViewController : UIViewController
    
         @property (nonatomic,strong) IBOutlet UIActivityIndicatorView *activityIndicatorView;
    
     @end
    
  • Establish the connection from the Outlets to the UIActivityIndicatorView.

Start:

Use the following code when you need to start the activity indicator using following code in your implementation file(.m)-

 [self.activityIndicatorView startAnimating];

Stop:

Use the following code when you need to stop the activity indicator using following code in your implementation file(.m)-

 [self.activityIndicatorView stopAnimating];

How to remove the focus from a TextBox in WinForms?

I've found a good alternative! It works best for me, without setting the focus on something else.

Try that:

private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{    
    e.SuppressKeyPress = true;
}

How to make picturebox transparent?

Try using an ImageList

ImageList imgList = new ImageList;

imgList.TransparentColor = Color.White;

Load the image like this:

picturebox.Image = imgList.Images[img_index];

How to get HQ youtube thumbnails?

You need to get id from:

youtube.com/watch?v=VIDEO_ID

And put this in:

i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg

I hope that I helped :D

How to get `DOM Element` in Angular 2?

Use ViewChild with #localvariable as shown here,

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

In component,

OLDEST Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

ngAfterViewInit()
{
   this.el.nativeElement.focus();
}


OLD Way

import {ElementRef} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer) {}
ngAfterViewInit() {
    this.rd.invokeElementMethod(this.el.nativeElement,'focus');
}


Updated on 22/03(March)/2017

NEW Way

Please note from Angular v4.0.0-rc.3 (2017-03-10) few things have been changed. Since Angular team will deprecate invokeElementMethod, above code no longer can be used.

BREAKING CHANGES

since 4.0 rc.1:

rename RendererV2 to Renderer2
rename RendererTypeV2 to RendererType2
rename RendererFactoryV2 to RendererFactory2

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

console.log(this.rd) will give you following methods and you can see now invokeElementMethod is not there. Attaching img as yet it is not documented.

NOTE: You can use following methods of Rendere2 with/without ViewChild variable to do so many things.

enter image description here

Creating random numbers with no duplicates

The most easy way is use nano DateTime as long format. System.nanoTime();

Position a CSS background image x pixels from the right?

The most appropriate answer is the new four-value syntax for background-position, but until all browsers support it your best approach is a combination of earlier responses in the following order:

background: url(image.png) no-repeat 97% center; /* default, Android, Sf < 6 */
background-position: -webkit-calc(100% - 10px) center; /* Sf 6 */
background-position: right 10px center; /* Cr 25+, FF 13+, IE 9+, Op 10.5+ */

How do I create a message box with "Yes", "No" choices and a DialogResult?

if (MessageBox.Show("Please confirm before proceed" + "\n" + "Do you want to Continue ?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)

{
//do something if YES
}

else

{
//do something if NO
}

It will Prompt a message box like this.

How to create a readonly textbox in ASP.NET MVC3 Razor

You can use the below code for creating a TextBox as read-only.

Method 1

 @Html.TextBoxFor(model => model.Fields[i].TheField, new { @readonly = true })

Method 2

@Html.TextBoxFor(model => model.Fields[i].TheField, new { htmlAttributes = new {disabled = "disabled"}})

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.

SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)

That should be the simplest way to convert it to a time without doing anything to crazy.

In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:

SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)

How to change the style of a DatePicker in android?

Create a new style

<style name="my_dialog_theme" parent="ThemeOverlay.AppCompat.Dialog">
    <item name="colorAccent">@color/colorAccent</item>                   <!--header background-->
    <item name="android:windowBackground">@color/colorPrimary</item>     <!--calendar background-->
    <item name="android:colorControlActivated">@color/colorAccent</item> <!--selected day-->
    <item name="android:textColorPrimary">@color/colorPrimaryText</item> <!--days of the month-->
    <item name="android:textColorSecondary">@color/colorAccent</item>    <!--days of the week-->
</style>

Then initialize the dialog

Calendar mCalendar = new GregorianCalendar();
mCalendar.setTime(new Date());

new DatePickerDialog(mContext, R.style.my_dialog_theme, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //do something with the date
    }
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH)).show();

Result:

enter image description here

AJAX reload page with POST

By using jquery ajax you can reload your page

$.ajax({
    type: "POST",
    url: "packtypeAdd.php",
    data: infoPO,
    success: function() {   
        location.reload();  
    }
});

Non-static variable cannot be referenced from a static context

The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.

The lifecycle of a class, in broad terms, is:

  1. the source code for the class is written creating a template or pattern or stamp which can then be used to
  2. create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
  3. destroy the object reclaiming the resources it is holding such as memory during garbage collection.

In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.

The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.

So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.

However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.

import java.io.*;

class HelloWorld {
    int myInt;      // this is a class variable that is unique to each object
    static int myInt2;  // this is a class variable shared by all objects of this class

    static void main (String [] args) {
        // this is the main entry point for this Java application
        System.out.println ("Hello, World\n");
        myInt2 = 14;    // able to access the static int
        HelloWorld myWorld = new HelloWorld();
        myWorld.myInt = 32;   // able to access non-static through an object
    }
}

How to get text of an element in Selenium WebDriver, without including child element text?

Here's a general solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:

return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element) 

I'm actually using this code in a test suite.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Quickest, easiest laziest way to solve the problem:

  1. Right-click on the project icon in Solution Explorer and choose "Properties".
  2. Go to the "Application" tab and choose an earlier .NET target framework.
  3. Save changes.
  4. Go to the "Application" tab and choose the initial .NET target framework.
  5. Save changes => problem solved!

How can I prevent the backspace key from navigating back?

    document.onkeydown = function (e) {    
        e.stopPropagation();
        if ((e.keyCode==8  ||  e.keyCode==13) &&
            (e.target.tagName != "TEXTAREA") && 
            (e.target.tagName != "INPUT")) { 
            return false;
        }
    };

Detect when input has a 'readonly' attribute

Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/

if($('input').prop('readonly')){ }

.prop() can also be used to set the property

$('input').prop('readonly',true);

$('input').prop('readonly',false);

How do I make an auto increment integer field in Django?

In Django

1 : we have default field with name "id" which is auto increment.
2 : You can define a auto increment field using AutoField field.

class Order(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    #you use primary_key = True if you do not want to use default field "id" given by django to your model

db design

+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                  |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE `core_order` (
  `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`auto_increment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

If you want to use django's default id as increment field .

class Order(models.Model):
    dd_date = models.DateTimeField(auto_now_add=True)

db design

+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                                                                                    |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+
| core_order | CREATE TABLE `core_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dd_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

Defining private module functions in python

This question was not fully answered, since module privacy is not purely conventional, and since using import may or may not recognize module privacy, depending on how it is used.

If you define private names in a module, those names will be imported into any script that uses the syntax, 'import module_name'. Thus, assuming you had correctly defined in your example the module private, _num, in a.py, like so..

#a.py
_num=1

..you would be able to access it in b.py with the module name symbol:

#b.py
import a
...
foo = a._num # 1

To import only non-privates from a.py, you must use the from syntax:

#b.py
from a import *
...
foo = _num # throws NameError: name '_num' is not defined

For the sake of clarity, however, it is better to be explicit when importing names from modules, rather than importing them all with a '*':

#b.py
from a import name1 
from a import name2
...

HREF="" automatically adds to current page URL (in PHP). Can't figure it out

You can just put // in front of $yourUrl in href:

<a href="//<?=$yourUrl?>"></a>

Open file dialog box in JavaScript

Simple answer .

(1) Put input element type="file" anywhere on page and set attribute type="hidden" or style="display:none". Give an id to input element. e.g. id="myid"

(2) Chose any div, image, button or any element which you want to use to open file dialog box, set an onclick attribute to it, like this- onclick="document.getElementById('myid').click()"

That is all.

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

Mailto links do nothing in Chrome but work in Firefox?

I had the same problem. The problem, by some strange reason Chrome turned himself as the default tool to open a mailto: link. The solution, put your mail client as the default app to open it. How to : http://windows.microsoft.com/en-nz/windows/change-default-programs#1TC=windows-7

Good luck

Responsive iframe using Bootstrap

The best solution that worked great for me.

You have to: Copy this code to your main CSS file,

.responsive-video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 60px; overflow: hidden;
}

.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

and then put your embeded video to

<div class="responsive-video">
    <iframe ></iframe>
</div>

That’s it! Now you can use responsive videos on your site.

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Using reCAPTCHA on localhost

I was recently working on creating a website involving recaptcha v2 and I have a need to do test automation on my localhost. I did not add any ip or localhost into recaptcha admin portal.

Follow the below steps

  1. Log in to recaptcha admin site screenshot

  2. Locate Key Settings

  3. Click on advanced settings

  4. Under Domain Name Validation, un-check Verify the origin of reCAPTCHA solutions checkbox. This option is used to verifying requests come from one of the above listed domains.

    Please note that, If disabled, you are required to check the host-name on your server when verifying a solution.


I created a new key and disable this and use this key for testing in localhost.

This is a sample page which implements reCAPTCHA for comments.

Plotting using a CSV file

This should get you started:

set datafile separator ","
plot 'infile' using 0:1

counting number of directories in a specific directory

Best way to navigate to your drive and simply execute

ls -lR | grep ^d | wc -l

and to Find all folders in total, including subdirectories?

find /mount/point -type d | wc -l

...or find all folders in the root directory (not including subdirectories)?

find /mount/point -maxdepth 1 -type d | wc -l

Cheers!

How to add SHA-1 to android application

For linux Ubuntu Open Terminal and Write :-

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

How to log as much information as possible for a Java Exception?

Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter wraped in a BufeeredWriter. For the main static method, to catch the Uncaught Exceptions I do:

SwingUtilities.invokeLater( new Runnable() {
    @Override
    public void run() {
        //Initializations...
    }
});


Thread.setDefaultUncaughtExceptionHandler( 
    new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException( Thread t, Throwable ex ) {
            handleExceptions( ex, true );
        }
    }
);

And as for the method:

public static void handleExceptions( Throwable ex, boolean shutDown ) {
    JOptionPane.showMessageDialog( null,
        "A CRITICAL ERROR APPENED!\n",
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE );

    StringBuilder sb = new StringBuilder(ex.toString());
    for (StackTraceElement ste : ex.getStackTrace()) {
        sb.append("\n\tat ").append(ste);
    }


    while( (ex = ex.getCause()) != null ) {
        sb.append("\n");
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    }

    String trace = sb.toString();

    JOptionPane.showMessageDialog( null,
        "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE);

    if( shutDown ) {
        Runtime.getRuntime().exit( 0 );
    }
}

In you case, instead of "screaming" to the user, you could write a log like I told you before:

String trace = sb.toString();

File file = new File("mylog.txt");
FileWriter myFileWriter = null;
BufferedWriter myBufferedWriter = null;

try {
    //with FileWriter(File file, boolean append) you can writer to 
    //the end of the file
    myFileWriter = new FileWriter( file, true );
    myBufferedWriter = new BufferedWriter( myFileWriter );

    myBufferedWriter.write( trace );
}
catch ( IOException ex1 ) {
    //Do as you want. Do you want to use recursive to handle 
    //this exception? I don't advise that. Trust me...
}
finally {
    try {
        myBufferedWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }

    try {
        myFileWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }
}

I hope I have helped.

Have a nice day. :)

SQL: Alias Column Name for Use in CASE Statement

Not in MySQL. I tried it and I get the following error:

ERROR 1054 (42S22): Unknown column 'a' in 'field list'

updating table rows in postgres using subquery

There are many ways to update the rows.

When it comes to UPDATE the rows using subqueries, you can use any of these approaches.

  1. Approach-1 [Using direct table reference]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2>
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: table1 is the table which we want to update, table2 is the table, from which we'll get the value to be replaced/updated. We are using FROM clause, to fetch the table2's data. WHERE clause will help to set the proper data mapping.

  1. Approach-2 [Using SubQueries]
UPDATE
  <table1>
SET
  customer=subquery.customer,
  address=subquery.address,
  partn=subquery.partn
FROM
  (
    SELECT
      address_id, customer, address, partn
    FROM  /* big hairy SQL */ ...
  ) AS subquery
WHERE
  dummy.address_id=subquery.address_id;

Explanation: Here we are using subquerie inside the FROM clause, and giving an alias to it. So that it will act like the table.

  1. Approach-3 [Using multiple Joined tables]
UPDATE
  <table1>
SET
  customer=<table2>.customer,
  address=<table2>.address,
  partn=<table2>.partn
FROM
  <table2> as t2
  JOIN <table3> as t3
  ON
    t2.id = t3.id
WHERE
  <table1>.address_id=<table2>.address_i;

Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the FROM clause.

  1. Approach-4 [Using WITH statement]

    • 4.1 [Using simple query]
WITH subquery AS (
    SELECT
      address_id,
      customer,
      address,
      partn
    FROM
      <table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
  • 4.2 [Using query with complex JOIN]
WITH subquery AS (
    SELECT address_id, customer, address, partn
    FROM
      <table1> as t1
    JOIN
      <table2> as t2
    ON
      t1.id = t2.id;
    -- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
    address  = subquery.address,
    partn    = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;

Explanation: From Postgres 9.1, this(WITH) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.

I hope, this would be helpful.

Disable click outside of bootstrap modal area to close modal

The solution that work for me is the following:

$('#myModal').modal({backdrop: 'static', keyboard: false})  

backdrop: disabled the click outside event

keyboard: disabled the scape keyword event

How to retrieve JSON Data Array from ExtJS Store

Store.getRange() seems to be exactly what you are searching for. It will return you Ext.data.Record[] - array of records. If no arguments is passed, all the records are returned.