Q:

Calling CanadaPost from NetSuite Client

I'm trying to call the Canada Post API directly from the NetSuite client in order to get the shipping rates.
This is the test code for devlopment:
var url = 'https://ct.soa-gw.canadapost.ca/rs/ship/price';
var auth = 'Basic BASE64ENCODEDUSERNAMEANDPASSWORD';
var xml = '' +
'<?xml version="1.0" encoding="utf-8"?>' +
'<mailing-scenario xmlns="http://www.canadapost.ca/ws/ship/rate-v3">' +
'<customer-number>1234567</customer-number>' +
'<parcel-characteristics><weight>1.0</weight></parcel-characteristics>' +
'<services><service-code>DOM.XP</service-code></services>' +
'<origin-postal-code>K2B8J6</origin-postal-code>' +
'<destination><domestic><postal-code>J0E1X0</postal-code></domestic></destination>' +
'</mailing-scenario>';

var header = {
    'Authorization': auth,
    'Content-Type': 'application/soap+xml;application/vnd.cpc.ship.rate-v3+xml',
    'Accept-language': 'en-CA',
    'Accept': 'application/vnd.cpc.ship.rate-v3+xml'
};

var r = nlapiRequestURL(url, xml, header, null, 'POST');

console.log(r.code[0]);
console.log(r.body);

The instructions are pretty clear and the XML format seems to be right, but I keep getting the same response:
<?xml version="1.0" encoding="UTF-8"?>
<messages xmlns="http://www.canadapost.ca/ws/messages">
<message>
400
<description>Backend Bad Request</description></message></messages>

Any clue?
Reference:
https://www.canadapost.ca/cpo/mc/business/productsservices/developers/services/rating/getrates/default.jsf
*Edit: I've tried using also  'Content-Type': 'application/vnd.cpc.ship.rate-v3+xml' and I get the following error:
<?xml version="1.0" encoding="UTF-8"?>
<messages xmlns="http://www.canadapost.ca/ws/messages">
<message>
415
<description>Backend Unsupported Media Type</description></message></messages>

A:

The first issue is your Content-Type header is wrong. You can't actually mix content types like that. The CP website indicates it wants
Content-Type: "application/vnd.cpc.ship.rate-v3+xml"

Your problem is going to be that NS explicitly states that they will only respect certain content-type values:

Also note that if you call nlapiRequestURL, passing in the header with a content type, NetSuite respects the following types:

  all text media types (types starting with "text/")
  "application/json"
  "application/vnd.maxmind.com-country+json"
  "application/xml"
  "application/soap+xml"
  "application/xhtml+xml"
  "application/atom+xml"
  Otherwise, NetSuite will overwrite the content type with our default type as if the type had not been specified. NetSuite default types are:

  "text/xml; charset=UTF-8"
  "application/x-www-form-urlencoded; charset=UTF-8"

What I would do would be to test whether CP lets you get away with Content-Type : "text/xml" or "application/xml"
If not I'd file a case with both CP and NS in hopes that either CP would allow the more generic type or NS would allow a specific type. Don't hold your breath.
what I have actually done to solve this sort of thing is to just proxy the request through a system that I have control of. It's pretty easy to write a small app that will receive the request; reset the headers properly and forward the request.


Q:

Selecting each td by attribute name, then gives 'undefined' for the attribute value

I have a table with a td in it like so:
0

Using jQuery, the following JavaScript
$('td[age]').each(function(){
    console.log($('this').attr('age'));
});

prints 'undefined' to the console in Chrome.
Why is it not printing "123"?

A:

Where you have
$('this')

You should instead have
$(this)


Q:

Entity Framework lazy loaded collection sometimes null

I have 2 models, one of which has a child collection of the other:
[Table("ParentTable")]
public class Parent
{
    [Key, Column("Parent")]
    public string Id { get; set; }

    [Column("ParentName")]
    public string Name { get; set; }

    public virtual ICollection<Widget> Widgets { get; set; }
}

[Table("WidgetTable")]
public class Widget
{
    public string Year { get; set; }

    [Column("Parent")]
    public string ParentId { get; set; }

    public string Comments { get; set; }

    [Key, Column("ID_Widget")]
    public int Id { get; set; }

    [ForeignKey("ParentId"), JsonIgnore]
    public virtual Parent Parent { get; set; }
}

This code works for > 99% of widgets:
var parent = _dbContext.Parents.FirstOrDefault(p => p.Id == parentId);

Usually, parent.Widgets is a collection with more than one item. In a couple of instances, however, parent.Widgets is null (not a collection with no items).
I have used Query Analyzer to trace both the query for the parent and the query for widgets belonging to that parent. Both return exactly the rows I expect; however, the model for one or two parent IDs results in a null value for the Widgets collection. What could cause a lazy-loaded collection to be null in some instances but not others?

A:

This situation commonly comes up when a dbContext lifetime is left open across an Add, saveChanges, and then retrieval.
For example:
var context = new MyDbContext(); // holding Parents.
var testParent = new Parent{Id = "Parent1", Name = "Parent 1"};
context.Parents.Add(testParent);

At this point if you were to do:
var result = context.Parents.FirstOrDefault(x=> x.ParentId == "Parent1");

you wouldn't get a parent. Selection comes from committed state.. So...
context.SaveChanges();
var result = context.Parents.FirstOrDefault(x=> x.ParentId == "Parent1");

This will return you a reference to the parent you had inserted since the context knows about this entity and has a reference to the object you created. It doesn't go to data state. Since your definition for Widgets was just defined with a get/set auto-property the Widgets collection in this case will be #null.
if you do this:
context.Dispose();
context = new MyDbContext();
var result = context.Parents.FirstOrDefault(x=> x.ParentId == "Parent1");

In this case the parent is not known by the new context so it goes to data state. EF will return you a proxy list for lazy loading the Widgets, which there are none so you get back an empty list, not #null.
When dealing with collection classes in EF it's best to avoid auto-properties or initialize them in your constructor to avoid this behaviour; you'll typically want to assign Widgets after creating a Parent. Initializing a default member is better because you don't want to encourage ever using a setter on the collection property.
For example:
private readonly List<Widget> _widgets = new List<Widget>();
public virtual ICollection<Widget> Widgets
{
  get { return _widgets; }
  protected set { throw new InvalidOperationException("Do not set the Widget collection. Use Clear() and Add()"); }
}

Avoid performing a Set operation on a collection property as this will screw up in entity reference scenarios. For instance, if you wanted to sort your Widget collection by year and did something like:
parent.Widgets = parent.Widgets.OrderBy(x=> x.Year).ToList();

Seems innocent enough, but when the Widgets reference was an EF proxy, you've just blown it away. EF now cannot perform change tracking on the collection.
Initialize your collection and you should avoid surprises with #null collection references. Also I would look at the lifetime of your dbContext. It's good to keep one initialized over the lifetime of a request or particular operation, but avoid keeping them alive longer than necessary. Context change tracking and such consume resources and you can find seemingly intermittent odd behaviour like this when they cross operations.


Q:

How to add object in the static list on the constructor

#include <forward_list>

using namespace std;

class Test {
public:
    Test(){objects.push_front(this);}
private:
    static forward_list<Test*>objects;
};

int main(){
    Test a;
}//Visual Studio 17, error

Visual studio doesn't say what the problem is. It just retruns these two codes - LNK1120 and LNK2001.

A:

You have an undefined reference to static forward_list<Test*>objects; You have to define your static object like this:
#include <forward_list>

using namespace std;

class Test {
public:
    Test(){objects.push_front(this);}
private:
    static forward_list<Test*>objects;
};

forward_list<Test*> Test::objects;

int main(){
    Test a;
}//Visual Studio 17, error


Q:

Rails - render partial collection as not working

I am trying to render a partial of a collection using a name different to that of the model:
<%= render "current_campaigns", collection: @current_campaigns, as: :current_campaign %>

The model is called Campaign but this is a subset of campaigns as defined in the controller action:
def index
  @current_campaigns = Campaign.where(status: :approved)
end

In the partial (which lives in the application directory not the campaigns directory):
<%= current_campaign.question %>

The resulting error:
undefined local variable or method `current_campaign' for #<#<Class:0x007fad3d5e5500>:0x007fad451976a8>

I was under the impression that as would make this work but apparently not. Any thoughts?

A:

Try the following

<%= render partial: 'path-relative-to-views/current_campaigns', collection: @current_campaigns, as: :current_campaign %>

And the partial should name _current_campaign.html.erb for convention.


Q:

Bad padding on my subnav

I cannot figure out why the padding on my drop down sub nav under products is incorrect. PLEASE HELP! Here is the test site... http://test.wimsattdirect.com/test2/navigation3.html#
Here is the code:
HTML:

HOME

PRODUCTS

drop1

drop2

drop 3

SERVICES

LOCATIONS

NEWS/EVENTS

CAREERS

PROS

OUR STORY

css:
 .slidenav {
    position: fixed;
    top: 0;
    right: 5px;
}

.slidenav li {
    float: left;
    display: inline-block;
    overflow:hidden;
}
.slidenav li a {
    color: #3A3D3F;
    padding-top: 26px;
    padding-left: 11px;
    display: block;
    overflow: hidden;
    padding-right: 9px;

}

.subnav { width: 120px;
margin: 0;
height: 50px;}

.slidenav li ul {-webkit-transition: all 0.2s;
  -moz-transition: all 0.2s;
  -ms-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
  }

.slidenav li a:hover {color: #000;}

.slidenav ul li subnav ul {
    padding: 0;
    position: relative;
    left: 0;
    display: none;
    opacity: 0;
    visibility: hidden;
    overflow: hidden;
    -webkit-transition: height 200ms ease-in;
    -moz-transition: height 200ms ease-in;
    -o-transition: height 200ms ease-in;
    transition: height 200ms ease-in;
}

.slidenav ul li ul.subnav a {
    display: none;
    overflow:hidden;
}

.slidenav ul li:hover ul.subnav a {
    display: block;
    overflow:hidden;
        }
.slidenav ul li:hover ul.subnav li {
    width: 100%;
    overflow: hidden;
    background-color: #C2C2C2;
     }

.nav ul {
    *zoom:1;
    list-style:none;
    margin:0;
    padding:0;

}
.nav ul:before,.nav ul:after {
    content:"";
    display:table;
}
.nav ul:after {
    clear:both;
}
.nav ul > li {
    float:left;
    position:relative;
}
.nav a {
    display: block;
    padding-right: 20px;
    padding-bottom: 10px;
    line-height: 0px;

}

.nav a:hover {
    text-decoration:none;
    background:#595959;
}

.nav li ul li {
    width:200px;
    height:0;
    -webkit-transition:height 200ms ease-in;
    -moz-transition:height 200ms ease-in;
    -o-transition:height 200ms ease-in;
    transition:height 200ms ease-in;
}
.nav li ul a {
    border:none;
}
.nav li ul a:hover {
    background:rgba(0,0,0,0.2);
}

.nav li ul {
    position:relative;
    left:10;
    margin: 0;
    z-index:0;

}

.nav ul > li:hover ul li {
    height:76px;

}

A:

Change line-height: 0px; to line-height: normal;(style.min.css line 32)
.nav a {
    display: block;
    padding-right: 20px;
    padding-bottom: 10px;
    line-height: normal;
}

.slidenav ul li ul.subnav a
{
   overflow: hidden;
   display: block;
   padding: 10px;
}


Q:

How to find the child nodes of an node of an infragistics web navigator?

I need to find all the child nodes of a particular node in Infragistics tree view(WebNavigator). it is possible to get the parent() using the available property. But I need the childs. How can i access the childs of that particular node. I am using asp.net 2.0 with VB.Net. Thanks

A:

Assuming that you have a reference to the Node that you want to get the children.  On the server you can access them from the Nodes collection that is exposed by the Node.
If you are looking to do this in JavaScript then you can use the getChildNodes method.


Q:

arrays of integers

I have an array:
$age = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31");

and in my html I'm getting the values in the array to be a in dropdown list:
   foreach($age as $val)
    {echo '<option value="'.$val.'">'.$val.'</option>'; }?>

was wondering how can I generate an array of range of numbers so I can easily change it in the future instead of manual keying all the numbers?
can I do something like this?
    $minNum = 18;
    $maxNum = 80;
    $age = [];
    while($minNum <= $maxNum){
    $age.push($minNum++);
    }

when I do the above I got undefined push function error

A:

In PHP, arrays don't have any functions. You would use array_push.
However, PHP has a built-in for this: range
$age = range(18, 80);


Q:

How to create re-usable blocks in CloudFormation

Scenario:
I have a serverless/cloudformation script that re-deploys the same code with different configurations to AWS as lambdas and exposes each lambda via API Gateway.
So far the only way I've been able to do this is via copious amounts of copy and paste within the same script.. but its starting to drive me up the walls... thus, as I'm a complete newby to AWS and, navigating the AWS docs and internet has yielded pretty bad results, in answering this... I'm trying my luck here.
Within a cloudformation script:
"Resources":{
   "LambdaResourceNG":{
      "Type":"AWS::Serverless::Function",
      "Properties":{
         "Handler":"some-handlername::foo::bar",
         "Runtime":"dotnetcore2.0",
         "Environment":{
            "Variables":{
               "PictureOptions__OriginalPictureSuffix":{
                  "Fn::Join":[
                     "",
                     [
                        "_",
                        "ng",
                        "_",
                        {
                           "Fn::FindInMap":[
                              "Environments",
                              {
                                 "Ref":"EnvironmentValue"
                              },
                              "PictureOptionsOriginalPictureSuffix"
                           ]
                        }
                     ]
                  ]
               },

            },
            "Events":{
               "Bar":{
                  "Type":"Api",
                  "Properties":{
                     "Path":"/ng/bar",
                     "Method":"POST"
                  }
               },
               "Foo":{
                  "Type":"Api",
                  "Properties":{
                     "Path":"/ng/foo",
                     "Method":"POST"
                  }
               }
            }
         }
      },
   }

Question:
In the script block above.. The resource is called LambdaResourceNG. If I wanted to have another resource...LambdaResourceKE... with all appropriate sections changed to KE. How would I make a "function" that I could re-use within this erm... language?
I've already found out how to use maps to swap out variables based on some env value... but how would one go about creating reusable blocks of code/config?

A:

If the existing CloudFormation nested stacks feature doesn't suffice and you need real programmability then the final CF template can be the output of a higher-level process.
There are tools available to create templates e.g. AWS Cloud Development Kit, Troposphere and cfndsl.
Another option would be to drive the creation of the final template from a CLI. It doesn't have to be particularly sophisticated, just something that includes a template engine (like jinja2 or handlebars). Then you can program the inclusion of reusable template fragments, dynamically inject values into those fragments, iterate over loops as necessary, and emit a final CloudFormation template (or a main template and set of nested templates).


Q:

Exclude match results (pcre regex)

So I've this regex (from https://github.com/savetheinternet/Tinyboard/blob/master/inc/functions.php#L1620)
((?:https?:\/\/|ftp:\/\/|irc:\/\/)[^\s<>()"]+?(?:\([^\s<>()"]*?\)[^\s<>()"]*?)*)((?:\s|<|>|"|\.|\]|!|\?|,|,|")*(?:[\s<>()"]|$))

it works for matching links like: http://stackoverflow.com/ etc..
question is, how I can exclude these kind of markup matches (mainly the url ja img parts):
[url]http://stackoverflow.com/[/url]
[url=http://stackoverflow.com/]http://stackoverflow.com/[/url]
[img]http://cdn.sstatic.net/stackoverflow/img/sprites.png[/img]
[img=http://cdn.sstatic.net/stackoverflow/img/sprites.png]

A:

To exclude this you can add at the begining of your expression this subpattern:
(?:\[(url|img)](?>[^[]++|[(?!\/\g{-1}))*+\[\/\g{-1}]|\[(?:url|img)=[^]]*+])(*SKIP)(*FAIL)|your pattern here

The goal of this is to try to match the parts you don't want before and forces the regex engine to fail with the backtracking control verb (*FAIL). The (*SKIP) verb forces the regex engine to not retry the substring matched before when the subpattern fails after.
You can find more informations about these features here.
Notice: assuming that you are using PHP for this pattern, you can improve a little bit this very long pattern by replacing the default delimiter / by ~ to avoid to escape all / in the pattern and by using the verbose mode (x modifier) with a Nowdoc syntax. Like this you can comment it, make it more readable and easily improve the pattern
Example:
$pattern = <<<'EOF'
~
### skipping url and img bbcodes ###
(?:
    \[(url|img)]              # opening bbcode tag
    (?>[^[]++|[(?!/\g{-1}))*+ # possible content between tags
    \[/\g{-1}]                # closing bbcode tag
  |
    \[(?:url|img)= [^]]*+ ]   # self closing bbcode tags
)(*SKIP)(*FAIL)            # forces to fail and skip

| # OR

### a link ###
(
    (?:https?|ftp|irc)://      # protocol
    [^\s<>()"]+?
    (?:
        \( [^\s<>()"]*? \)     # part between parenthesis
        [^\s<>()"]*?
    )*
)
(
    (?:[]\s<>".!?,]|,|")*
    (?:[\s<>()"]|$)
)
~x
EOF;


Q:

Binding an interface with Guice to a Proxy that implements it

I have an interface class reference and an object I created using a dynamic proxy that implements the interface above.

final Class<?> interfaceType;
final Object interfaceImplementation = Proxy.newProxyInstance(...)`

I want to make the proxy instance available in the Guice application context by binding the interface to the proxy object. I tried but failed to quickly achieve this with Guice.
Is it possible to do something like:

bind(interfaceType).toInstance(interfaceImplementation);

so that I can inject the interface into other classes?

A:

The problem is that the return type of Proxy.newProxyInstance() is just Object, but bind(...).toInstance(...) wants to ensure that the type is the same as the ? from Class<?> interfaceType.  At some point, you're going to need to do an unchecked cast to get everything working.  Here's how I'd write it:
private <T> T newProxyInstance(ClassLoader loader, InvocationHandler handler, Class<T> primaryInterface, Class<?>... extraInterfaces) {
    Class<?>[] allInterfaces = Lists.asList(primaryInterface, extraInterfaces)
            .stream()
            .toArray(Class<?>[]::new);
    @SuppressWarning("unchecked")
    T proxy = (T) Proxy.newProxyInstance(loader, allInterfaces, handler);
    return proxy;
}

then I think
bind(interfaceType)
        .toInstance(newProxyInstance(loader, handler, interfaceType[, ...]));

would work.


Q:

How to code for flashPlayer 10.2 inside of flash

I am wanting to try some of the new features of Flash Player 10.2 in flash.When I go to import some of the new classes they do not work.
How can I set Flash up to use the new features of the current SDK?

A:

You can, if you compile using the Flex SDK from the Flash IDE. You just need to make sure to get an SDK that compiles toward 10.2; probably the Hero builds.
However, the Flash IDE is notoriously bad for coding. I'd recommend always using something external.


Q:

Create new column for in multiindex dataframe and fillna

Let's say I have the following multi-indexed dataframe, generated with the following code:
import pandas as pd, numpy as np

names = ['Name1','Name2','Name3','Name4']
values = ['x1','x2','x3','x4']
categories = ['y1','y2','y3']

x1 = pd.Series([0, 0, 0], index=categories)

index = pd.MultiIndex.from_product([names, values]); placeholders = np.zeros((len(names)*len(values), len(categories)))

df = pd.DataFrame(placeholders, index=index, columns=categories)

for i in names:
    for j in values:
        df.loc[i,j] = x1

           y1   y2   y3
Name1 x1  0.0  0.0  0.0
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0
Name2 x1  0.0  0.0  0.0
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0
Name3 x1  0.0  0.0  0.0
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0
Name4 x1  0.0  0.0  0.0
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0

How would I use a dictionary such as the following to fill the column y3 corresponding to row x1 and filling np.nan for values for any other rows in the y3 column or when a given Name (i.e. Name1, Name2, Name3, etc.) is not a key in the dictionary?
{'Name1': 54, 'Name3': 50}

Expected output (0's could be np.nan):
           y1   y2   y3
Name1 x1  0.0  0.0   54
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0
Name2 x1  0.0  0.0  0.0
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0
Name3 x1  0.0  0.0   50
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0
Name4 x1  0.0  0.0  0.0
      x2  0.0  0.0  0.0
      x3  0.0  0.0  0.0
      x4  0.0  0.0  0.0

A:

The idiomatic way is probably to use update
In [31]: df2 = pd.DataFrame({(k,'x1'): {'y3': v} for k, v in d.items()}).T

In [32]: df2
Out[32]:
          y3
Name1 x1  54
Name3 x1  50

In [33]: df.update(df2)

In [34]: df
Out[34]:
           y1   y2    y3
Name1 x1  0.0  0.0  54.0
      x2  0.0  0.0   0.0
      x3  0.0  0.0   0.0
      x4  0.0  0.0   0.0
Name2 x1  0.0  0.0   0.0
      x2  0.0  0.0   0.0
      x3  0.0  0.0   0.0
      x4  0.0  0.0   0.0
Name3 x1  0.0  0.0  50.0
      x2  0.0  0.0   0.0
      x3  0.0  0.0   0.0
      x4  0.0  0.0   0.0
Name4 x1  0.0  0.0   0.0
      x2  0.0  0.0   0.0
      x3  0.0  0.0   0.0
      x4  0.0  0.0   0.0


Q:

Bootstrap checkbox and radio input with font-awesome

Can anyone give me a solution to this problem on IE8. I have this:
HTML:
 <label>
        <input type="checkbox" checked /><i class="icon-fixed-width icon-check"></i> Three
    </label>

CSS:
[type=checkbox] { display: none; }
label { cursor: pointer; }
[class*=icon-].icon-fixed-width { text-align: left; }

jQuery:
$("[type=checkbox]").change(function () {
    $checkbox = $(this)
    $icon = $checkbox.siblings("[class*=icon-]")

    checked = $checkbox.is(":checked")

    $icon.toggleClass('icon-check', checked)
        .toggleClass('icon-check-empty', !checked)
});

All work fine on modern browsers but on IE8 wont work.
What is wrong here?
Fiddle:
ty.

A:

Just add a semicolon after each Javascript line. I think the IE8 Javascript engine "crashes" when you do not end your Javascript statement with ;
$("[type=checkbox]").change(function () {
    $checkbox = $(this);
    $icon = $checkbox.siblings("[class*=icon-]");
    checked = $checkbox.is(":checked");
    $icon.toggleClass('icon-check', checked).toggleClass('icon-check-empty', !checked);
});

Fiddle


Q:

Singularly cast an array of strings to custom enum type in WHERE clause

I am trying to cast a list of strings to a list of custom enum types. The effect I am looking for can be achieved with this:
select * from table_1 where column_a in (cast('ENUM1' AS custom_enum), cast('ENUM2' AS custom_enum))

But since I am attempting this to bypass some JPA/hibernate issues I am having with annotated filters on sql enum types, I need to dynamically add the enum strings to the list. So I am trying to figure out how to cast a whole list of strings to a list of enum_types. I'm guessing something like this:
select * from table_1 where column_a in (cast({'ENUM1', 'ENUM2'} AS custom_enum[]))

But not much I have tried gives me any luck.

A:

Use = ANY instead of IN. The array literal should be enclosed in quotes:
select *
from table_1
where column_a = any (cast('{ENUM1, ENUM2}' as custom_enum[]))

or cast the column to text:
select *
from table_1
where column_a::text in ('ENUM1', 'ENUM2')


Q:

Store date values in Google Datastore

I'm trying to store a date value in Google Datastore using the Google API PHP Client but the service replies always with an error:
Invalid value for: Invalid format: "2014-08-18 12:40:52" is malformed at " 12:40:52".
Here's the interesting section of the code I use:

function create_entity($name, $property, $data) {
    $entity = new Google_Service_Datastore_Entity();
    $entity->setKey(createKey($name));

    $string_prop = new Google_Service_Datastore_Property();
    $string_prop->setStringValue($data);
    $string_prop->setIndexed(false);

    $time = date("Y-m-d H:i:s");

    $string_date = new Google_Service_Datastore_Property();
    $string_date->setDateTimeValue($time);
    $string_date->setIndexed(false);

    $property_map = [];
    $property_map[$property] = $string_prop;
    $property_map['date'] = $string_date;

    $entity->setProperties($property_map);

    return $entity;
}

function create_commit($name, $property, $data) {
    $entity = create_entity($name, $property, $data);

    $mutation = new Google_Service_Datastore_Mutation();
    $mutation->setUpsert([$entity]);

    $req = new Google_Service_Datastore_CommitRequest();
    $req->setMode('NON_TRANSACTIONAL');
    $req->setMutation($mutation);
    return $req;
}

A:

According to the Cloud Datastore docs, the dateTimeValue property must be a string that is RFC 3339 formatted):

dateTimeValue: string (RFC 3339 formatted, with milliseconds, for instance 2013-05-14T00:01:00.234Z)


Q:

USB keyboard, unaffected by settings, repeating keys when held together

Key Repeat and Delay Until Repeat settings work fine and are immediately applied for the MacBook keyboard in TextEdit, but have no effect on the USB keyboard - even after reboot.
If I hold hi, the result is hhi via the USB keyboard. Further, if I hold hit, the result is hhihit.
Another example, if I hold ca, the result is cac via the USB keyboard. Further, if I hold cat, the result is cactac. So different keys seems to give different behavior.
Any idea how to disable the repeating letters upon holding on the USB keyboard? Since it makes it difficult to type quickly. Also a bonus would be to have the keyboard settings applied to the USB keyboard.

TeckNet Kraken LED Illuminated Gaming Keyboard
macOS Sierra 10.12.3
MacbBook Pro (15-inch, Early 2011)

A:

Thank you to @tom-gewecke's suggestion! Trying a different keyboard worked, functioning normally without this issue.
So it seems to be a compatibility issue between the aforementioned keyboard and OS, possibly other versions of both.


Q:

HIghlighting the text in PDF document iPhone xcode

Hii friends,
i am developing a e Book using a web view where i am loading the web view with PDF document.Now i want to develop the search functionality but i am not unserstanding how to implement it.So kindly give me a solution,
Thanks in advance.

A:

Instead of using UIWebView, you might want to look into using Quartz 2D's CGPDFDocumentRef and parsing a CGPDFDictionary for strings of interest.
Once your know which PDF dictionary elements contain your text and where they are located, you might be able to highlight that text with other Quartz 2D routines.
Another option might be to convert your PDF document to RTF or HTML formats, either of which would probably be easier to parse and edit to add highlighting.


Q:

Delphi Menu Hint Bug

I got the code below from the site "https://www.thoughtco.com" (Zarko Gajic). It presents the tips near the mouse pointer when it is in the menu item.

However, it has a bug. When the menu is opened by the keyboard the tooltip appears next to the mouse pointer, regardless of the location on the screen where the mouse pointer is.

I tried to fix the bug by adding the lines that are commented out. Now the error is that the hints always appears regardless of whether you click the menu item quickly or not.
How to fix this problem?
Thanks.
The code:
procedure TfrmPrincipal.WMMenuSelect(var Msg: TWMMenuSelect);
var
  menuItem : TMenuItem;
  hSubMenu : HMENU;
  hPopupWnd: HWND; // Added
  R: TRect;        // Added
  Pt: TPoint;      // Added
begin
  inherited;

  menuItem := nil;

  if (Msg.MenuFlag <> $FFFF) or (Msg.IDItem <> 0) then
  begin
    if Msg.MenuFlag and MF_POPUP = MF_POPUP then
    begin
      hSubMenu := GetSubMenu(Msg.Menu, Msg.IDItem);
      menuItem := Self.Menu.FindItem(hSubMenu, fkHandle);
    end
    else
    begin
      menuItem := Self.Menu.FindItem(Msg.IDItem, fkCommand);
    end;
  end;

  hPopupWnd := FindWindow('#32768', nil); // Added

  if hPopupWnd = 0 then Exit;             // Added

  GetWindowRect(hPopupWnd, R);            // Added

  GetCursorPos(Pt);                       // Added

  if PtInRect(R, Pt) then                 // Added
    miHint.DoActivateHint(menuItem)
  else                                    // Added
    miHint.DoActivateHint(nil);           // Added

end;

constructor TMenuItemHint.Create(AOwner: TComponent);
begin
  inherited;

  showTimer := TTimer.Create(self);
  showTimer.Interval := Application.HintPause;

  hideTimer := TTimer.Create(self);
  hideTimer.Interval := Application.HintHidePause;

end;

destructor TMenuItemHint.Destroy;
begin
  hideTimer.OnTimer := nil;
  showTimer.OnTimer := nil;
  self.ReleaseHandle;
  inherited;
end;

procedure TMenuItemHint.DoActivateHint(menuItem: TMenuItem);
begin
  hideTime(self);

  if (menuItem = nil) or (menuItem.Hint = '') then
  begin
    activeMenuItem := nil;
    Exit;
  end;

  activeMenuItem := menuItem;

  showTimer.OnTimer := ShowTime;
  hideTimer.OnTimer := HideTime;
end;

procedure TMenuItemHint.HideTime(Sender: TObject);
begin
  self.ReleaseHandle;
  hideTimer.OnTimer := nil;
end;

procedure TMenuItemHint.ShowTime(Sender: TObject);
var
  r : TRect;
  wdth : integer;
  hght : integer;
begin
  if activeMenuItem <> nil then
  begin

    wdth := Canvas.TextWidth(activeMenuItem.Hint);
    hght := Canvas.TextHeight(activeMenuItem.Hint);

    r.Left := Mouse.CursorPos.X + 16;
    r.Top := Mouse.CursorPos.Y + 16;
    r.Right := r.Left + wdth + 6;
    r.Bottom := r.Top + hght + 4;

    ActivateHint(r,activeMenuItem.Hint);
  end;

  showTimer.OnTimer := nil;

end;

A:

WM_MENUSELECT tells you whether the menu item is being selected by mouse or keyboard.
If the MF_MOUSESELECT flag is present, use the mouse coordinates provided by GetCursorPos() (or the VCL's TMouse.CursorPos wrapper), or GetMessagePos().
If the flag is not present, use GetMenuItemRect() to get the screen coordinates of the bounding rectangle of the specified menu item, and then use whatever coordinates you want that are within that rectangle (centered, bottom edge, etc).
You should NOT be trying to work with the menu window directly at all, so get rid of your calls to FindWindow(), GetWindowRect(), and PtInRect().


Q:

How to export a variable that takes its value from an async function

I apologize if my question sounds stupid, but I found that I need in many situations global variables such as ones that represent database and redis clients to be used in many files, however these variables themselves need to wait to get their values from promises or async functions that initialize the communication to the database or redis servers.
I want to do something like that
init.js:
export default async () => {
   return await initializeWhatever()
}

db.js:
import init from './init'
let db = null
init().then(val => db = val)
export default db

api.js:
import db from './db'
const doApi = req => {
 db('users').select({username:req.param.username})
}

However the db variable imported in api.js is always null, why doesn't it get updated to the correct value when init() finishes? If my approach to using db is wrong, what is the correct way to export global variables that are computed asynchronously?

A:

When you export a variable, you're exporting what's stored in the variable, not the variable itself. Assigning to the variable will only change the variable, but will not affect what was exported.
Think of it like this:
let a = null;
let b = a;
a = 'something';
console.log(b);
// null

Note how storing something new in a doesn't change what's stored in b.
To do something like what you want in your question,  you need to export an object and update references on that object:
init.js
export default async () => {
    return await initializeWhatever()
}

db-module.js
import init from './init'
const dbModule = { db: null };
init().then(val => dbModule.db = val)
export default dbModule

api.js
import dbModule from './db-module'
const doApi = req => {
    dbModule.db.select({username:req.param.username})
}

Obviously you might want to change some names to make things cleaner. I don't know a lot about your project so I'm not sure how to name them.
Also, you'll have to make sure have some way of making sure that any uses of your dbModule.db object happen after it's actually in place. In other words, you have to make sure there's no way doApi in api.js can be invoked before init in db-module.js finishes.
To do this, you'll need to make the promise chain from init available to api.js:
init.js
export default async () => {
    return await initializeWhatever()
}

db-module.js
import init from './init'
const dbModule = { db: null };
dbModule.promise = init().then(val => dbModule.db = val)
export default dbModule

api.js
import dbModule from './db-module'
const doApi = req => {
    dbModule.db.select({username:req.param.username})
}
dbModule.promise.then(() => {
    // Set up routes and start listening in this promise chain.
    // Ensure there is no way `doApi` can be called before this happens.
});

Why does this work? Because in JS, variables don't store entire copies of objects. They simply store references. If two variables point at the same object, changes to the object will be reflected whether your access it through one variable or another. Think of it like this:
let c = { prop: null };
let d = c;
c.prop = 'something';
console.log(d.prop);
// 'something'


Q:

Update only one field in EF Core

How could I update only one field of my table by EF core?
In another language how could I translate below SQL statement into EF Core  :
UPDATE table_name SET column1 = value1 WHERE condition;

A:

I update it by below code
 public async Task updateUserInfo(string token,long  userId)
        {
User user = _userRepository.GetDbContext().Set<User>().Find(userId);

            user.token= token;

            _userRepository.GetDbContext().Set<User>().Attach(user);

            _userRepository.GetDbContext().Entry(user).Property(x => x.token).IsModified =true;
           await _userRepository.GetDbContext().SaveChangesAsync();
}


Q:

PHP reading fields in database

I have a script that reads my database table fields. Its not reading the first column which is the id.It reads the other fields and adds them into the array. I have added in the for loop a -1 to get every field but to no success.
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);

$key_values = array();

$link = mysql_connect($host,$user,$pass);
$db_select = mysql_select_db($dbselect);
$query = mysql_query('SHOW COLUMNS FROM '.$table.'');

if (!$link) {
    die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = $dbselect;
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
    die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from '.$table.'', $link);
$num_fields = mysql_num_fields($res);
for($i=0;$i<$num_fields;$i++){

$key_values[]=mysql_field_name($res,$i);

}
echo "<pre>";
print_r($key_values);
echo "</pre>";

A:

There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.
<?php
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);

$db = new mysqli($host,$user,$pass,$dbselect);
if($db->connect_error)
        die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

// NOTE real_escape_string may not work for tables untested
$result = $db->query("SELECT * FROM " . $db->real_escape_string($table));
if (!$result)
        die "Error: " . $db->error;

while ($row = $result->fetch_object())
{
    echo $row->id;
}
$result->close();
$db->close();


Q:

Есть ли смысл регулярно менять крупный (30 символов?) ключ доступа к секретному файлу?

Рассматриваю два варианта шифрования ссылки.

Есть секретное слово, которое меняется каждый раз дня каждого пользователя и состоит из ~ 30 символов.
Секретное слово всегда одно и то же.

Вопрос в том что - естественно найдется умный человек, который раскодирует ссылку, но больше времени понадобится ли при первом варианте или же нет?
Ну и может кто то подскажет хорошую библиотеку на php, чтобы закодировать ссылку на файл?

A:

Секретное слово расшифровать нельзя, не из чего. Его можно разве что угадать (или украсть, но это читерство, не рассматриваем).
Скорее всего ваша система недостаточно мощная (или в слове достаточно энтропии), чтобы дать злоумышленнику опробовать все возможные комбинации за один день, поэтому считаем, что хотя бы одна смена всё-таки произошла.
Новая ситуация возникает всего одна. Если смена произошла на комбинацию, которую атакующий уже опробовал, то в результате успешного перебора без повторов он может не найти правильный ответ.
Поэтому смена слова каждый день может улучшить ситуацию, но чисто теоретически. Даже без неё подобная атака трудноосуществима на практике, потому что чтобы уложиться в разумное время, перебор вынужден будет производиться с огромной скоростью, давая огромную нагрузку на систему, вызывая огромные задержки и потенциально отказ всего сайта, что... вы же заметите, наверное?


Q:

Classic ASP Impersonation | Windows authentication | File Access Denied IIS 7

I have a classic ASP/VBScript website (landing page - default.asp) that writes the website user access (LOGON_USER) activity to a simple txt file via the Scripting.FileSystemObject.
VBScript creates an FSO to open/create a new file under the folder 'logs'
Windows 2008 R2 64 bit environment
IIS 7.5 -

Authentication - Windows Authetication enabled. All other authentication disabled.
AppPool running in Classic PipeLine mode;
Enable 32 bit applications set to true;
Identity is NetworkService.
Load User Profile set to false
ASP: executeInMta set to false

ACL for logs folder

Users group - Read and Execute;
SYSTEM - Full Control (Inherited);
Administrators - Full Control (Inherited);
IIS_IUSRS - Full Control;
Network Service - Full Control.

This setting yields me a '800A0046 - Permission Denied'.
Please note that windows authentication is enabled. And I map the LOGON_USER value to a value in DB to permit a user access my website. AppPool is set to NT Authority\NetworkService. Though the apppool identity is set to NetworkService, after a user autheticates, the files are accesses via the authenticated user (impersonated). Sample Process monitor activity below.
Process Monitor File System Activity

default.asp - Desired Access - SUCCESS - Impersonation: domainname\username
logs\log3011.txt - Desired Access - DENIED - Impersonation: domainname\username

Now, this puts me in a situation where I have to go to the security properties of 'logs' folder and grant every permissible user Read/Write permission. What I am looking for is, since my apppool runs as NetworkService(logs folder is given full control for NetworkService), I want the logs folder to be accessed via Network Service and not the user authenticated via windows authentication. I understand that this is the expected result when using Windows authentication. However, I use windows autnetication just to verify if the user is allowed to access the website. I need all other website actitivities to use NT Authority\NetworkService.  (I am asking for a solution to stop Classic ASP impersonating the windows authenticated user, and rather use the appool identity - networkservice in my case - to access the resources)
Is that too much to ask for?
Please guide me with appropriate explanations. Thx.

A:

Yup. Classic ASP impersonates. Don't know of a way around this that's built in to ASP - you might find StackOverflow more knowledgeable on this, as I'd suggest it's a programming topic.
Your desired model is usually referred to as the "trusted subsystem" model in the ASP.Net Patterns and Practices documentation (from years ago).
In the past, I've used an ASP.net page with  to do the writing, called via WinHTTP from an ASP page; using a COM object with its own identity specified is the other alternative. You could (as easily) convert the page to ASP.Net, and just use that with impersonation off. And then there's the "call RevertToSelf()" option, which forgets your thread identity; you may need a COM object to do that for your thread as well, from memory again.
Edit: Or use a database that runs as a different identity; the file system's only problematic because it's so easy to use!
Also, if the users all write to the same file, the "write to a log" scheme isn't viable when multiple users access it concurrently, and it'll at best introduce a delay in that scenario.
If each user only needs to write to their own log (and you hope they don't hit refresh too soon while writing to avoid concurrency issues), you might be able to simply grant Write permission to those users to that folder. Without Read, it's a bit useless; without actually attacking the box (it's Windows Integrated so you're on an intranet) it'd be hard for them to accidentally overpopulate the username and DoS the machine.


Q:

How to convert ip address to DWORD?

Hey, how can I convert ip address to DWORD using python ?
I searched a while but didn't found anything useful.
Thanks for the helpers!

A:

Don't roll your own solution.  Use the socket library.
import socket
socket.inet_pton(socket.AF_INET, "127.0.0.1")

It will throw exceptions when it can't properly parse the address, and writing your own parsers for things is just a recipe for problems down the line.
Doing it this way also makes it easier to transition your code to IPv6.  And writing your own address parser for IPv6 would be a really bad idea because IPv6 addresses are complex and have some weird corner cases.
Edit: Apparently, this doesn't work on Windows.  I'm not sure how you're supposed to parse IPv6 addresses on Windows, but there is still a library call that can parse IPv4 addresses.  It's socket.inet_aton, and you should use it if socket.inet_pton doesn't exist instead of rolling your own solution.

A:

Python doesn't have a DWORD type. If you need it as a 4-byte string use:
struct.pack('bbbb', *(int(x) for x in '127.0.0.1'.split('.')))


Q:

Require Domain on Email Address jQuery Validation

I'm using the following code (with jQuery Validation Plugin)  to validate an email address:
    $(".schedule-tour-form").validate({
        rules: {
            Email: {
                required: true,
                email: true
            }
        },
    });

    <input id="email" name="Email" class="email" type="email" placeholder="name@email.com" />

Problem is it still allows emails without domain suffixes. For example it validates "test@test"
How to I require a domain suffix?

A:

The official page of plugin, even consider test@test as a valid mail, then I suppose that this is intended. You could create a new rules, with a strict regex pattern, as suggested here.
//custom validation rule
$.validator.addMethod("customemail",
    function(value, element) {
        return /^([a-zA-Z0-9_.-+])+\@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(value);
    },
    "Sorry, I've enabled very strict email validation"
);

Then to your rules add:
rules: {
                    email: {
                        required:  {
                                depends:function(){
                                    $(this).val($.trim($(this).val()));
                                    return true;
                                }
                            },
                        customemail: true
                    },


Q:

Software design/architecture problems

I code for a while now and learned several programming languages. I programmed a lot of little tools and such. I think I master the act of coding itself pretty good so I have e.g. no problems with syntax, I got a pretty good understanding of what is going on under the hood (reasonable assembler knowledge) and so on.
My big problem though is: I just can't design bigger/more complex applications. I learned the principles of OOP, design patterns, learned some basic lisp programming and all stuff I could find and thought it would help me with my issue.
But no matter what I try, how long I try: I just can't get it right. My designs always seem wrong to me somehow. Cause of that I never drawn through a bigger project, i'm kinda never satisfied with the structure of my program.
Have you had a similiar problem? How did you manage to solve it? Got you any hints for me on how to go on?

A:

I think experience is a key factor here. Every design fails at some point, then it's up to you to improve it and learn from your mistakes.
In my opinion good software design is not something you can learn by reading a few books.

A:

Design itself is an iterative activity. You first start with a certain design and then in phases you make it better.
Design is not about achiveing perfection, which can't even be achieved in larger application.
Design is all about making good balances and tradeoffs that in the end provide a good, robust and maintainable application, that conforms to the requirements.
You will never get it 100% right on all sides.
Reading a few good books on design/architecture will not make you directly a rock star on the matter but it will certainly give you the tools that you can use to improve and perfect your skills.
Here are some examples of books:

Code Complete: A Practical Handbook
of Software Construction
Head First Design Patterns
Design Patterns: Elements of
Reusable Object-Oriented Software
Patterns of Enterprise Application
Architecture
Microsoft .NET: Architecting
Applications for the Enterprise
(PRO-Developer)
The Art of Unit Testing: With
Examples in .Net

Of course practical experience also counts.

A:

 design bigger/more complex applications

When you say  design bigger/more complex applications, i assume what you have in mind is what are generally referred to as "Enterprise scale applications".
You can check out this question which talks about various criteria that help to try and objectify as to what it is that makes an application an enterprise scale application.
Talking about these concerns,

Small applications might not necessarily have a lot of these concerns applicable to them.
Even with enterprise apps, with such a large set of concerns that need to be addressed, what differentiates the design is what concerns are given more importance. Also, in case of conflicting concerns, which one is chosen over the other.

When designing for your application, if you try and keep these concerns in mind and make design decisions based on these concerns, then that will be one way to try of moving in the right direction.HOWEVER, this is easier said than done. Though seemingly a simple looking list, getting a design right is something seasoned architects lose sleep / hair / life over and is usually NOTORIOUSLY difficult to get right especially for a beginner.
Some of these decisions are things learnt only from experience. In my personal experience, what greatly helped me was working with and under the supervision of experienced architects. To be able to learn and gaining the benefit of their knowledge and experience teaches you things no book / blog can.
But no matter what i try, how long i try: i just can't get it right.
My designs always seem wrong to me somehow.

Frankly speaking, you are totally the wrong person to judge. How do you really know that your design is wrong? The only real way to say design is wrong is if your application doesnt do what it was supposed to do.
If you want to have some validation of your design, then i suggest you ask someone who has worked on similar size projects which you have in mind and ask them to look at your design and review it - from their perspective. That, will really give you some good idea as to where your design is really at.
Cause of that i never drawn through a bigger project, i'm kinda never satisfied
with the structure of my program.

Unfortunately, some of the real complexities in designing an enterpise application result from a variety of things that are just not possible to simulate otherwise. Some of them can be organizational constraints e.g. my client's CTO does not use allow the use of X technology ) to others like we need to integrate our application with that home grown MS Access app that one of our vendors is using. Such complications to the application and its design is something that you have to experience and there is usually a lot to be learned from it.
To get such experience, you have to work in such places which provide this kind of opportunity. Usually, what i have seen is that the bigger the company, the more complicated their IT environment is and that gives the most opportunity for complex scenarios to arise


Q:

Does the symfony cache file system handle ext2 32000 files in the same directory limitation?

Does the symfony cache system handle ext2 32000 files in the same directory limitation ?
I have 80000 users and i want to cache their profiles but do symfony cache system handle the ext2 limitation ?
i'm also posting for the others who will face the same problem.

A:

I'm not 100% sure whether my answer is correct but in PROJECT/lib/symfony/cache/sfCacheFile.class.php there is a method: sfCacheFile::getFilePath() that returns a path to a file. It seems that there is no any protection against limitations of ext2 filesystem.
But there is a very simple solution - override that class:

In PROJECT/apps/APP/config/factories.yml set your own cache class:
default:
# Others factories (if any)

  view_cache:
    class: myOwnFileCache
    param:
      automatic_cleaning_factor: 0
      cache_dir:                 %SF_TEMPLATE_CACHE_DIR%
      lifetime:                  86400
      prefix:                    %SF_APP_DIR%/template

Now create that class and make sure it extends sfFileCache and overrides getFilePath()
# PROJECT/lib/PROJECT/cache/myOwnFileCache.class.php
class myOwnFileCache extends sfFileCache {
    protected getFilePath($key) {
        /*
            Convert from: abcdef
                      to: a/b/abcdef
        */
        $key = substr($key, 0, 1) . DIRECTORY_SEPARATOR . substr($key, 1, 1) . DIRECTORY_SEPARATOR . $key;
        return parent::getFilePath($key);
    }

}
Clear cache: ./symfony cc

Now you need 32000 cache keys that starts with the exact same two letters/digits to crush your filesystem.


Q:

How to get a max and min values of a number in a loop with twig?

I am listing some products but i don't want to use max() and min() in query SQL. I tried to use max() from twig, but it returned an error.
{% for product in products %}
   {% set maxValue = max(product.value)%}
   value--->>{{maxValue}}
{% endfor %}

Error:

An exception has been thrown during the rendering of a template ("max() [function.max]: When only one parameter is given, it must be an array")

A:

Issue resolved
{% set maxValue = 0 %}

{% for product in products %}
    {% set maxValue = max(product.value, maxValue) %}
{% endfor %}

{{maxValue}}


Q:

supressing a line if a subreport is empty in crystal reports

I have a report made on crystal reports that one of its fields is a subreport. I have a line object drew below this subreport for division purposes.
Something like this:
| SUBREPORT |
------------- (line object)

Is there a way to supress this line if my subreport is empty? I've tried to use a bottom border on the subreport, but it won't align with the rest of the report.

A:

add a section below the sub report and add line in that section. Now write your supress condition for that section so that line gets supressed


Q:

How to make bar plot with converting the month column in python?

I have a dataframe like this. The month column is in type of string.
I want to make a bar plot from 201501 to 201505 with x axis is month while y axis is total_gmv. x format is like Jan,2015   Feb 2015. So how can I realize it using python?  Thanks.
month   total_gmv
201501  NaN
201502  2.824294e+09
201503  7.742665e+09
201504  2.024132e+10
201505  6.705012e+10

A:

Previous replies have some clues but its does not show exhaustive answer.
You have to set custom xtick labels and rotate it like here:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {'month': ['201501', '201502', '201503', '201504', '201505'],
     'total_gmv': [np.nan, 2.824294e+09, 7.742665e+09, 2.024132e+10, 6.705012e+10]})
df['month'] = pd.to_datetime(df['month'], format='%Y%m', errors='ignore')

ax = df.plot(kind='bar')
ax.set_xticklabels(df['month'].dt.strftime('%b, %Y'))
plt.xticks(rotation=0)
plt.show()


Q:

LDAP: How to add a person to an existing group?

Using command-line (Linux) or LDIF, I could find many examples of creating a new group and defining its members, but no examples of this:
How to add a user to an existing group?
Let's say the person also already exists.
For instance adding user uid=fred,ou=people,dc=example,dc=com to group cn=vipb,ou=groups,dc=example,dc=com.

A:

You add a memberUid attribute to the group. For example:
$ ldapmodify -D <admin DN> -h <ldaphost>
password: [enter password]
dn: cn=vipb,ou=groups,dc=example,dc=com
changetype: modify
add: memberUid
memberUid: fred

^D

For the record, the LDAP schema is described in RFC 2307.


Q:

git checkout . not working on R.java

I am working on an android project through Github. Now, when I pull any commit and do any unwanted changes in working directory, I use git checkout . to revert back. This works fine with all other files but shows R.java still as modified. How to revert R.java file also? I am using PowerShell Git in Windows8.

A:

R.java is automatically generated and shouldn't be checked into VCS. You have to add the following lines to your .gitignore file to prevent generated files to be added to the source control:
# Generated files
bin/
gen/


Q:

XPath all descendents, even if nested - but not descendents of parent

I am attempting to write XPath to work with some XML Nodes.
Sample of my XML is below (for Element name and nesting illustration).
<Forms>
<Form>
 <Control/>
 <Control>
    <Control></Control>
 </Control>
 <Control>
   <Form><!-- This is the nested one, I don't want the Control children from this-->
    <Control/>
   </Form>
 </Control>
</Form>

Is there a way to modify the XPath statement below - to include all Controls (even ones nested within eachother - under the "Form", but not from nested Form(see Form<2>)? This current XPath brings back "Controls" that are underneath nested "Form" nodes.
string xpath = @"/Forms/Form[@id='" + node.Attributes["id"].Value + "']//Control[@type='GroupItem' or @type='Detail' or @type='GroupHeader']";

I am basically trying to un-nest all Control tags, and wrap them with "Controls" tag, so I am using this Xpath in C# to reformat - but I don't want to pull Control out of a nested Form, I want to wrap their in Controls tag seperately.
Thanks for any assistance!

A:

How about:
 /Forms/Form[@id='blah']/descendant::Control[blah]

this uses the descendant axis on the Control lookup (the default is child)
Obviously replace the blah - they are just for brevity; the important thing in the above is descendant::


Q:

JSON.parse throws errors while eval doesn't on the same strings. Why?

suppose I have something like
var a = '["\t"]'

If I do
eval('var result = ' + a)

Everything works fine. But if I do
var result = JSON.parse(a)

It throws error: Unexpected token.

Same happens with \b, \f: works with eval, while fails with JSON.parse. Why? Shouldn't the parser behave in the same way when encounters "\t"?
On the other hand, both eval and JSON.parse fail with a \n (as expected), but they also both fail with a \r. Why is this?

I'm a little bit confused with all this so could anybody explain what is going on? If possible with details: how is the parser behaving in the two cases?

A:

You have to escape \ in the JavaScript string, so you'd end up with
var a = '["\\t"]'

For details, please refer to "http://json.org/"


Q:

Javascript function not firing on click

I have a Javascript function in which on click of a button, a post request will be sent to another file. If this request is successful, the button will be disabled and its color changes. An alert will be returned as well.
$(document).on("click", ".employeeComplete", employeeReg);

    function employeeReg(self, name){
        self = $(self);
        var stats   = {};
        stats['age']  = 'age';
        stats['name'] = name;
        $.post('employee', stats)
        .done(function(e){
            alert("hello");
            if(e){
                alert("This employee has been registered.");
                self.attr('disabled', 'disabled');
                self.css('background-color', '#111111');

            }
            else{
                alert("Error.");
            }
        })
        .fail(function(){
            alert("Error.");
        });

        self.attr("disabled", "disabled");
    }

in the first line, i had previously had parantheses after my function name as such:
$(document).on("click", ".employeeComplete", employeeReg());

but that fired the function on page load, not on button click. Upon removing the parentheses, the function doesn't work on button click or page load at all. Thanks.
edit
my sselector was misspelled, but the only the alert is being returned, no button change or disable.
when i change self to this or $(this) (Also removed the self variable and parameter from function) , i receive the following console error:
Uncaught TypeError: Illegal invocation

A:

The first (and generally only) argument to an event callback is the event data itself. This is done by the browser JS engine and is not something you can influence or choose yourself.
To get the item clicked on, within the callback context, you can always reference this.
See example below (in order to make a runnable demo I've commented out the ajax part, the purpose is to demonstrate the correct use of this).

$(document).on("click", ".employeeComplete", employeeReg);

function employeeReg(event) {
  var self = $(this);
  var stats = {};
  stats['age'] = 'age';
  stats['name'] = name;
  /*        $.post('employee', stats)
          .done(function(e){
              alert("hello");
              if(e){
                  alert("This employee has been registered.");
                  self.attr('disabled', 'disabled');
                  self.css('background-color', '#111111');

              }
              else{
                  alert("Error.");
              }
          })
          .fail(function(){
              alert("Error.");
          });*/

  alert("This employee has been registered.");
  self.css('background-color', '#111111');
  self.attr("disabled", "disabled");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="employeeComplete">Click to test</button>

N.B. Also consider switching ".attr" for ".prop" - see documentation at http://api.jquery.com/attr/ which states: "As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method." . There is also a more detailed discussion of why this is the case.


Q:

emacs で、 tmux でいうところの balance-window はできますか？

emacs で縦ウィンドウ分割を行っていくと、例えば 1/2, 1/4, 1/4 で分割されます。これを、 1/3, 1/3, 1/3 になるように、高さを調整したいのですが、これを実現する機能はありますか。

A:

M-x balance-windows, C-x + で実現できました。


Q:

Dynamically add items to jquery slideshow

I'm trying to add items to a jquery slideshow ( slides ) but i can't find a way to refresh it.
I have this html code:
add slide

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

and this js:
$(function() {
    $("#slides").slides();

    $('.add').live('click', (function() {
        $('.slides_control').append('
Slide added
');
        // note: slides_control div is added by the slides plugin automatically and is the real container of the items.
        return false;
    }));

});

The demo is in fiddle
I need to reload the slideshow to show new data but i can't find a way to do it.

A:

The newest version of Slides (see Github) actually does have a function slides('update'), but the current version doesn't have that yet.
In the meantime, you can use this little hack:
$("#slides").slides();

$('.add').on('click', function() {
    var children = $('#slides .slides_control').children();
    var newContainer = $('
');
    var slides = $('#slides');

    slides.empty().append(newContainer);
    newContainer.append(children);
    newContainer.append('

New slide

');

    slides.slides();

    return false;
});

You can play with it here: http://jsfiddle.net/R7zvM/
Please note that you should probably do some testing before using this in production code. It seems pretty stable, but your mileage may vary.
P.S. the .live() method is deprecated as of jQuery 1.7. In this example you did't need event delegation, anyway, but if you ever do you should use the new syntax:
$(document).on('click', 'a.add', function() {
    console.log('Do something');
});


Q:

Displaying tomorrows day and the day after in Dutch?

I am currently using simpleWeather.js to display simple weather forecasts on my personal website. It's working great, but I am experiencing one simple issue.
Currently it outputs forecasts in English, like:

THU: 22°C
FRI: 26°C
SAT: 23°C

However instead of showing "THU:" I want it to show "Donderdag:".
Obviously the same result for the remaining days of the week.
I know it's preffered to have a working code example, so I created one here:
https://codepen.io/anon/pen/Moreab
$(document).ready(function() {
  $.simpleWeather({
  location: 'Austin, TX',
  woeid: '',
  unit: 'c',
  success: function(weather) {

  html = '
'+weather.forecast[1].day+':  min. '+weather.forecast[1].low+' max. '+weather.forecast[1].high+'
';
  html += '
'+weather.forecast[2].day+':  min. '+weather.forecast[2].low+' max. '+weather.forecast[2].high+'
';
  html += '
'+weather.forecast[3].day+':  min. '+weather.forecast[3].low+' max. '+weather.forecast[3].high+'
';
  html += '
'+weather.forecast[4].day+':  min. '+weather.forecast[4].low+' max. '+weather.forecast[4].high+'
';

  $("#weather").html(html);
},
error: function(error) {
  $("#weather").html('
'+error+'
');
}
});
});

It looks ugly, but it's shows exactly what I mean. As you can see it shows THU: FRI: SAT: etc...
I want those to be changed to their Dutch relatives.
Can someone tell me how to achieve this? TY.

A:

You can use an object to translate the English names to Dutch:
var day_to_dutch = {
    Mon: 'Maandag',
    Tue: 'Dinsdag',
    Wed: 'Woensdag',
    Thu: 'Donderdag',
    Fri: 'Vrijdag',
    Sat: 'Zaterdag',
    Sun: 'Zondag'
};

Translating can be done as follows:
day_to_dutch[weather.forecast[1].day]


Q:

Unable to get all the data including links from a tr tag

I've written a script in python to get data from some html elements which are in a table. I have roughly picked some data which are within a tr tag. My goal is to get the data (including href links) within class fn. What I have tried so far can parse all of them (from class fn excluding the links). How can I change my below script to get the links as well from that class. Thanks in advance for any solution.
This is what I've tried so far:
from bs4 import BeautifulSoup

content="""

    1964
    Townes, Charles HardCharles Hard Townes;

    Basov, NikolayNikolay Basov;

    Prokhorov, AlexanderAlexander Prokhorov
    Hodgkin, DorothyDorothy Hodgkin
    Bloch, Konrad EmilKonrad Emil Bloch;

    Lynen, Feodor Felix KonradFeodor Felix Konrad Lynen
    Sartre, Jean-PaulJean-Paul Sartre[D]
    King, Jr., Martin LutherMartin Luther King, Jr.
    —

"""
soup = BeautifulSoup(content,"lxml")
for items in soup.select('tr'):
    item_name = [item.text for item in items.select(".fn a")]
    print(item_name)

Output I'm having now:
['Charles Hard Townes', 'Nikolay Basov', 'Alexander Prokhorov', 'Dorothy Hodgkin', 'Konrad Emil Bloch', 'Feodor Felix Konrad Lynen', 'Jean-Paul Sartre', 'Martin Luther King, Jr.']

To remind you again: my expected output is to get all the data including href links from class fn.

A:

You can use either bs4 or regular expressions:
bs4:
from bs4 import BeautifulSoup as soup
s = soup(content, 'lxml')
new_data = list(zip([i.text for i in s.find_all('a')], [i['href'] for i in s.find_all('a', href=True)]))

Output:
[(u'Charles Hard Townes', '/wiki/Charles_Hard_Townes'), (u'Nikolay Basov', '/wiki/Nikolay_Basov'), (u'Alexander Prokhorov', '/wiki/Alexander_Prokhorov'), (u'Dorothy Hodgkin', '/wiki/Dorothy_Hodgkin'), (u'Konrad Emil Bloch', '/wiki/Konrad_Emil_Bloch'), (u'Feodor Felix Konrad Lynen', '/wiki/Feodor_Felix_Konrad_Lynen'), (u'Jean-Paul Sartre', '/wiki/Jean-Paul_Sartre'), (u'[D]', '#endnote_Note1D'), (u'Martin Luther King, Jr.', '/wiki/Martin_Luther_King,_Jr.')]

Regex:
import re
new_data = map(lambda x:filter(None, x)[0], re.findall('href="(.*?)"|title="(.*?)">', content))
final_data = [(new_data[i], new_data[i+1]) for i in range(0, len(new_data)-1, 2)]

Output:
[('/wiki/Charles_Hard_Townes', 'Charles Hard Townes'), ('/wiki/Nikolay_Basov', 'Nikolay Basov'), ('/wiki/Alexander_Prokhorov', 'Alexander Prokhorov'), ('/wiki/Dorothy_Hodgkin', 'Dorothy Hodgkin'), ('/wiki/Konrad_Emil_Bloch', 'Konrad Emil Bloch'), ('/wiki/Feodor_Felix_Konrad_Lynen', 'Feodor Felix Konrad Lynen'), ('/wiki/Jean-Paul_Sartre', 'Jean-Paul Sartre'), ('#endnote_Note1D', '/wiki/Martin_Luther_King,_Jr.')]

A:

This modified code got me the href together with the data
from bs4 import BeautifulSoup

content="""

    1964
    Townes, Charles HardCharles Hard Townes;

    Basov, NikolayNikolay Basov;

    Prokhorov, AlexanderAlexander Prokhorov
    Hodgkin, DorothyDorothy Hodgkin
    Bloch, Konrad EmilKonrad Emil Bloch;

    Lynen, Feodor Felix KonradFeodor Felix Konrad Lynen
    Sartre, Jean-PaulJean-Paul Sartre[D]
    King, Jr., Martin LutherMartin Luther King, Jr.
    —

"""
soup = BeautifulSoup(content,"lxml")
for items in soup.select('tr'):
    item_name = [[item.text,item.get('href')] for item in items.select(".fn a")]
    print(item_name)

OUTPUT
[['Charles Hard Townes', '/wiki/Charles_Hard_Townes'], ['Nikolay Basov', '/wiki/Nikolay_Basov'], ['Alexander Prokhorov', '/wiki/Alexander_Prokhorov'], ['Dorothy Hodgkin', '/wiki/Dorothy_Hodgkin'], ['Konrad Emil Bloch', '/wiki/Konrad_Emil_Bloch'], ['Feodor Felix Konrad Lynen', '/wiki/Feodor_Felix_Konrad_Lynen'], ['Jean-Paul Sartre', '/wiki/Jean-Paul_Sartre'], ['Martin Luther King, Jr.', '/wiki/Martin_Luther_King,_Jr.']]


Q:

force user to enter specific details in textbox input

i want to force users to enter details for check like "Check No: 791790 Date: 26/05/2015 ClrDate: 29/05/2015" in one textbox
the textbox i am using :
<input type="text" class="form-control validateblank txtAccCheckDet" id="txtAccCheckDet">

i have tried using
data-inputmask="'alias': '"Check No:''" "Date:" dd/mm/yyyy'" "ClrDate:"'dd/mm/yyyy' data-mask=""
in textbox but not working.
any help using css,javascript or jquery will be acceptable.

A:

You can use a regular expression, something like this for example.
var regex = '^Check\sNo: [0-9]{6}\sDate:\s[0-3]{1}[0-9]{1}\/[0-9]{2}\/[0-9]{4}\sClrDate:\s[0-3]{1}[0-9]{1}\/[0-9]{2}\/[0-9]{4}$'

And then use something like
string.match(regex)

To check if the inputed string matches the regex.


Q:

Striped table rows in ASP.NET MVC (without using jQuery or equivalent)

When using an ASP.NET WebForms ListView control to display data in an HTML table I use the following technique in to "stripe" the table rows:
<ItemTemplate>
    <tr class="<%# Container.DisplayIndex % 2 == 0 ? "" : "alternate" %>">

</ItemTemplate>

With the following CSS:
tr.alternate
{
    background-color: #EFF5FB;
}

I have just gone through the ASP.NET MVC Movie Database Application tutorial and learnt that in MVC-land table rows can be (must be?) constructed as follows:
<% foreach (var item in Model) { %>

            <%= Html.Encode(item.Title) %>

<% } %>

What can I add to this code to stripe the rows of my table?
Note: I know that this can be done using jQuery, I want to know if it can be done another way.
Edit
If jQuery (or equivalent) is in your opinion the best or most appropriate post, I'd be interested in knowing why.

A:

Another option that doesn't involve lambdas and is a bit cleaner than what you got working might be this...
<% int i=0; foreach (var item in Model) { %>
    <tr class="<%= i++ % 2 == 0 ? "alternate" : "" %>">

            <%= Html.Encode(item.Title) %>

<% } %>

A:

What about an extension method?
public static void Alternate<T>(this IEnumerable<T> items, Action<T, bool> action)
{
    bool state = false;
    foreach (T item in items)
        action(item, state = !state);
}

This way you could say:
<% movies.Alternate((movie, alt) => { %>
  <tr class="<%= alt ? "alternate" : "" %>">

        <%= Html.Encode(movie.Title) %>

<% }); %>

Edit, additionally if you want the index, you can use an extension method like this:
public static void Each<T>(this IEnumerable<T> items, Action<T, int> action)
{
    int state = 0;
    foreach (T item in items)
        action(item, state++);
}


Q:

On-line live analysis board?

Here is the situation. I have a friend with whom I very much like to discuss chess (our games, other games etc.). We are not living in the same country, so we discuss chess on-line. During our on-line discussions, we often, of course, need a chessboard. Usually, we use our wooden chessboards (which we see through our computer cameras), but this is inconvenient, as it causes synchronization difficulties.
My question is: Is there a site or a chess program with a chessboard which both my distant friend and me could see and alter, in such a way that every change in position is simultaneously shown to him and to me. In other words, something like a "live analysis board". If we were at the same place, we would have a chessboard on which we would analyze a game. He could alter the position, and I would see it, and vice versa. Now, I need the same thing, just on-line. Does anybody use something similar and/or has a suggestion?
I hope my description above is enough to understand what I mean. Obviously, my English is far from perfect, but I hope it will do.
Finally, I would like to stress that I am NOT asking for a suggestion for a site for PLAYING chess, but for ANALYZING games and discussing different positions.
Any suggestion would be appreciated. Thanks!

A:

Chess.com has an analysis board meant for doing analysis with other people. But its available only for premium members. Also I am unsure if it has voice support in built when doing the analysis.
For the free alternative, its worth to look at FICS- It has a very cool feature for analysis called "examine", that combined with "mexamine" will give you exactly what you are looking for. Along with this, you could just setup a skype or gtalk (replace your fav free voip program here) for chatting with voice when you are examining the game. You could use Babaschess the free and best FICS client available.

A:

You can use software for remotely accessing your friend's computer. He could run a program displaying a chessboard on the screen and you could use your own mouse to move the mouse pointer on his screen. You will both be seeing his screen and both able to affect the board with the mouse.

A:

After trying out several options, I have to say that I find the study tool on lichess by far and away the best.
It is intuitive, very easy to use, and the features are fantastic. For me, the most important features are the trivial way of importing previously annotated games (unlike with FICS, for example), the fact that all the analysis (variations, comments, arrows and highlighted squares) are saved and can be re-examined later, and all the comments from other users are also saved (which is very convenient). On top of all that, it's free (you only need to register).
You can learn more about the study tool here. I highly recommend trying it out (as well as lichess in general).


Q:

Location Manager inside Async Task from Service

I have a service which checks a Database through a period of time to check if there is a valid requirement for the GPS. If there is a usage, it then starts the GPS locationupdates. I tried using a different thread but it would cause the App to hang. I found the App performed better with the do in background.
I keep getting the following error

Can't create handler inside thread that has not called
  Looper.prepare().

I try to use Looper but I just for some reason just can't seem to find the right way to implement it. I need a hand getting to the PingListener which will not run, I did remove the error by adding in
Looper.prepare();
before the While loop in gpsPlotter.
Please ignore all the logging and some garbage variables I left which I've left in there as I like to trace everything while coding.
public class PingListener implements LocationListener{
    public void onLocationChanged(Location pointer) {
        // TODO Auto-generated method stub
        String lat = String.valueOf(pointer.getLatitude());
        String longi = String.valueOf(pointer.getLongitude());
        new pingThread().execute(lat, longi);
        Log.d("Updating", "Sending Updates");

    }
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}

private class pingThread extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        BeaconHandler db = new BeaconHandler(Ping.this);
        List<Beacon> beacons = db.getAllBeacons();

        int activecheck = 0;
        for(Beacon bn : beacons){
            activecheck = activecheck + bn.getStatus();
        }
        Log.d("Active Result", String.valueOf(activecheck));
        String ger = "";
        String postresponse = "";

          try{

            HttpClient retCode = new DefaultHttpClient();
            HttpPost retEmail = new HttpPost("http://www.site.com/tracker/return.php");

            List<NameValuePair> createValuePairs = new ArrayList<NameValuePair>();

            createValuePairs.add(new BasicNameValuePair("vert", args[0]));
            createValuePairs.add(new BasicNameValuePair("horz", args[1]));
            createValuePairs.add(new BasicNameValuePair("id", "2"));

            retEmail.setEntity(new UrlEncodedFormEntity(createValuePairs));

            // Execute HTTP Post Request
            ResponseHandler<String> createresponseHandler = new BasicResponseHandler();
            postresponse = retCode.execute(retEmail, createresponseHandler);

            ger = "Network Details\nLat:" + args[0] + "\nLong:" + args[1];
            Log.d("Sent: ", ger);
          }
          catch(Exception e){
              Log.e("Error", e.getMessage());
              Log.getStackTraceString(e);
          }

        return ger;

    }

    protected void onPostExecute(String value){

    }

}

private class gpsPlotter extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        int updateset = 0;
                    //Looper.prepare();
        while(true){
            try{
                BeaconHandler dbg = new BeaconHandler(Ping.this);
                List<Beacon> beacons = dbg.getAllBeacons();
                int activecheck = 0;
                for(Beacon bn : beacons){
                    activecheck = activecheck + bn.getStatus();
                }
                //db.close();
                if(activecheck > 0 && updateset == 0){
                    pinger.requestLocationUpdates(LocationManager.GPS_PROVIDER, 600, 0, reciever);
                    updateset = 1;
                    Log.d("GPS RESET", "Listener Set");
                }
                else if(activecheck == 0 && updateset == 1){
                    pinger.removeUpdates(reciever);
                    updateset = 0;
                    Log.d("GPS RESET", "Listener Removed");
                }
                else{
                    Log.d("GPS RESET", "No Modifications");
                }
                Thread.sleep(20000);
            }
            catch(Exception e){
                Log.e("GPS RESET ERROR", e.getMessage(), e);
            }
        }
    }
}

A:

Use IntentService instead of AsyncTask.


Q:

Resultado Busca não localizada

Bom dia!
Tenho dois JS, um que emula algo parecido com um banco de dados seguindo o exemplo:
var menu;

$(document).ready(function() {

menu = new clsMenu();

var Exemplo01 = menu.addFolder("Exemplo", "Exemplo")

})

E outro que faz o filtro nele:
    function letras(texto) {
        var letrasPorString = [];
        var letrasPorIndex = [];
        var i, letra;

        for (i = 0; i < texto.length; i++) {
            letra = texto.substr(i, 1);
            if (letrasPorString[letra] === undefined) {
                letrasPorString[letra] = 1;
                letrasPorIndex.push(letra);
            } else {
                letrasPorString[letra]++;
            }
        };

        this.porString = letrasPorString;
        this.porIndex = letrasPorIndex;
    }

    function compararLetras(letrasObj1, letrasObj2, corte) {
        var i;
        var qndeCertas = 0;
        for (i = 0; i < letrasObj1.porIndex.length; i++) {
            var letra = letrasObj1.porIndex[i];
            if (letrasObj1.porString[letra] === letrasObj2.porString[letra]) {
                qndeCertas++;
            }
        };

        var percentual = (qndeCertas / letrasObj1.porIndex.length) * 100;
        return percentual >= corte;
    }

    function duplas(texto) {
        var tduplas = [];
        var i;
        for (i = 0; i < texto.length - 1; i++) {
            tduplas.push( texto.substr(i, 2) );
        }

        return tduplas;
    };

    function compararDuplas(duplas1, duplas2, corte) {
        var i, j;
        var encontrados = 0;
        for (i = 0; i < duplas1.length; i++) {
            var dupla = duplas1[i];
            var encontrado = false;
            for (j = 0; j < duplas2.length; j++) {
                if (dupla == duplas2[j]) {
                    encontrado = true;
                }
            };

            if (encontrado) { encontrados++ }
        };

        var percentual = (encontrados / duplas1.length) * 100;
        return percentual >= corte
    }

    function compararKeyTag(key, tag, buscaAproximada, corte) {
        if (buscaAproximada === true) {
            var lk, lt, dk, dt;
            lk = new letras(key);
            lt = new letras(tag);
            dk = new duplas(key);
            dt = new duplas(key);

            if (corte === undefined) { corte = 70 }
            if ( compararLetras(lk, lt, corte) && compararDuplas(dk, dt, corte) ) {
                return true;
            } else {
                return false;
            }
        } else {
            if (tag.indexOf(key) > -1) {
                return true;
            } else {
                return false;
            }
        }
    }

    function compararKeysTags(keysArr, tagsArr, buscaAproximada, corte) {
        var encontrados = 0;
        $(keysArr).each(function(index, key) {
            var encontrado = false;
            $(tagsArr).each(function(index, tag) {
                if (compararKeyTag( key, tag, buscaAproximada, corte )) {
                    encontrado = true;;
                }
            });

            if (encontrado) {encontrados++};
        });

        if ( encontrados == keysArr.length ) {
            return true;
        } else {
            return false;
        }
    }

Retornando sempre o resultado deste filtro em uma div no arquivo html:

                    MENU

            <form class="search-container example">
                <input type="text" id="search-input" placeholder="Busca" style="color: black">

                <button type="submit" id="search"></button>
            </form>

O problema é, peguei esse projeto ja desenvolvido, e a pessoa que criou ele hoje não está mais trabalhando junto a mim, fora eu ainda não ter um conhecimento a ponto de conseguir fazer o que necessito, que é, quando a busca não retornar resultado, ser apresentado uma mensagem tipo "Sua busca não obteve resultado".
Alguém poderia me auxiliar com isso?
Desde já muito obrigado!

A:

Qual função é chamada quando se clica no botão de pesquisa? É só ir nessa função que é ativa quando se clica no botão pesquisar e fazer com que quando o retorno da pesquisa for nulo, que ele seja ativado um window.alert("Resultado Busca não localizada");.


Q:

Type casting differnce

In the following code :
#include<cstdio>
#define max(a,b) (a>b?a:b)
using namespace std;

int main()
{
    int f=10000000;

    long long i=(long long)max(1000000,f*f);
    printf("%lld",i);
    return 0;
}

I get the output of

276447232

But if I write
long long i=max((long long)1000000,(long long)f*f);

I get the output of

100000000000000

What is the difference between the two lines? Why doesn't the type conversion occur in the first case?

A:

This line says: "take the max of these two int values, the latter of which will overflow. Then take the result and cast it to long long". By the time the long long cast is called in the first case, it is too late. Signed integer overflow is undefined behavior.
long long i=(long long)max(1000000,f*f)

This line says: "take the max of these two long long values and return it". The reason (long long)f*f works is because it is casting the first f to long long before the multiplication, due to precedence. The second f is then promoted to long long for the multiplication to occur.
long long i=max((long long)1000000,(long long)f*f);


Q:

Knockout JS: `hasFocus` always has Focus

Background
I have a single view model, and two models. For each model, I'm attempting to bind a name property to the dom. There are default values for each name, but I want the user to be able to edit these values. Following the Knockout documentation, I went with the hasFocus  method. My problem is that, on click, I can edit, but when I click out, the focus does not change, and my array does not update. It looks like my model editable property is never set back to false. See the corresponding HTML and JS below.
So what am I doing wrong? Here's the checklist I was using (to no avail) for troubleshooting...

Ensure that names are observable.
Ensure that editing is observable.
Ensure that my edit function sets editing to true.
Ensure that editing defaults to false
Ensure that <input> has a value binding.
Ensure that  has a text binding.
Ensure that that event handlers are bound to the value of editing

JSBin:  http://jsbin.com/fehoq/117/edit

JS
function StudentModel(fullName) {
    var _this = this;
    this.fullName = ko.observable(fullName);
    this.editing = ko.observable(false);
    this.edit = function() {
        _this.editing(true);
        console.log(_this.editing());
    };
    ...
}

HTML

          <input data-bind="value: fullName()  + ' ' + ($index() + 1), visible: editing(), hasFocus: editing()"/>

...

A:

You would want to bind hasFocus against the observable itself, so that the false value can get written back to it.  So, you would want:
hasFocus: editing rather than hasFocus: editing()
In the latter, the binding only receives the value and has no way to get back to the observable to write to it.


Q:

Set "Selected Item" in multiselect RadComboBox

Is there any way we can set Selected Items or Checked Items in a multiselect RadComboBox ?. I want to set value on postback from server.
I tried following code but that works only if it is not a multiselect RadComboBox.
Radbox1.SelectedValue = "123"
My front end code.
<telerik:RadComboBox ID="Radbox1" runat="server" CheckBoxes="true" EnableCheckAllItemsCheckBox="true"
    Width="300" Height="200" AutoPostBack="True" OnSelectedIndexChanged="Radbox1_SelectedIndexChanged" />
I have value in Radbox1 which will be populated from database.
Thanks,
Rahul

A:

When the Radcombobox is set to allow multiple selections via the checkboxes, you must use each items checked property.
I use a list here to simulate the items that I wish to have marked on postback. You could have this list pre-populated or it could even be loaded from a database:

A:

protected void RadComboBox1_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
{
    if ("YourString" == e.Item.Text))
    {
        e.Item.Checked = true;
    }
}

Or
protected void RadComboBox1_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
{
    List<String> yourStringList = new List<String>() {"string1","string2"};
    if (yourStringList.Contains(e.Item.Text))
    {
         e.Item.Checked = true;
    }
}

A:

I've done something like this; Machine_Serial_Numbers is a telerik:RadComboBox;
foreach (var machine in bulletinData.Machines)
        {
            var comboItem = Machine_Serial_Numbers.FindItemByValue(machine.Id.ToString());

            if (comboItem != null)
            {
                comboItem.Checked = true;
            }
        }

This worked for me.


Q:

React JS. Передать класс случайному элементу массива

Всем здоровья! Подскажите, плиз, как организовать условие, чтобы показать не все картинки, а одну - рандомно. Кстати, даже так все не показываются, выдает ошибку: "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop"... как быть?
    let [blockClass, setBlockClass] = useState("");

    let imageElements = props.images.map((image, i) => {
        return <img key={image.id} src={image} className={classNames(style.img, style[blockClass])}
                    id={style[`img` + i]} alt=""/>
    });

    let showImage = () => {
        setBlockClass("block");
    };

A:

Код стоит приводить полностью.
import React from "react";

export default function App() {
  const [items] = React.useState([1,2,3,4,5])
  const [random] = React.useState(Math.floor(Math.random() * items.length) + 1 )

  return (

Hello random

{items[random]}

  );
}


Q:

Proof that there is a bijection, if there are injective maps in both directions

Let $A$ and $B$ be two sets.
Let $f:A\to B$ be injective such that $Im(f) \subsetneq B$.
Let $g:B\to A$ be injective such that $Im(g) \subsetneq A$.
Obviously $A$ and $B$ are not finite sets. Can we guarantee an existence of a bijection between $A$ and $B$?

A:

Yes. In fact, one can show that if there is an injective function from $A$ to $B$ and   an injective function from $B$ to $A$, then there is a bijection from $A$ to $B$. This is known as the Cantor–Bernstein–Schroeder theorem. (Of note is that its proof does not depend on the Axiom of Choice.)


Q:

Why WriteXml create a new xml file

I try to use ReadXml and WriteXml to load/save a xml file in datagrid, but the WriteXml method just create a new empty file instead of save changes to the old one. For details: [Link][1]
----------------------------------update----------------------------------------
    private void RefreshModule()
    {
        ModulesView = new ListCollectionView(sdb.GetModules())
        {
            Filter = obj =>
            {
                var Module = (Module)obj;
                return SelectedProduct != null && SelectedProduct.ModelNumber == Module.ModelNumber;
            }
        };
    }

    private Product selectedProduct;
    public Product SelectedProduct
    {

        get { return selectedProduct; }
        set
        {
            if (selectedProduct != value)
            {
                selectedProduct = value;
                NotifyPropertyChanged();
                RefreshModule();
             }
         }
     }

A:

The SaveDataSet method of your StoreDbDataSet class should take a DataSet parameter and serialize this one to the file.
public void SaveDataSet(DatatSet ds)
{
    ds.WriteXmlSchema(DatabaseConstructorName);
    ds.WriteXml(DatabaseFileName);
    ds.AcceptChanges();
}

But how are you supposed to be able to serialize a DataSet if you set the ItemsSource property of the DataGrid to an ObservableCollection?
Return the DataSet from your GetModules method:
public DataSet GetModules()
{
    return StoreDbDataSet.ReadDataSet();
}

And bind to the DataView of the DataTable. Something like this:
private DataSet _ds;
private void RefreshModule()
{
    _ds = sdb.GetModules();
    ModulesView = new ListCollectionView(ds.Tables["Modules"].DefaultView)
    {
        Filter = obj =>
        {
            var Module = obj as DataRowView;
            return SelectedProduct != null && SelectedProduct.ModelNumber == Module["ModelNumber"].ToString(); //ModuleNumber is the column name in the DataTable
        }
    };
}

private void Writecfg_Button_Click(object sender, RoutedEventArgs e)
{
    StoreDbDataSet sdb = new StoreDbDataSet();
    sdb.SaveDataSet(_ds);
}


Q:

Crashlytics - How to add Custom Keys - Eclipse

I am trying to work with Crashlytics. The setup is done with eclipse and the sessions are logging in fine. But the sessions are get logged for Activities. For ex., com.xxx.xx.MainActivity, com.xxx.xx.SplashActivity and so on. What should i do to make Custom Event logs? For ex., log the event when user clicks on a button in an activity?
I tried
Crashlytics.log(0, "MainActivity", "Button Clicked");
Crashlytics.setString("MainActivity", "logged_in");
but i don't see any reports in my dashboard with name "MainActivity" or "Button Clicked" or "logged_in". Is there a way to set these custom events?

A:

I don't believe Crashlytics has that capability yet. I asked support in late November about this and they said that is was on the roadmap. This is a quote from one of their support emails.

Custom events is definitely on our roadmap for Answers, the team is heads down on it right now.

You may have to use another provider for now until they implement this.


Q:

Why is the waitUntil method protected for ElementsCollection?

As you can see in the documentation, the waitUntil method is protected for ElementsCollection:
http://selenide.org/javadoc/3.7/com/codeborne/selenide/ElementsCollection.html
This is not the case for SelenideElement for example:
http://selenide.org/javadoc/3.7/com/codeborne/selenide/SelenideElement.html
Why is the method protected for ElementsCollection?

A:

I think the idea behind this is that it make sense to apply waitUntil + visible/disappear/hasText/etc. Condition combination for single element, but totally useless to collection of elements and potentially buggy.
There is no way to set how many elements should disappear or should appear while you are waiting, taking in account performance cost it may bring - that was the right decision.


Q:

How to let ES not score on should cause

i am just using ES to filter out some data, not need score function at all. but there are some or logic i have to include. i know we can replace must with filter, so ES will not score it and may cache it. How to profile should cause?
it this two query have different?
{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "term": {
                  "closeStatus": 0
                }
              },
              {
                "bool": {
                  "must_not": {
                    "exists": {
                      "field": "closeStatus"
------------------------------------------------
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "closeStatus": 0
          }
        },
        {
          "bool": {
            "must_not": {
              "exists": {
                "field": "closeStatus"

A:

If you don't care about the score, use constant_score query:
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "closeStatus": 0
              }
            },
            {
              "bool": {
                "must_not": {
                  "exists": {"field": "closeStatus"}
                }
              }
            }
          ]
        }
      }
    }
  }
}


Q:

Apple Mach-O Linker (id) Error - undefined symbols for architecture i386

I know this type of error has been raised many times before, but I have not found solution of my error. I am using xcode 4.0. I downloaded ASIHTTPRequest zip and copied classes folder along with two files of 'Reachability". After compilation, it is giving me strange errors which I can't figure out. Below I copied text of error for undefined symbols for architecture i386.
Ld /Users/svp/Library/Developer/Xcode/DerivedData/Manual_BeforePres2-fahkeiivemkgpubswgvzglvndszw/Build/Products/Debug-iphonesimulator/Manual.app/Manual normal i386
cd "/Users/svp/Desktop/Manual nav before pres 2"
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/svp/Library/Developer/Xcode/DerivedData/Manual_BeforePres2-fahkeiivemkgpubswgvzglvndszw/Build/Products/Debug-iphonesimulator -F/Users/svp/Library/Developer/Xcode/DerivedData/Manual_BeforePres2-fahkeiivemkgpubswgvzglvndszw/Build/Products/Debug-iphonesimulator -filelist /Users/svp/Library/Developer/Xcode/DerivedData/Manual_BeforePres2-fahkeiivemkgpubswgvzglvndszw/Build/Intermediates/Manual_BeforePres2.build/Debug-iphonesimulator/Manual.build/Objects-normal/i386/Manual.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -lz -framework SystemConfiguration -framework CFNetwork -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/svp/Library/Developer/Xcode/DerivedData/Manual_BeforePres2-fahkeiivemkgpubswgvzglvndszw/Build/Products/Debug-iphonesimulator/Manual.app/Manual

 Undefined symbols for architecture i386:
"_UTTypeCreatePreferredIdentifierForTag", referenced from:
  +[ASIHTTPRequest mimeTypeForFileAtPath:] in ASIHTTPRequest.o
"_UTTypeCopyPreferredTagWithClass", referenced from:
  +[ASIHTTPRequest mimeTypeForFileAtPath:] in ASIHTTPRequest.o
"_kUTTagClassFilenameExtension", referenced from:
  +[ASIHTTPRequest mimeTypeForFileAtPath:] in ASIHTTPRequest.o
"_kUTTagClassMIMEType", referenced from:
  +[ASIHTTPRequest mimeTypeForFileAtPath:] in ASIHTTPRequest.o
ld: symbol(s) not found for architecture i386

collect2: ld returned 1 exit status

Also it is giving me a warning in ASIAuthenticationDialog.m file:
ASIAuthenticationDialog may not respond to _presentingViewController

Please anyone tell me what are these errors and warning for? What am I doing wrong? I have wasted many hours over it :(
EDIT:
Code for warning in ASIAuthenticationDialog.m file:
#import "ASIAuthenticationDialog.h"
#import "ASIHTTPRequest.h"

#pragma mark show / dismiss

+ (void)dismiss
{
if ([sharedDialog respondsToSelector:@selector(presentingViewController)])
    [[sharedDialog presentingViewController] dismissModalViewControllerAnimated:YES];
else
    [[sharedDialog parentViewController] dismissModalViewControllerAnimated:YES];
}

A:

If you were to look up the missing symbols in the documentation, you would find them listed along with the framework where they are located.  For example, UTTypeCreatePreferredIdentifierForTag says it is located in the MobileCoreServices.framework.  (The others may be there too; I didn't look for all of them.)  Add the necessary framework(s) to the link library step of your target's build phases and the symbols should be resolved.
As for the warning, please show the code where it's happening.


Q:

How associativity holds on set of all bijective functions on a finite set?

I came across following statement:

The set of all bijective functions on a finite set forms a group under function composition.

The proof was given as follows:

We can have identity function as $\{(1,1),(2,2),(3,3),(4,4)\}$.
  Since function is bijective and mapping to same set, we can have an inverse for any function by inverting the relation (changing the mapping $a\rightarrow b$ to $b\rightarrow a$).
  Since the function maps to the same set, it must be closed and associative also.

I was thinking is associativity really holds in above set. For example, consider the finite set: $\{1,2,3,4\}$ and two bijective functions $f_1$ and $f_2$ as follows:

Now, $f_1(f_2(1))=f_1(3)=3$ and $f_2(f_1(1))=f_2(2)=1$.
So, I feel its not bijective. Am I incorrectly evaluating associativity?

A:

Your example shows that compostion is not commutative. It has nothing to do with being associative.


Q:

CSS font-size in pixels: what does it meaure?

CSS has font-size that can use "px" pixels.  But what exactly is being measured to be the given pixels?
Take 14px, does that mean that no letter will be over 14 pixels?  Is that the average size of the letter heights? Is that the measurement of the tallest letter?  Or is it an altogether different measure?

A:

A font usually contains other characters than Latin letters. Some of them will reach above the tallest ascenders or below the deepest descenders of the Latin letters. So the font size specifies the height of the character box in which all possible glyphs in the font must fit. Latin letters may or may not utilise the full extent of that box.