Google Analytics PHP API : get reporting

I have a professional website using Google Analytics for metrics and I try to automatize one task I used to do manually but.. not able to understand if it's possible ?!

I just began to using the Google PHP client library to access the Google Analytics API on my website Test with the HelloAnalytics.php file is OK, I manage to connect and retrieve my data.

What i'm trying to do is :

Get all URLs viewed in the past 24H (what you can see when you navigate in the GA dashboard -> Behavior -> Site content -> All pages)

Combine those datas with my custom Definition which is in fact a special token i generate for every users on my website via PHP, then send it thought with Javascript and ga('set', 'mycustomdefinition', 'my token');

Is it possible ?
Many thanks in advance for your support !


How to center a bootstrap well?

I can't seem to get this well to align with the center of the page. It seems like it should be easy but I can't figure it out.


How to display "arrow" emoji in android

I was using TextView to display strings contain emoji characters. This worked for most emojis. However, for the "Right Arrow Curving Left" emoji (U+21A9), android seems to have two styles of this character:

 and

If I directly render this in a TextView using the following code,

    View.setText(new String(Character.toChars(0x21A9)));

The second style is displayed. Any idea how to let it display the first one?


Reputation points deducted 'Serial Voting Revese'

Why is it happening that my reputation point were reversed saying 'Serial Voting Reversed'.

I don't think this is a fair play with a member who is helping community and spending his time and effort. At the end he is getting this treatment.

Any idea how to avoid this?


Adobe Edge Animate and d3.js: d3.scale.range([value]) not working properly in Chrome and Safari

I'm trying to create a bar chart using Adobe Edge Animate and d3.js.

I'm having some difficulties with how the different browsers displays the axes. Here is a link to a d3 chart only containing axes and no data (the code is in d3example2_edgeActions.js):

http://www.nyhetsgrafikk.no/demo/d3example2/d3example2.html

Mozilla Firefox and Opera: everything works

Chrome and Safari: ticks are stacked on top of each other to the left

I believe this has to do with d3.scale.range([value]) not working properly - all though it does set the range of the chart (when I change the range and run the code my chart is changed), the ticks are stacked on top of each other. Chrome is not returning any errors. Any ideas to how I can fix this?


Dagger 2 Inject Child Class

I understand that with Dagger 2 I cannot inject in a base class and expect it to carry over to the child class. But why can I not call inject inside of a child class unless I explicitly have an inject method for that class?

I tried following the example in this article: Dagger 2: Even Sharper, Less Square. This solution should allow me to call inject in a subclass, but when I test it I get a NullPointerException for all of my @Inject targets.

public abstract class BaseFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        injectComponent(MyApplication.getComponent());
    }

    protected abstract void injectComponent(AppComponent component);
}

public class MyFragment extends BaseFragment {

    @Inject MyDependency mDependency;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
        mDependency.doSomething(); // NullPointerException
        ...
    }

    ...

    @Override
    public void injectComponent(AppComponent component) {
        component.inject(this);
    }
}

Is there another way to inject into each subclass without creating an inject method for each an every class? Or is that the only way Dagger 2 will work? If that is the case, I will end up with an absurdly long Component class. With an inject method for every Activity, Fragment or various other helper classes:

@Singleton @Component(modules = {AppModule.class})
public interface AppComponent {

    void inject(MyClass clazz);

    void inject(MyClass2 clazz);

    ...

    void inject(MyClassN clazz);
}

I would much rather have to call component.inject() in every class, than have to do that along with another inject method.

Although similar, I do not believe my question is a duplicate Dagger 2 Activity Injection Not Working. That question asks why the injection was not working, to which the answer would be: because Dagger 2 has a strong type-association and you must declare an inject method for each and every class. This question focuses more on a way around the boilerplate, while hopefully maintaining strong type-association.


How to add JSF Implementation Libraries?

I'm using TomEE. I was under impression that TomEE already has the JSF IMplementation Libraries.

So when create an Eclipse project, I follow the documentation and choose Library Provided By Target Runtime

It reads this facet requires jsf implementation library to be present on project classpath. By disabling library configuration, user takes on responsibility of configuring classpath appropriately via alternate means

So I go ahead and add all the bundled jars that come with TomEE ...\apache-tomee-webprofile-1.7.4\lib (this includes myfaces-api-2.1.17.jar and myfaces-impl-2.1.17.jar)

Then I Run on Server the following test xhtml . But it renders a blank page. Obviously, the xhtml was not compiled. So the bundled TomEE jars did NOT kick in. How can I make those bundled TomEE jars compile my test xhtml ?

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:a="http://xmlns.jcp.org/jsf/passthrough">

    <h:head>
        <title>Hello World - Input Form</title>
    </h:head>
    <h:body>

        <h:form>
            <h:inputText id="name" value="#{theUserName}"
                            a:placeholder="What's your name?" />

            <h:commandButton value="Submit" action="myresponse" />
        </h:form>

    </h:body>
</html>


How to validate 17 digits in array of VIN numbers from form in php?

I have the following validation code that runs after my form is submitted:

foreach ($_POST['vin']) as $vin_value ) {
if(strlen($vin_value) != 17) {
echo "VIN is not 17 digits";
echo "VIN is " . strlen($vin_value) . " digits";
echo "VIN value is: " . $vin_value;
} else {
mail($admin_email, "Auto Quote Request", $email_body);
echo "Thank you for contacting us!";
}

}

I am trying to make sure the individual vin's ($vin_value) of my vin[] array are exactly 17 digits.  Right now when I submit the form no message is displayed at all.  What's going on here??  And I realize this code just checks for characters, not digits.  Thanks.

html form input:

<div class="form-group">
  <label for="inputVIN" class="col-lg-2 control-label">Vehicle Identification Number</label>
  <div class="col-lg-10">
    <input class="form-control" id="inputVIN" placeholder="Must be 17 digits." type="text" name="vin[]">

  </div>
</div>

The input is an array. This is to accommodate the possibility of multiple vin numbers. There is an option to add another form field with the name of vin[]. All the inputs relevant to this question have name="vin[]" . To reiterate, at first there is one form group with name=vin[], but the user can click a button to add more. This is why I am using an array in the first place. So I want each element in the array (the $vin_value)to contain exactly 17 characters. That is why I am using a foreach. I hope that provides enough context.


Cannot retrieve django serialized json using javascript

Hi I am parsing serialzed json -

def wall_copy(request):
    posts = user_post.objects.order_by('id')[:20].reverse()
    posts_serialized = serializers.serialize('json', posts)
    return JsonResponse(posts_serialized, safe=False)

and trying to get data as-

$(document).ready(function()
    {
            setInterval(function()
        {
            var xhr = new XMLHttpRequest();
            xhr.open("GET","http://10.8.21.17:8000/wall/wall_copy/",false);
            xhr.send(null);
            var data = JSON.parse(xhr.responseText);
            //alert(xhr.status+' '+xhr.statusText);
            for(i=0; i<20; i++)
            {
                alert(data[i].post_content);
            }
                }, 3000);
    });

But the problem is that every time it alerts as 'Undefined'. I checked the url and the server is sending json data but I am unable to fetch it.

Json data-

"[{\"fields\": {\"post_id\": \"rahularyan06:16PM on February 26, 2015\", \"posted_by\": \"rahularyan\", \"post_content\": \"koi nhi re\", \"time_of_post\": \"2015-02-26T18:16:00Z\"}, \"model\": \"wall.user_post\", \"pk\": 77}, {\"fields\": {\"post_id\": \"aquaman06:00PM on February 26, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"kuch nhi\", \"time_of_post\": \"2015-02-26T18:00:44Z\"}, \"model\": \"wall.user_post\", \"pk\": 76}, {\"fields\": {\"post_id\": \"rahularyan06:00PM on February 26, 2015\", \"posted_by\": \"rahularyan\", \"post_content\": \"kya hua??\", \"time_of_post\": \"2015-02-26T18:00:04Z\"}, \"model\": \"wall.user_post\", \"pk\": 75}, {\"fields\": {\"post_id\": \"aquaman12:01AM on February 26, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"lelo\", \"time_of_post\": \"2015-02-26T00:01:14Z\"}, \"model\": \"wall.user_post\", \"pk\": 74}, {\"fields\": {\"post_id\": \"aquaman10:41AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"sahi me lega??\", \"time_of_post\": \"2015-02-25T10:41:43Z\"}, \"model\": \"wall.user_post\", \"pk\": 73}, {\"fields\": {\"post_id\": \"aquaman10:41AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"sahi me lega??\", \"time_of_post\": \"2015-02-25T10:41:34Z\"}, \"model\": \"wall.user_post\", \"pk\": 72}, {\"fields\": {\"post_id\": \"shreyansh10:41AM on February 25, 2015\", \"posted_by\": \"shreyansh\", \"post_content\": \"yo\", \"time_of_post\": \"2015-02-25T10:41:17Z\"}, \"model\": \"wall.user_post\", \"pk\": 71}, {\"fields\": {\"post_id\": \"aquaman10:40AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"muh me lega??\", \"time_of_post\": \"2015-02-25T10:40:53Z\"}, \"model\": \"wall.user_post\", \"pk\": 70}, {\"fields\": {\"post_id\": \"aquaman10:40AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"bc\", \"time_of_post\": \"2015-02-25T10:40:42Z\"}, \"model\": \"wall.user_post\", \"pk\": 69}, {\"fields\": {\"post_id\": \"shreyansh10:40AM on February 25, 2015\", \"posted_by\": \"shreyansh\", \"post_content\": \"lele\", \"time_of_post\": \"2015-02-25T10:40:28Z\"}, \"model\": \"wall.user_post\", \"pk\": 68}, {\"fields\": {\"post_id\": \"aquaman10:39AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"kya bhai??\", \"time_of_post\": \"2015-02-25T10:39:39Z\"}, \"model\": \"wall.user_post\", \"pk\": 67}, {\"fields\": {\"post_id\": \"aquaman10:38AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"sb mast\", \"time_of_post\": \"2015-02-25T10:38:22Z\"}, \"model\": \"wall.user_post\", \"pk\": 66}, {\"fields\": {\"post_id\": \"shreyansh10:38AM on February 25, 2015\", \"posted_by\": \"shreyansh\", \"post_content\": \"or baaki??\", \"time_of_post\": \"2015-02-25T10:38:05Z\"}, \"model\": \"wall.user_post\", \"pk\": 65}, {\"fields\": {\"post_id\": \"aquaman10:03AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"badiya\", \"time_of_post\": \"2015-02-25T10:03:39Z\"}, \"model\": \"wall.user_post\", \"pk\": 64}, {\"fields\": {\"post_id\": \"shreyansh10:03AM on February 25, 2015\", \"posted_by\": \"shreyansh\", \"post_content\": \"thik ba\", \"time_of_post\": \"2015-02-25T10:03:23Z\"}, \"model\": \"wall.user_post\", \"pk\": 63}, {\"fields\": {\"post_id\": \"aquaman10:00AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"kaisan??\", \"time_of_post\": \"2015-02-25T10:00:30Z\"}, \"model\": \"wall.user_post\", \"pk\": 62}, {\"fields\": {\"post_id\": \"aquaman10:00AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"hi\", \"time_of_post\": \"2015-02-25T10:00:04Z\"}, \"model\": \"wall.user_post\", \"pk\": 61}, {\"fields\": {\"post_id\": \"aquaman09:58AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"abe jldi likh\", \"time_of_post\": \"2015-02-25T09:58:43Z\"}, \"model\": \"wall.user_post\", \"pk\": 60}, {\"fields\": {\"post_id\": \"aquaman09:57AM on February 25, 2015\", \"posted_by\": \"aquaman\", \"post_content\": \"hello\", \"time_of_post\": \"2015-02-25T09:57:49Z\"}, \"model\": \"wall.user_post\", \"pk\": 59}, {\"fields\": {\"post_id\": \"shreyansh09:39AM on February 25, 2015\", \"posted_by\": \"shreyansh\", \"post_content\": \"lele\", \"time_of_post\": \"2015-02-25T09:39:39Z\"}, \"model\": \"wall.user_post\", \"pk\": 58}]"

Help me how can I get this data through javascript.

Thanks in advance.


sorl-thumbnail: resize original image before saving?

Using sorl-thumbnail v11.01 and an ImageField on my model is there a simple way to have an uploaded file resized before saving it (to avoid saving a massive image, in case one has been uploaded)? Thanks in advance.


MySQL Failover error "Missing gtid_executed system variable"

I have done a GTID replication in MySQL 5.7.18, I have setup the fail over both cluster_manager and slave health is good. When I am trying to down cluster manager I am getting this error.

Failover starting in 'auto' mode...
  2017-05-29 14:53:56 PM CRITICAL The server IP :3306 does not comply to the latest GTID feature support. Errors:
      Missing gtid_executed system variable.

So I googled, they were telling to check global variable and variable which I don't understand. This is my cluster manager status of gtid_exe

mysql> show variables like '%**gtid_exe%'**;

+----------------------------------+-------+
| Variable_name                    | Value |
+----------------------------------+-------+
| gtid_executed_compression_period | 1000  |
+----------------------------------+-------+
1 row in set (0.00 sec)

mysql> show global variables like '%**gtid_exe%**';

+----------------------------------+-------------------------------------------------+
| Variable_name                    | Value                                           |
+----------------------------------+-------------------------------------------------+
| **gtid_executed**                | c6b90b56-4084-11e7-8af7-00163e4da2ba:1-26006378 |
| gtid_executed_compression_period | 1000                                            |
+----------------------------------+-------------------------------------------------+
2 rows in set (0.01 sec)


Inserting a line of text at the beginning of an Access export

I would like to export Access query results to a text file with some added string in the first line of exported file.

Specifically, I would like to combine a text string:

 *Abc def

with the Access query results (tab delimited):

DoCmd.TransferText acExportDelim, "Export_spec", "Export", "C:\export.txt", True, ""

and then save it as a text file.

The text string have to be in the first line of the text file, followed by access query results.

The results should looks like:

*Abc def
Header1 Header2 Header3 Header4 ...
Value1 Value2 Value3 Value4 ...
... ... ... ... ...


Is this a good architecture / design concept for handling/manipulating file uploads?

I'm looking at adding multi-file uploading to our ASP.NET MVC web application. I am going to use the 3rd Party Multi-File uploader Aurigma to handle the actual uploading.

Once each file is 100% received by the web server, it needs to be checked for the following

is it an image or video.

if it's an image, does it need to be resized? if so, resize.

if it's a video, we need to re-encode it to flash (unfortunately.. bring on html5 :) )

finally, store on S3 amazon.

So i know how to do most of steps 1 to 4 - that's not the question.

My question is: how should I really be handling this workflow? Especially if i get a bulk of media at once -> after all, this is a multi-file uploader :) I don't want to have lots of media getting processed at once (eg. 5 video's getting encoded to flash..).

So I thought i might have MSMQ installed and when each file gets 100% recieved, then pop it into MSMQ. That way, only one item is getting processed at once. The cost of this, is that if there's a lot of expensive processing, the queue might actually start to get a few items in there ... and there will be some waiting period from the time an item is uploaded to the site, until it's actually 100% processed. We can easily handle this in the UI to tell them it's not finished yet.

So - does this sound like an OK way to handle this problem?

Secondly, this is in a web farm scenario .. so installation / deployment / maintenance needs to be considered.

Would love to see what other people are thinking.


Curl header request returning 404 but body returning 200

I'm sending a header request with curl using the following code

function getContentType($u)
{
    $ch = curl_init();
    $url = $u;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.12011-10-16 20:23:00");

    $results = split("\n", trim(curl_exec($ch)));
    print_r($results);
    foreach($results as $line) {
        if (strtok($line, ':') == 'Content-Type') {
            $parts = explode(":", $line);
            return trim($parts[1]);
        }
    }
}

For most websites it is returning correctly, although for some servers it is returning a 404 error when the page is actually available. I'm assuming this is because the servers have been configured to reject the header request.

I'm looking for a way to bypass this server header request rejection, or a way to tell if the header request has been rejected and is not in fact 404.


Efficient approach to load XML and read it when needed using c#/.net 3.5

I want to know the efficient way to store the configuration xml to be used in the program. I want to load the following config xml into memory as soon as I start the program and then use the properties where needed.
XML:

<ViewModelConfiguration>
  <FICallSchedule>
    <Model>
      <Details>
        <DataSource>
          <Dataset se-datafilter="callschedule" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" />
          <XmlData></XmlData>
        </DataSource>
        <ComputePercentage isactive="true" dataorientation="horizontal">
          <column source="value1" destination="value3" datafilter="" />
          <column source="value2" destination="value4" datafilter="" />
        </ComputePercentage>
      </Details>
    </Model>
  </FICallSchedule>
</ViewModelConfiguration>

Currently I am reading the main tags like <Dataset> and load all the attributes of it in dictionary object. And then use that dictionary with key in my code. Similarly I do it for ComputePercentage and so on and so forth.

I was wondering if I can load the complete XML into some object and access each node or attribute something like: Model.Details.Dataset.DataSource.se-datafilter or Model.Details.ComputePercentage which will return a collection of columns. I am not sure if this makes any sense otherwise I would stick to dictionary objects only.


jQuery UI Datepicker hiding previous months

I'm trying to create 12 months jquery UI Datepicker with date range selection.
I'm using

numberOfMonths: [12,1],

which is working fine
Problem is when i try to select two dates between two months (March,15,2016 to April,15,2016) calendar wills start from April i cant edit previous month dates, i want to keep 12 months in every condition in short i need 12 months jquery datepicker which can select two dates. my code is

<div id="jrange" class="dates">
          <input type="text" id="startDate" size="10" placeholder="9 Mar" readonly>
          <span id="spaceDash">&#8211;</span>
          <input type="text" id="endDate" size="10" placeholder="10 Mar" readonly>
          <div></div>
        </div>
$(document).ready(function(){
$("#jrange div").datepicker({
  minDate: 0,
  numberOfMonths: [12,1],
  dateFormat: "MM dd",
  showMonthAfterYear: true,
  beforeShowDay: function(date) {
    var date1 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#startDate").val());
    var date2 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#endDate").val());
    return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];

  },
  onSelect: function(dateText, inst) {
    var date1 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#startDate").val());

    var date2 = $.datepicker.parseDate($(this).datepicker("option", "dateFormat"), $("#endDate").val());
    if (!date1 || date2) {
            $("#input1").val(dateText);
            $("#input2").val("");
            $(this).datepicker("option", "minDate", dateText);
        } else {
            $("#input2").val(dateText);
            $(this).datepicker("option", "minDate", null);
        }
    }
});


Change color of an anchor when clicked

i want that when i click this link its color changes to the given color

<li id="press"><a href="<?=base_url()?>index.php/page/press">Press</a></li>


Storing and querying location (coords) in PostgreSQL

In my user schema I have a location column which will hold the last updated coordinates of the user. Is there a PostgreSQL data type I could use to allow me to run SQL queries to search, for example something like: SELECT username FROM Users WHERE currentLocation="20 Miles Away From $1"


What's a good shuffle percentage?

I'm basically new to coding for random results, but did some reading and tested out the javascript version of the Fisher-Yates algorithm (as seen on wikipedia), with an ordered list.

I ended up adding code to make sure the array was shuffled differently than its initial order, and also calculated the percentage of how many objects were shuffled to a different position by the algorithm.

So I'm wondering what might be considered a good result.  Kind of a generic question.  If I shuffled a deck of cards, what would be the least acceptable amount of shuffle?  Right now I have mine coded to repeat the algorithm if it comes out less than 25 percent shuffled.

What do you think?


How to migrate database from SAP DB to PostGres?

Any idea how to go about doing that through a tool(preferred). Any alternate ways to do that.


how to integrate Paypal Express checkout using new method?

I want to integrate PAYPAL EXPRESS CHECKOUT in my project. I think PAYPAL has upgraded the APIs and its methods. I downloaded REST API from Github but I am not able to figure out how to integrate it. All i get is confused. Because in that REST zip I downloaded there are so many files and I was not able to understand how can i integrate express checkout with the new API and method. Also I have gone through many of the sites with the examples but as soon as I execute them I get an error 10001. Please help.


ng-flow - no destination directory option

I am using ng-flow in my application and it works pretty well. Currently, the destination directory for the files being uploaded is set in my web.config and used within my webapi controller method.

What I want to do is allow the user to specify the destination, rather than it come from config. However, looking at the docs, I don't see an option that I can add to the below appconfig for this:

function appConfig(flowFactoryProvider) {
flowFactoryProvider.defaults = {
    target: 'api/upload',
    permanentErrors: [404, 500, 501],
    maxChunkRetries: 1,
    chunkRetryInterval: 5000,
    simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
    console.log('catchAll', arguments);
});

}

Am i missing something or do I need to handle this myself?


spark embedded (same JVM) for <400k text file process

Can we do a mini spark job embedded in our app? Any example? Reason : want to process part of a file and give results quicker than submitting a regular job. File is only 500 lines. But do not want to keep 2 code bases - just the one that is used for the large files too. File size is less than an MB.

I want to process the file in the same JVM that my client code is running. Want a single executor kicked off from within same JVM, via a flag in the config. (so a few jobs will have this flag set and others wont. Those that do not will run as usual on the cluster.)


Can I configure settings in UWP app desktop scanner?

I have had good success in getting input from a flatbed scanner in my UWP app

using Windows.Devices.Enumeration;
using Windows.Devices.Scanners;

ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);
var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Default, folder);

and even make use of the auto configured scan profile

if (myScanner.IsScanSourceSupported(ImageScannerScanSource.AutoConfigured))
{
    ...
    // Scan API call to start scanning with Auto-Configured settings.
    var result = await myScanner.ScanFilesToFolderAsync(
        ImageScannerScanSource.AutoConfigured, folder).AsTask(cancellationToken.Token, progress);
    ...
}

but is there any way that I can control the configuration, get a lower resolution or just B&W? All of the format options appear to be read only properties. I have tried to make an external scanner profile in Win10 but it isn't picked up (even when it is the default). The API appears to be aware of the scanner supported settings because the ScanToStream equivalent call reads in lowest possible resolution as a preview.


MySQL - Delete a selection

I am trying to delete all the accounts associated with IPs that are used more than two times in my MyBB database. The following code works to "select" these users.

SELECT * FROM `mybb_forumusers` WHERE `regip` IN (
    SELECT `regip` FROM `mybb_forumusers`
    GROUP BY `regip`
    HAVING COUNT( `regip` ) > 2
)

However, I cannot successfully delete all of these users without getting errors. I have tried the following (and variations):

DELETE FROM `mybb_forumusers` WHERE `uid` IN (
    SELECT `uid` FROM `mybb_forumusers` WHERE `regip`IN (
        SELECT `regip` FROM `mybb_forumusers`
        GROUP BY `regip`
        HAVING COUNT( `regip` ) > 2
    )
)


Autolayout ambiguity with inequalities

I'm confused about how Cocoa's Autolayout determines whether a layout is ambiguous. Here's a simple example:

The observed behavior is as follows. The spacers to the left and right of the green rectangle are always the same width. When you stretch the superview horizontally outwards, the spacers stick to 80 while the rectangle expands. When you shrink the superview horizontally, the rectangle sticks to 398 while the spacers shrink to 10, after which the rectangle continues to shrink. At no point is the layout labeled ambiguous by IB.

However, you'll notice that the horizontal layout is defined almost entirely by inequalities! From what I can see, when the rectangle has a width of > 398, there's no reason for the spacers to have a width of 80. They could have a width of anywhere from 10 to 80 and still satisfy each horizontal inequality. That sounds ambiguous to me, but IB clearly does not agree.

There must be some implicit rule I'm missing. Please help me out!


Javasript onclick not working

I tried a whole bunch of things from:

It works in normal browser. Does not work on mobile.

However nothing seems to work.

I tried to do it in different ways but I could not make it. I am waiting for help from friends who have knowledge about the subject.

Here's what I have:

 function processAjax(kat,div)
  {
if(div==1)
{
$('#DivCat1').hide('slow', function() {});
$('#DivCat2').hide('slow', function() {});
$('#DivCat3').hide('slow', function() {});
$('#DivCat4').hide('slow', function() {});
$('#DivCat5').hide('slow', function() {});
$('#DivCat6').hide('slow', function() {});
$('#DivCat7').hide('slow', function() {});
}
if(div==2)
{
$('#DivCat3').hide('slow', function() {});
$('#DivCat4').hide('slow', function() {});
$('#DivCat5').hide('slow', function() {});
$('#DivCat6').hide('slow', function() {});
$('#DivCat7').hide('slow', function() {});
}
if(div==3)
{
$('#DivCat4').hide('slow', function() {});
$('#DivCat5').hide('slow', function() {});
$('#DivCat6').hide('slow', function() {});
$('#DivCat7').hide('slow', function() {});
}
if(div==4)
{
$('#DivCat5').hide('slow', function() {});
$('#DivCat6').hide('slow', function() {});
$('#DivCat7').hide('slow', function() {});
}
if(div==5)
{
$('#DivCat6').hide('slow', function() {});
$('#DivCat7').hide('slow', function() {});
}
if(div==6)
{
$('#DivCat7').hide('slow', function() {});
}
if(div==7)
{
$('#DivCat8').hide('slow', function() {});
}
$('#DivCat'+div).show('slow', function() {});
$('#DivCat'+div).load('katgetir.php?kat='+kat+'&div='+div);

$('#change').animate({scrollLeft : 500},'slow');
}

<select multiple class="form-control">

  <option id="45" onclick="processAjax(45,1)">Kat</option>

</select>

What might I be doing wrong?

How do I get this code to work on mobile too?


jenkins - error while deploying tomcat war - curl: (56) Recv failure

I setup jenkins on one ec2 machine & deploying war file on second ec2 machine. from jenkins when I am sending following command.

http://username:password@ec-machine-address:8080/manager/text/undeploy?path=/

jenkins running in infinite loop. When I try same command on terminal I receive following error.

curl: (56) Recv failure: Connection reset by peer

It was working fine some time back & I deployed war  6-7 times. But suddenly I am receiving this error. I dont think, I change in jenkins setup. So maybe this is something to do with server blocking request from jenkins ec2. Not sure though whats problem.


how to fix the precision for lat/lng?

with the v2 version we can fix the precision with toFixed
example: point.y.toFixed(4)
how can we do with the v3 version ?


Docker image for TFS Xamarin Android build agent?

We are building Xamarin.Android projects on TFS (on-premise).

With every Visual Studio / Android SDK update we have to update all our build agents.
Is there a way to simplify this process?

There are some  vsts-agent images available, but none of them are for xamarin. There are some xamarin-related images, but they are a bit out of date (and not related to TFS).

Is there anything I'm missing? Any other solutions to the problem?


YouTube Embed feature for looping single videos isn't working

Loop feature is not working.Example


How to stop the UIScrollView get touch events from its parent view?

I have a UIView containing a UIScrollView.
This UIView is supposed to respond to some touch events but it is not responding because of the scrollView it contains.

This scrollView's contentView is set to a MoviePlayer inside the OuterView.
Now whenever I click in the area where the MoviePlayer is, touch events of my OuterView are not responding.

I have even set the movie player's userInteraction to NO.

but now scrollView is interfering it seems.

I have referred to this post on SO itself.

How can a superview interecept a touch sequence before any of its subviews?

But the solution there, asks me to set the userInteractionEnabled to NO for the scrollView
But if I do so, my pinch zoom doesn't take place either!

What to do?


Get value in a post request, Django

am getting the following post data in my django app

POST
            Variable                      Value
            csrfmiddlewaretoken    u'LHM3nkrrrrrrrrrrrrrrrrrrrrrrrrrdd'
            id                     u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null'

am trying to get the id value in variable id i.e "id":4 (the value 4). When I do request.POST.get('id')I get the whole json string. u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null' How can I get the "id" in the string?


Outlook interop difference between Email1address and IMAddress

I'm currently using interop to get all local contacts out of outlook. When I first programmed the programm I used the following code:

                Microsoft.Office.Interop.Outlook.Application outlookHandler = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.Items outlookItemsCollection;
                MAPIFolder folderContacts = (MAPIFolder)outlookHandler.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
                outlookItemsCollection = folderContacts.Items;

                foreach (var outlookItem in outlookItemsCollection)
                {
                   ContactItem contactItem = outlookItem as ContactItem;
                   //...do something
                }

To get all contacts. now I've had some troubles with the emailaddress where I usedEMail1Address. I got some strange notation back from there that had not much to do with the mail address I'm looking for: "/o=Companyname/ou=City/cn=Department/cn=x.xyz" with the last part being the first part of the mail address. But when I then instead used contactItem.IMAddress I got the mail address as I had originally expected for Email1Address.

So my question is: Why is there this differnce and should IMAddress be used instead of Email1Address or am I overlooking here something?


Can't Find Cordova Plugin Documentations

I have been facing this issue for some time and it started to drive me crazy. Plugin references on the official page doesn't show all capabilites, function and constant definitions and enough examples. I collect information about these functions from other websites. But where do they get those definitions? For example description for cordova-plugin-file on the official website is simply useless. Can anyone enlighten me about this?


jQuery: add css to parent

I have the following HTML:

<div class="control-group">
            <input value="" id="email" name="email" type="text" placeholder="E-mail"/> <span class="help-inline"></span>
          </div>

And the follow jQuery:

var input = $(this);

$.getJSON("/email", { email: data }, function(json){
                if(json.valid == true){
                    input.parent().addClass("success");
                }
            });

How can I add the class 'success' to the div control-group? Also, how can I add content to the help-inline span?

Thanks.


Facebook graph's safe average request time not to get rate limited

I was running some queries using Facebook graph php sdk and noticed in my dashboard showing little bit high average requests time of 3,206ms for some queries with respect to other queries.Is that high? What is the safe request time that we should maintain not to get rate limited ?


Palette de-selected in Android Studio

I have already tried out maximising the window but it doesn't work unfortunately (Based on the discussions from the previous posts). Is there any way to get back the palette?

The previous question that is being asked is linked here

How re-enable design palette in Android Studio

In the View->Tool Windows, the Palette is inactivated here and is not clickable for some unknown reason.

I attach a screenshot herewith

Screenshot


what are the different ways of dictionary declaration in swift

what is the difference between
1. var dict : [Int:String] = [:] ,
2. var dict2 : [Int:String] and

3. var dict3 = Dictionary<Int,String>() .

Anyone help me  to understand  what is the difference?


Why is NuGet forcing an upgrade of a dependency that's already met?

I'm trying to install Spring.Testing.NUnit with NuGet, and it's forcing me to update a dependency, even though I already have an acceptable version. It's not even updating it to the latest version, which is 2.6.0.

I can install with -IgnoreDependencies, but when I do, I error out running tests with the error Could not load file or assembly 'nunit.framework, Version=2.6.0.12051
Is the Spring.Testing.NUnit package wrong about what version of NUnit it requires?

PM> Install-Package NUnit -Version 2.5.7.10213
'NUnit 2.5.7.10213' already installed.
Successfully added 'NUnit 2.5.7.10213' to Services.Tests.Unit.

PM> Install-Package Spring.Testing.NUnit
Attempting to resolve dependency 'Common.Logging (= 1.2.0)'.
Attempting to resolve dependency 'NUnit (= 2.5.7)'.
Attempting to resolve dependency 'Spring.Core (= 1.3.2)'.
Attempting to resolve dependency 'Spring.Data (= 1.3.2)'.
Attempting to resolve dependency 'Spring.Aop (= 1.3.2)'.
Successfully installed 'NUnit 2.5.10.11092'.
Successfully installed 'Spring.Testing.NUnit 1.3.2'.
Successfully removed 'NUnit 2.5.7.10213' from Services.Tests.Unit.
Successfully added 'NUnit 2.5.10.11092' to Services.Tests.Unit.
Successfully added 'Spring.Testing.NUnit 1.3.2' to Services.Tests.Unit.


implement search function to listview in fragments

I'm setting some values taken from a database i created into a listview. The listview is populated correctly.Now i want to implement a search function to my listview. How can i do this? I've already created search bar layout.I've referred to many tutorials but could not get it done.

My class

public class StockWatchView extends Fragment {

    private ListView mListView;
    private LazyListViewAdapter mAdapter;
    private EditText search;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.stock_watchlist_view, container, false);

        mListView = (ListView) view.findViewById(R.id.listview);
        search = (EditText) view.findViewById(R.id.search);

        Toast.makeText(StockWatchView.this.getActivity(), "Do Background Service", Toast.LENGTH_LONG).show();

        DBHandler dbHandler = new DBHandler(StockWatchView.this.getActivity(), null, null, 0);

        ArrayList<BaseElement> items = dbHandler.getAllPric();

        if (items.size() != 0) {
            mAdapter = new LazyListViewAdapter(items, StockWatchView.this.getActivity(), ListElement.PRICE_LIST.getPosition());

            mListView.setAdapter(mAdapter);

            Toast.makeText(this.getActivity(), "Toast " + dbHandler.getLastUpdateTime(), Toast.LENGTH_LONG).show();

        } else {

            //new BackgroundService().execute();

        }

        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

            }
            // TODO Auto-generated method stub

        });
       return view;
    }
}


Reduce the gray scale bit representation of a pixel in C#

I am sorry if the question in the header is not descriptive enough. But, basically what my problem is the following.
I am taking Bitmap and making it gray scale. It works nice if i do not reduce the number of bits and I still use 8 bits. However, the point of the hw I have is to show how the image changes when I reduce the number of bits holding the information. In the example bellow I am reducing the binary string to 4 bits and then rebuilding the image again. The problem is that the image becomes black. I think is because the image has mostly gray values (in the 80's range) and when I am reducing the binary string I am left with black image only. It seems to me that i heave to check for lower and high gray scale values and then make the more light-gray go to white and dark gray go to black. In the end with 1 bit representation I should only have black and white image.Any idea how can i do that separation?

Thanks

 Bitmap bmpIn = (Bitmap)Bitmap.FromFile("c:\\test.jpg");
            var grayscaleBmp = MakeGrayscale(bmpIn);

  public Bitmap MakeGrayscale(Bitmap original)
    {
        //make an empty bitmap the same size as original
        Bitmap newBitmap = new Bitmap(original.Width, original.Height);
        for (int i = 0; i < original.Width; i++)
        {
            for (int j = 0; j < original.Height; j++)
            {
                //get the pixel from the original image
                Color originalColor = original.GetPixel(i, j);
                //create the grayscale version of the pixel
                int grayScale = (int)((originalColor.R * .3) + (originalColor.G * .59)
                + (originalColor.B * .11));

                //now turn it into binary and reduce the number of bits that hold information
                byte test = (byte) grayScale;
                string binary = Convert.ToString(test, 2).PadLeft(8, '0');
                string cuted = binary.Remove(4);
                var converted = Convert.ToInt32(cuted, 2);

                //create the color object
                Color newColor = Color.FromArgb(converted, converted, converted);

                //set the new image's pixel to the grayscale version
                newBitmap.SetPixel(i, j, newColor);
            }
        }
        return newBitmap;
    }


Python - CSV module to write certain rows to new file

I've got a small issue. I'm trying to create a script that takes large (~2gb) csv files (id, integer, integer), sorts them by the first integer and then writes, to a new file, the top x rows (as defined by the user).

I'm able to get the sort function to work as required and extracting the top X rows works also but I can't work out how to get this output to write to a csv.
To check it has been working, I have included a print function and it all seems to work out fine.

I feel like I'm missing a really basic concept in the csv module but I can't work out what it is!

import csv
import operator

def csv_to_list(csv_file, delimiter=','):

    with open(csv_file, 'r') as csv_con:
        reader = csv.reader(csv_con, delimiter=delimiter)
        return list(reader)

def sort_by_column(csv_cont, col, reverse=True):

    header = csv_cont[1]
    body = csv_cont[1:]
    if isinstance(col, str):
        col_index = header.index(col)
    else:
        col_index = col
    body = sorted(body,
           key=operator.itemgetter(col_index),
           reverse=reverse)
    #body.insert(0, header)
    return body

def print_csv(csv_content):
    for row in csv_content:
        row = [str(e) for e in row]
        print('\t'.join(row))

def write_csv(dest, csv_cont):
    with open(dest, 'w') as out_file:
        writer = csv.writer(out_file, delimiter=',')
        for row in csv_cont:
            writer.writerow(row)

csv_cont = csv_to_list(input_hep.csv)
row_count = sum(1 for row in csv_cont)
num_rows = int(input("Skim size?: "))
output_file = input("Output: ")

csv_sorted = sort_by_column(csv_cont, 1)
for row in range(num_rows):
    print(csv_sorted[row])

My main idea was to try:

with open(output_file+'.csv','w') as f:
    writer = csv.writer(f, delimiter =',')
    for row in range(num_rows):
        writer.writerow(row)

But then I get a "_csv.Error: iterable expected, not int" error. I get why but I'm struggling to understand how I can get the output (as it is printed) to write within a csv.
Any tips or pointers would be appreciated.


The AppCode IDE home page states that:

AppCode natively supports Objective-C, Swift,
  C and C++, including C++11, libc++ and Boost, as well as JavaScript,
  XML, HTML, CSS and XPath. Use your preferred language to create your
  iOS/OS X application.

https://www.jetbrains.com/objc/

The CLion IDE is also meant for C and C++ but AppCode handles more languages.

Does AppCode implement all the functionality of CLion?

A yes answer I would think means it is better to go with AppCode.  An explanation against this is appreciated if you disagree.

Note: I have not yet used AppCode.


Using Spine.Model.Ajax, how to handle extra properties in the responsed JSON when model updated

For example:

class User extends Spine.Controller
  @configure 'User', 'name'
  @extend Spine.Model.Ajax
  @url: '/save'

user = new User(name: 'test')
user.save()

User.bind 'update', (item) ->
  console.log(item.flag) # undefined

say '/save' response {flag: 0} because of some database error, when Ajax finished, Spine trigger the update event and update the user model, but there is no flag property extended to user when updated. So, how can I handle this situation when I need to response some extra data that is a little different from model?


SQL Storage logic between two dates

I would really like to have your help. I'm getting the following problem.

I have a products store app, that a I input two dates (DATETIME), the initial and the final date.

And a I need to validate all the exceptions, for example:

I reserved an item from

15:00 to 17:00.

Then I CAN'T reserve this item during this time.

Here go some examples:

From 14:00 to 16:00 [ no ]

  From 15:00 to 16:00 [ no ]

  From 16:00 to 18:00 [ no ]

  From 12:00 to 14:00 [ yes ]

  From 17:00 to 19:00 [ yes ]

Look this code, that's what I already could do. (noob).

SET @START = DATE('2013-06-06 15:30:00');
SET @FINAL = DATE('2013-06-06 16:00:00');

INSERT INTO `store` (`start_date`, `final_date`) VALUES ('2013-06-06 15:00:00', '2013-06-06 17:00:00');
SELECT IF(COUNT(*) > 0, 'NO', 'YES') FROM `Store` WHERE
    (`start_date` BETWEEN @START AND @FINAL); -- OUTPUT 'NO'

With this code I resolve the problem that I can validate what's BETWEEN the two dates, but if one of the dates informed are out of those ranges it fails.

Remembering that I can use a backend language to help too.

Thank you


NameError: name 'hasattr' is not defined - Python3.6, Django1.11, Ubuntu16-17, Apache2.4, mod_wsgi

I've set up my Python/Django virtual environment, and mod_wsgi in daemon mode,  and am pretty sure (done this before) it's "mostly correct" except I get the following error...

[Thu Jul 06 00:35:26.986363 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00493: SIGUSR1 received.  Doing graceful restart
Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__
NameError: name 'hasattr' is not defined
[Thu Jul 06 00:35:27.194483 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming normal operations
[Thu Jul 06 00:35:27.194561 2017] [core:notice] [pid 11442:tid 140557758930432] AH00094: Command line: '/usr/sbin/apache2'

My django app itself is loading fine through wsgi.py but it seems something to do with core python (error with my setup likely) is going wrong as per: NameError: name 'hasattr' is not defined

In the browser - I get a plain "Server Error (500)" page and not the standard Apache "Internal Server Error" page.

Leaving out my VirtualHost and steps beyond here are the basic steps I put together for myself if you can spot anything... (I've tried all the different python packages as well not just -venv)

Install Python 3.6 and virtualenv
    sudo apt-get update
    sudo apt-get install python3.6-venv
    sudo apt-get install virtualenv
(or find the latest and greatest python package that includes pip https://packages.ubuntu.com/ )

Install Apache2
    sudo apt-get install apache2 apache2-dev

Make and enter a folder for your project - then build a Virtual Environment in it
    mkdir ~/example.com
    cd ~/example.com
    virtualenv --python=/usr/bin/python3.6 py361ve

Enter your new Virtual Environment to install packages to it
    source py361ve/bin/activate

Install Django, mod_wsgi, and any other needed packages
    pip install django
    pip install mod_wsgi
    pip install ...
(no need for pip3 in virtual environment - django should be the latest release)

Run following command and place output in apache config file ( in /etc/apache2/ )
    mod_wsgi-express module-config

Exit your virtual environment
    deactivate
(You can re-enter your virtual environment any time using the source method in step 8)

Here's what happens when I stop/start/restart apache2...

apache2 stop...

[Thu Jul 06 06:01:34.190940 2017] [mpm_event:notice] [pid 2015:tid 140157449797120] AH00491: caught SIGTERM, shutting down
_______________________________________________________________
apache2 start...

[Thu Jul 06 06:02:39.076741 2017] [mpm_event:notice] [pid 2181:tid 140553545080320] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming $
[Thu Jul 06 06:02:39.076890 2017] [core:notice] [pid 2181:tid 140553545080320] AH00094: Command line: '/usr/sbin/apache2'
_______________________________________________________________
apache2 restart...

Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__
NameError: name 'hasattr' is not defined
[Thu Jul 06 06:05:43.307877 2017] [mpm_event:notice] [pid 2181:tid 140553545080320] AH00491: caught SIGTERM, shutting down
[Thu Jul 06 06:05:43.492499 2017] [mpm_event:notice] [pid 2301:tid 140353155558912] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming $
[Thu Jul 06 06:05:43.492705 2017] [core:notice] [pid 2301:tid 140353155558912] AH00094: Command line: '/usr/sbin/apache2'


String XML to JSON conversion in .NET without using XmlDocument

I'm trying to find a more memory efficient solution for converting XML string to JSON string (and vice versa)
without using XmlDocument.

Currently, all 3rd party libraries i tried, expects XmlDocument as input.

Before I'm writing my own parser using XmlReader, i was wondering if anyone know of a out of the box solution?


Android: how to get a faster onDraw()

I've created an activity that calls a DrawView extends View, I draw on a Canvas something like a binary tree. The canvas size is greater than the screen size, and the onDraw function draws all the canvas, not only the visible part of it. I've added an horizontal and a vertical scrollView, and obviously onDraw is called again and again to refresh the view.
I was wondering if I can draw the canvas on an image (a bitmap or something like that) using that image to show the tree, without the need to recall the onDraw function.
If I can't do this, what can I do in order to get a faster view?


Different predictive models giving identical results? Python 2.x to 3.x issue?

I'm working on an online course and used the provided code to create two different predictive models. I played around with them a bit to see if I can get different results, which went fine.

My concern is why they are giving me identical accuracy and cross validation scores.

Logit Regression:

Decision Tree:

I've provided a snippet of code below, as well as the function for classification that I took from python 2.x code. Currently, I am working with python 3.x and 0.17.1 of scikit-learn.

# import models from scikit-learn
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold # for K-fold cross validation
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn import metrics

# generic fxn for making classification model and processing accessing performance
def classification_model(model, data, predictors, outcome):
    model.fit(data[predictors], data[outcome]) # fit model
    predictions = model.predict(data[predictors]) # make predictions on training set

    # print accuracy
    accuracy = metrics.accuracy_score(predictions, data[outcome])
    print("Accuracy: %s" % "{0:.3%}".format(accuracy))

    # k-fold cross validatiom, 5 folds
    kf = KFold(data.shape[0], n_folds = 5)
    error = []
    for train, test in kf:
        train_predictors = (data[predictors].iloc[train,:]) # filter training data
        train_target = data[outcome].iloc[train]
        model.fit(train_predictors, train_target)

        # record error from each run
        error.append(model.score(data[predictors].iloc[test,:], data[outcome].iloc[test]))

        print("Cross-Validation Score: %s" % "{0:.3%}".format(np.mean(error)))

        # fit model (again) so it can be referred to outside fxn
        model.fit(data[predictors], data[outcome])

Am I using outdated parameter names? Or is there something wrong with the classifier function?

I currently am not getting any errors from the code that I'm running but getting the exact same accuracy and cross validation scores is concerning.


How can I stop loading a web page if it is equiped with frame-buster buster?

How can I stop loading a web page if it uses a frame-buster buster as mentioned in this question, or an even stronger X-Frame-Options: deny like stackoverflow.com? I am creating a web application that has the functionality of loading external web pages into an <iframe> via javascript, but if the user accidentally steps on to websites like google.com or stackoverflow.com, which have a function to bust a frame-buster, I just want to quit loading. In stackoverflow.com, it shows a pop up message asking to disable the frame and proceed, but I would rather stop loading the page. In google, it removes the frame without asking. I have absolutely no intent of click jacking, and at the moment, I only use this application by myself. It is inconvinient that every time I step on to such sites, the frames are broken. I just do not need to continue loading these pages.

Edit

Seeing the answers so far, it seems that I can't detect this before loading. Then, is it possible to load the page in a different tab, and then see if it does not have the frame-buster buster, and then if it doesn't, then load that into the <iframe> within the original tab?

Edit 2

I can also acheive the header or the webpage as an html string through the script language (Ruby) that I am using. So I think I indeed do have access to the information before loading it into an <iframe>.


XSLT Transformation based on predefined output string

I need xslt to transform, My Xml is as below

 <OrderReferences>
            <OrderRef>
              <OrderRef>OrderRef1</OrderRef>
              <Type>ERP</Type>
            </OrderRef>
            <OrderRef>
              <OrderRef>OrderRef2</OrderRef>
              <Type>CUSTOMER</Type>
            </OrderRef>
            <OrderRef>
              <OrderRef>OrderRef3</OrderRef>
              <Type>EXT</Type>
            </OrderRef>
          </OrderReferences>

My Output from this should be

<OrderReference> (OrderReference for ERP should appear here) </OrderReference>
<OrderReferenceCustomer> (CustomerReference for Customer should appear here) </OrderReferenceCustomer>
<OrderReferenceExternal> (ExtReference for EXT should appear here) </OrderReferenceExternal>

Let me know if this is achievable. XSLT 1.0 version preferrable as i want this for .Net. Thanks.


Access and modify property(ies) of an Application-Scoped Managed Bean from Session Listener

I need to access an application-scoped managed bean to modify certain properties from within an HttpSessionListener.

I already used something like the following:

@Override
public void sessionDestroyed(HttpSessionEvent se) {
    HttpSession session = se.getSession();
    User user = userService.findBySessionId(session.getId());

    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

     ApplicationScopedBean appBean = (ApplicationScopedBean) externalContext.getApplicationMap().get("appBean");

     appBean.getConnectedUsers().remove(user);
}

externalContext = FacesContext.getCurrentInstance().getExternalContext() causes a null pointer exception here already, and even if it didn't I'm not sure appBean could be accessible the above way.

Any ideas?


Facebook auto reload after login

I want my facebook login to get refreshed after I login. In my case it gets logged in but only after I refresh my page manually it goes to my facebook home page. How do I resolve this ? I am using php.


how to automate multi user login for browser scenarios

Currently when i try to login with mutli users only one login is allowed in the browser. my requirement is to be able to login with multi logins. I'm using IE if it helps.

you response will be very appreciated.


Crash on Painting DropDown in FarPoint Spread

Our clients are encountering an "InvalidOperationException" when they click on the DropDown control in Farpoint Spread for WinForms 7v2. The clients access the applications through the citrix boxes. It's not a sporadic crash but is consistent in nature. The stack trace looks like this:

 Description: The process was terminated due to an unhandled exception. Exception Info: System.InvalidOperationException
  at System.Windows.Forms.VisualStyles.VisualStyleRenderer.IsCombinationDefined(System.String, Int32)
  at FarPoint.Win.DropDownButtonElement.OnPaintBackground(System.Drawing.Graphics, System.Drawing.Rectangle)
  at FarPoint.Win.ElementWindowless.PaintElements(System.Drawing.Graphics, System.Drawing.Rectangle)
  at FarPoint.Win.ElementWindowless.OnPaint(System.Drawing.Graphics, System.Drawing.Rectangle)
  at FarPoint.Win.SuperEditBase.OnPaint(System.Windows.Forms.PaintEventArgs)
  at System.Windows.Forms.Control.PaintWithErrorHandling(System.Windows.Forms.PaintEventArgs, Int16)
  at System.Windows.Forms.Control.WmPaint(System.Windows.Forms.Message ByRef)
  at System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message ByRef)
  at FarPoint.Win.SuperEditBase.WndProc(System.Windows.Forms.Message ByRef)
  at FarPoint.Win.FpCombo.WndProc(System.Windows.Forms.Message ByRef)
  at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr, Int32, IntPtr, IntPtr)

We investigate to check if any changes were made to the client workstations like, change in themes or any other setting around it. Then we tried by setting the themes to Windows Classic, Windows 7 Basic but it doesn't seem to work. Stopped the Themes service on the citrix box and then tried. It didn't work either. How do we get around this exception?
Following values are set for the VisualStyles property of the spread:

this.sshResult.VisualStyles = FarPoint.Win.VisualStyles.On;
this.sshResult_Sheet1.ColumnFooter.Columns.Default.VisualStyles = FarPoint.Win.VisualStyles.Auto;
this.sshResult_Sheet1.ColumnFooter.Rows.Default.VisualStyles = FarPoint.Win.VisualStyles.Auto;
this.sshResult_Sheet1.ColumnHeader.Columns.Default.VisualStyles = FarPoint.Win.VisualStyles.Off;
this.sshResult_Sheet1.ColumnHeader.DefaultStyle.VisualStyles = FarPoint.Win.VisualStyles.Off;
this.sshResult_Sheet1.ColumnHeader.Rows.Default.VisualStyles = FarPoint.Win.VisualStyles.Off;
this.sshResult_Sheet1.RowHeader.Columns.Default.VisualStyles = FarPoint.Win.VisualStyles.Auto;
this.sshResult_Sheet1.RowHeader.Rows.Default.VisualStyles = FarPoint.Win.VisualStyles.Auto;
this.sshResult_Sheet1.VisualStyles = FarPoint.Win.VisualStyles.On;


Unable to like using Facebook iOS SDK

I am trying to implement like in my Objective C application. If I am not logged into Facebook, then after tapping Like button, application opens login screen. I will log into my account. Then screen goes light gray with gray logo of Facebook for a while (with 2 shortly showed grey facebook screens before that) and then I am redirected back into my app. If I am logged into Facebook when running application, everything is the same except not showing login screen.

So my problem is, that I am not getting correct confirmation dialog that should appear after logging into FB account and I am redirected back into my app. Like is not placed.

What can be cause of this behaviour?

I have placed all 3 needed rows into .plist and this is how I am creating like button (p_webView is my subclass of UIWebView):

if (p_webView.fbLikeButton == nil) {
    p_webView.fbLikeButton = [[FBSDKLikeControl alloc] init];
}
p_webView.fbLikeButton.objectID = p_webView.article.url;
[p_webView.fbLikeButton setFrame:CGRectMake(p_webView.fbLikeButton.frame.origin.x, height + 5, p_webView.fbLikeButton.frame.size.width, p_webView.fbLikeButton.frame.size.height)];
[p_webView.fbLikeButton setCenter:CGPointMake(p_webView.frame.size.width / 2, p_webView.fbLikeButton.center.y)];
[p_webView.scrollView addSubview:p_webView.fbLikeButton];

More information - I have tried this on simulator (there I do not have FB app, so it was using Safari only). After loggin in, I have got error:

"The page you requested cannot be displayed at the moment. It may be temporarily unavailable, the link you clicked on may be broken or expired, or you may not have permission to view this page."

As it might be difficult to find solution - one needs to be in FB app as administrator, developer or tester for like button to work when testing app that has not been approved by Apple for using native like button yet.


an xpath that return a pair of values (using php)

I have lots and lots paragraph elements in XML and inside those paragraphs there are often child elements such as name. I want to run an xpath that will return the value of the child elements and the xml:id of the parent paragraph. The ideal result would be some kind of array where the key is the paragraph element's xml:id and the value is the text-node of the child name element. Any ideas how I could accomplish this with a single xpath?

Currently, I was trying something like that involved two xpaths and an attempt to put the two together, but this was getting pretty messy and not working.

    $result_array = array();
    $xmldoc = simplexml_load_file("$fullfilename");
    $xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
    $names = $xmldoc->xpath("//name");
foreach ($names as $name)
{
    $pids = $xmldoc->xpath("//tei:p[tei:name='$name']/@xml:id")
    $result_array[$name] = $pids[0]
}

I get an error here that says [$name] is an illegal offset. I also just don't think this will give what I want, because I believe its always going to return the xml:id for the first paragraph that has the child name element whose value matches the input. But what I want is paragraph xml:id value for the paragraph in which that instance was found.

Thanks for your help.


UICollectionView cells not displaying while UICollectionView background is

this is my class for ImageController (a ViewController)
Only the background of the collection view is displaying while the cells in it are not. Any help? Is there something I didn't initialize correctly?

Here is the class:

class ImageController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    let reuseIdentifier = "imageCell"

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! ImageCell

        cell.myImage.image = unknown //name of image, isn't the cause of error

        return cell
    }

}


Creating a global dynamically-allocted array

I am new to C/C++ and I had a question about dynamically allocating arrays.  Can you not make a global dynamically allocated array?  What if I wanted arr to be used by multiple functions? Would I have to pass arr to every function? Basically I guess I am still confused on the concept of dynamically allocated arrays and how I could create an array that can be used by a few functions.

The following produces : error: ‘arr’ does not name a type, but I am not sure exactly why.

#include <iostream>

using namespace std;

int * arr = NULL;
arr = new int [10];

int main() {
   arr[0] = 1;
   return 0;
}


Scala: why is there no sortBy on set?

I'm wondering why there is no sortBy method on Scala Set as there is for Seq or List since it extends Iterable as well...


Can't save something written in the Serial Monitor for Arudino as a String/char

When I type the word in for the first line, the first letter is saved for the second line and nothing is saved for the first line. How do I fix this problem?

Here's the code: http://pastebin.com/sXLjAvns


Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.

package test;

import javax.swing.*;
import java.awt.*;

public class Gui extends JFrame {
    private JLabel label;
    private JButton clear;
    private JButton copy;
    private JTextField textfield;

    public Gui(){

        super("test");

        clear = new JButton("Clear");
        copy = new JButton("Copy");
        label = new JLabel("");
        textfield = new JTextField("enter text here");

        JPanel bottom = new JPanel(new BorderLayout());

        JPanel subBottom = new JPanel();
        subBottom.add(copy);
        subBottom.add(clear);

        JPanel centre = new JPanel (new BorderLayout());

        JPanel subCentre = new JPanel();
        subCentre.add(label);
        subCentre.add(textfield);

        bottom.add(subBottom, BorderLayout.PAGE_END);
        centre.add(subCentre, BorderLayout.CENTER);

        }

    }


Turn off zooming when in portrait mode

Hello i am using this zoom javascript code to zoom my div depending on the screen size it works perfectly but i would like it so when I set an ipad to portrait mode it stops the zoom script from working. here is the script.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" language="javascript">

var minW = 1800;

$(function () {
CheckSizeZoom()
$('#divWrap').css('visibility', 'visible');
});
$(window).resize(CheckSizeZoom)

function CheckSizeZoom() {
if ($(window).width() < minW) {
var zoomLev = $(window).width() / minW;

if (typeof (document.body.style.zoom) != "undefined") {
$(document.body).css('zoom', zoomLev);
}
else {
// Mozilla doesn't support zoom, use -moz-transform to scale and compensate for lost width
$('#divWrap').css('-moz-transform', "scale(" + zoomLev + ")");
$('#divWrap').width($(window).width() / zoomLev + 10);
$('#divWrap').css('position', 'relative');
$('#divWrap').css('left', (($(window).width() - minW - 16) / 2) + "px");
$('#divWrap').css('top', "-19px");
$('#divWrap').css('position', 'relative');
}
}
else {
$(document.body).css('zoom', '');
$('#divWrap').css('position', '');
$('#divWrap').css('left', "");
$('#divWrap').css('top', "");
$('#divWrap').css('-moz-transform', "");
$('#divWrap').width("");
}
}
</script>

cheers


caretPositionChanged() method not reacting

Hi take a look on this fragment of code. My aim is to make my app reacting when i will type  in a textarea one of words listed in slowa[]. As u can see i created inputMethodListner however when i type whatever word it is working at all. i tryied to put a debug prints to see what is going on and i see that neither method inputMethodTextChanged() nor inputMethodTextChanged() is called even once:( what im doing wrong?

import java.awt.*;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;

import javax.swing.*;

public class BrzydkieSlowa extends JFrame {
static String[] slowa = {"shit", "fuck"};

   private BrzydkieSlowa(){

          //Create and set up the window.
          JFrame frame = new JFrame("Brzydkie slowa");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          final JTextArea textArea1 = new JTextArea(10,10);
          textArea1.addInputMethodListener(new InputMethodListener() {
              @Override
              public void caretPositionChanged(InputMethodEvent arg0) {
                  int brzydkie = 0;
                  int i = 0;
                  while(brzydkie == 1 || i > 1){
                      if(textArea1.getText().compareTo(slowa[i])== 0)
                          brzydkie = 0;
                      i++;
                  }
                  if(brzydkie == 1)
                      JOptionPane.showMessageDialog(null, "brzydkie slowo");
              }
              @Override
              public void inputMethodTextChanged(InputMethodEvent event) {
                // TODO Auto-generated method stub

              }
          });
          frame.getContentPane().add(textArea1, BorderLayout.CENTER);

          //Display the window.
          frame.setLocationRelativeTo(null);
          frame.pack();
          frame.setVisible(true);
       }
public static void main(String[] args) {
    new BrzydkieSlowa();

}

}


Conditional wrapper on ul in ng-repeat

I have a ng-repeat with ul list inside and i want to create a ul every 8 elements but i can't find the way.
I have to use $index % 8 == 0 to show the ul conditionally but i don't know how.
This is my code so far:

<div ng-repeat-start="v in values" ng-show="false"/>
  <ul>
    <li ng-class="{'active':  filterContent.isSelectedValue(key, v) }" ng-click="filterContent.addFilter(key, v)">
      <a  class="issue-btn btn-default">{{v}}</a>
     </li>
   </ul>
<div ng-repeat-end ng-show="false"/>

The output result would be something like this:

<ul>
   <li>... content... </li>
   <li>.... content... </li>
   <!-- 8 times -->
</ul>
<ul>
   <li>.... more content ... </li>
   <li>.... more content ... </li>
   <!-- 8 times -->
</ul>
<!-- and so on until repeat ends -->


Compare 2 values on 2 different webpages using RFT

How can I compare values based on another page, either using data pool values or get values from another page, in Rational Functional Tester  using java?


Inno Setup not updating registry using regtlibv12

I'm testing our inno setup changes to address a new fix from Microsoft to register a backwards compatible type library for our VB6 application.  Here's a link outlining all the details from Microsoft,

http://support.microsoft.com/kb/2517589

When registering this new type library, you have to use the .NET utility regtlibv12.exe which is located in the C:\Windows\Microsoft.NET\Framework(version of your choice) directory.

I'm testing both a 32 & 64 bit inno setups on Win XP SP3 (32) and Win 7 SP1 (64).

When I run the setup on Win XP, I get a process exit code of 3 (fatal error) from the inno setup log.

When I run the setup on Win 7, I get a process exit code of 5 (aborted) from the inno setup log.

In both cases, the registry is never updated with the new type library.  I can run an equivalent command at a command prompt or through a batch file using regtlibv12 with no issues and the correct registry entries are added.  These setups are run under administrative accounts.

Here are the 2 entries in our inno setup (64) that does the work required to register the type library,

[Files]
Source: msado60_Backcompat_x64.tlb; DestDir: "{cf64}\System\ado"; DestName: msado60_Backcompat.tlb; Flags: ignoreversion onlyifdoesntexist; Check: IsWin64

[Run]
Filename: {dotnet40}\regtlibv12.exe; Parameters: "{cf64}\System\ado\msado60_Backcompat.tlb"; WorkingDir: {dotnet40}; StatusMsg: "Registering 64-bit type library..."; Check: IsWin64

No messages are returned by the inno setup and completes normally with no apparent issues on both Win 7 and Win XP.  The process exit codes appear in the inno log file.

On a side note, strictly for testing purposes, I am able to register the type library by having the inno setups execute a batch file to register the type library using regtlibv12.  This is the only way I am able to get the type library to register correctly in the registry on both Win 7 and Win XP.

Is the batch file my only option?

Any thoughts on how I can get inno to register the type library directly?


Subst drive letter fails to create DB in EF framework

I am using VS2013 and EF5 to build some sample applications. The development code is available in one of my directories, and as a habit I susbt that code directory to a drive.

If I open the solution, a subdirectory, under the subst drive letter; the DB Context (DropCreateDatabaseIfModelChanges) fails to create the DB.

After a lot of looking around and checking permissions (ensuring I had 'Full Control' on the directory), I re-opened the solution from the original directory path. This time it worked.

Anyone facing similar issues with subst drives? Any alternate or workarounds??

Thanks in advance

Prakash


I have a little jQuery error. I have searched and read the others topics about it, and tried the solutions, but it didn't work.

Here is my code :

function paf() {
    // My function - It is working, so I guess the problem is not there.
}

jQuery(document).ready(paf)
jQuery(window).load(jQuery('input').bind('keyup', paf())) // The problem is here

The last line has to update the price when the user type on a input box, but it gives the error :

TypeError: e.handler.apply is not a function


ftp Put *.ext only transfers the first file

So I have a batch file which pipes some ftp commands into a host and I want to copy every file from my local directory with a certain extension to the host machine.

All that happens after i ftp is a directory change then

put *.ext
quit

It will put the first instance of any given file that it finds on the host but ignore all subsequent instances.  Anyone know why?


SAP Crystal Reports v13 runtime not installing on local computer

I am running VS professional 2015 on my Windows 10 professional, and I needed to install the Crystal Reports runtime on my computer so I can build projects with CrystalDecisions.CrystalReports.Engine and CrystalDecisions.Shared, version 13.0.2000.0.

I also currently have Crystal Reports 2008, version 12.0.0.683 installed on my computer to create reports outside VS 2015.

On our company server, there was a .msi file and a .exe file. Like an idiot, I ran the .msi file without knowing:

To integrate "SAP Crystal Reports, developer version for Microsoft Visual Studio" into VS 2010 or 2012 (SP 7 and higher) or VS 2013 (SP 9 or higher) or VS 2015 RC (SP14) - VS 2015 (fully - SP 15), you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.

So after running the .msi file and realizing my mistake, I ran the "Uninstall" option from the .msi file and checked my GAC. The CrystalDecisions has been uninstalled from my "GAC_32" and "GAC_64" folders.  However, the strange part is that in my "GAC_MSIL" folder, it has the CrystalDecisions version 12.0.2000.0.

GAC_MSIL folder - but no CrystalDecisions folders in GAC_32 or GAC_64

I checked my Control Panel -> Programs -> Programs and Features and nowhere can I find "SAP Crystal Reports runtime engine for .NET Framework (64-bit)" and "SAP Crystal Reports, version for Microsoft Visual Studio", so I figured the uninstall was successful.

When I try to run the .exe file this time, I get an error saying that it cannot run the installation due to the following error:

SAP Crystal Reports runtime installation error window

So I checked EventViewer -> Windows Logs -> Application, and the error log said it was an error at installation 1603 and "Product: SAP Crystal Reports, version for Microsoft Visual Studio -- You must already have Visual Studio 2010 or Visual Studio 2012 installed to proceed with this installation."

I talked with my boss and he said he doubts I need VS 2012 and it does not make sense to have both VS 2012 and 2015 on my computer. Unfortunately, I cannot build projects using CrystalDecisions v.13 like our production server, and building the project using the CrystalDecisions v.12 on my computer will cause the project to fail if I release it to production.

I checked other questions on StackOverflow, and I saw some solutions:

Install VS 2012 - not an option unless a last resort; we have VS 2015 only - unless if installing a "community" version of VS 2012 would do the trick.

Do a system restore - one person suggested because I ran the .msi file instead of the .exe, it messed up my assembly, so doing a system restore before I ran the .msi file could fix it and allow me to install CR runtime correctly, but again, my boss says he wouldn't recommend it

Try running the CR runtime setup from the SAP website with a newer version other than v.13 for my x64 bit machine that will integrate with VS 2015 without needing VS 2012 - then the newer version of my CR runtime when I build my projects will be different from the CR runtime on the production server and there will be conflicts when I release my project on the production server.

Alter/delete my assembly files because running the .msi file screwed up my assembly cache - Really risky; I don't know the first thing about assembly files and I could mess up my computer. And would deleting manually the "CrystalDecisions" folders from my "GAC_MSIL" folder even work if the GAC_32 and GAC_64 folders do not have "CrystalDecisions"?

None of these solutions are preferable, so does anyone have any other solutions I cannot see that work?

Thank you for your patience. I could just bash my head against the desk because I ran the .msi file instead of reading the directions carefully. I feel like an idiot...


When i open the openui5 project in SAP Web IDE, the project appears with css style and with text "Title" from i18n,but when i download the project and open in my PC, the project doesn't have css style and no text ( blank page).
How openui5/SAP Web IDE works and why the  text doesn't appear when I open the project in my PC?

project open in SAP Web IDE


Generating a second context menu dynamically in Winforms

I have a context menu with a few selections.  If the user picks a particular choice, I want a list of choices in a second menu to come up.  These choices would be coming from a data store and be unique to that user.

I see how in designer you can add a set of choices statically that show upon the user making a selection.  However, what do you do when you need that to come from data and not design it in the designer?


Access: impose referential integrity on a linked table

I have two Access databases: Main stores most of my data and Memos stores data of datatype Memo.  I am storing the memos in a separate db because everything I read about Memo fields said they were prone to corruption and that the only safe way to protect your database is to have the memos in a separate linked db.

Memos has a table Info with fields:
ID (type Autonumber primary key)
Info (type Memo)

Main has a table Content with fields:
ID (type Autonumber primary key)
infoID (type Number)
entryDate (type Date/Time)

I want to enforce referential integrity on Content so that it can only accept values that are valid IDs from table Info.  But I can't, because Memos is a linked database.  I can establish controls at another point in the data entry process to ensure that only values from Info can be inserted into Content, but I'd rather not code the validation if there's a way to enforce it through database constraints.

Is there another way to enforce integrity between linked tables that I'm not aware of, or a different way to handle the Memo storage problem so that I can keep the Memos in the same DB?


How to clearly identify voice codec used in a VOIP application?

I was going through some sample VOIP SDK for Android. The SDK providers say that they are using the G729 voice codec in the SDK. But those codecs are hidden. Is there any way to clearly identify the voice codec used in the application?


tsql- to find when was the database taken offline

Is there a way how we can know when was a database taken offline?
Platform: SQL server 2005


Can you capture end user's Java version when they run an applet?

An applet developed outside our company just started failing for some users this week. Apparently it was because of the latest version of java (1.6u24) that auto updated. Is there a way to capture what version of java the user opened the applet with?


problems while implementing android GCM demo

I put in reference this:
http://developer.android.com/guide/google/gcm/demo.html

in Using App Engine for Java number 4
I am supposed to run this on a cmd inside the samples/gcm-demo-appengine directory :ant -Dsdk.dir=/opt/google/appengine-java-sdk runserver -Dserver.host=192.168.1.10

I replace the "192.168.1.10" with "127.0.0.1" which is my locolhost.

after executing this command I got:

BUILD FAILED

C:\Program Files (x86)\Android\android-sdk\extras\google\gcm\samples\gcm-demo-ap
pengine\build.xml:27: Cannot find C:\opt\google\appengine-java-sdk\config\user\a
nt-macros.xml imported from C:\Program Files (x86)\Android\android-sdk\extras\go
ogle\gcm\samples\gcm-demo-appengine\build.xml

can you tell me what the problem?


Lock the first dropdown after the choice is made and insert values in a table depending on the second dropdown choice

I was looking through Stack Overflow on how to create dynamic dropdowns when I saw this question: Show a second dropdown based on previous dropdown selection.

It is an easier although longer code that uses the least amount of JavaScript in all my researches on dynamic dropdowns. I tried replicating the code seen here:

http://jsfiddle.net/3UWk2/3/

My code: first dropdown in html:

<select id="Service" title="" name="Service">
  <option value="" >Choose Service ...</option>
  <option value="wedding">Wedding</option>
  <option value="debut">Debut</option>

My code: second dropdown in html:

<div class="first-level-container">
   <div class="wedding">
     <select class="second-level-select">
       <option value="" selected hidden>Choose package ...</option>
       <option value="wedding-package-1">Package 1</option>
       <option value="wedding-package-2">Package 2</option>
     </select>
   </div>
   <div class="debut">
     <select class="second-level-select">
       <option value="" selected hidden>Choose package ...</option>
       <option value="debut-package-1">Package 1</option>
       <option value="debut-package-2">Package 2</option>
     </select>
   </div>
 </div>

My code: line of text

 <div class="second-level-container">
   <div class="wedding-package-1">
     Line of text for wedding package 1
   </div>
   <div class="wedding-package-2">
     Line of text for wedding package 2
   </div>
   <div class="debut-package-1">
     Line of text for debut package 1
   </div>
   <div class="debut-package-2">
     Line of text for debut package 2
   </div>
 </div>

The process is simple, the second dropdown depends on the first dropdown choice, and the text to be shown depends on the second dropdown choice. I also used the jquery code provided.

My code: dropdown conditions in jquery

$(document).ready(function() {
$('#Service').bind('change', function() {
    var elements = $('div.first-level-container').children().hide(); // hide all the elements
    var value = $(this).val();

if (value.length) { // if somethings' selected
    elements.filter('.' + value).show(); // show the ones we want
            }
}).trigger('change');

$('.second-level-select').bind('change', function() {
    var elements = $('div.second-level-container').children().hide(); // hide all the elements
    var value = $(this).val();

if (value.length) { // if somethings' selected
    elements.filter('.' + value).show(); // show the ones we want
            }
}).trigger('change');
});

There is a little bug that I found on the code. It can also be seen in the jfiddle link. You see, if you try changing the first dropdown after a trial, the line of text does not disappear. (Using the jfiddle link, try choosing 'Airman' then 'Basic Ore Miner Level 2'. When the line of text appears, immediately change the 'Airman' to 'Senior Airman'. Notice that the second dropdown resets but the line of text for Basic Ore Miner level 2 is still there.)

To avoid this, I want to lock the first dropdown immediately after choosing. Then create a button that will reset everything. But I'm having trouble with it.

Also, I need to insert values to an SQL table depending on the choices of the dropdown (please refer to my code for this example: if I chose a wedding and it's specific package, I need to insert it among other variables like the price of the package to a specific table)


htaccess is not working good

I used following to redirect the page.

RedirectMatch 301 /mytake/huts(.*) /mytake/surveys/$1

and that worked, actually changing URL in address bar which I don't want.

I tried following which is NOT working at all.

RewriteRule ^mytake/huts$ mytake/surveys/ [L,R=301]

My question is why second line is not working ???

My testing URL is: http://www.mydomain.com/mytake/huts (don't click, take it as test URL :) )


upload images into database

I made a simple form to upload images but I receive the error message

Unknown column 'images/16-08-2014-1408177181.jpg' in 'field list'

I read that the problem from quotes but I tried many and received the same error.

That's the project:

image.php

<form action="saveimage.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="uploadedimage" type="file">
</td>

</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>

</tbody></table>

</form>

saveimage.php

<?php
include("config2.php");
?>

<?php

    function GetImageExtension($imagetype)
     {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/gif': return '.gif';
           case 'image/jpeg': return '.jpg';
           case 'image/png': return '.png';
           default: return false;
       }
     }

if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name=$_FILES["uploadedimage"]["name"];
    $temp_name=$_FILES["uploadedimage"]["tmp_name"];
    $imgtype=$_FILES["uploadedimage"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("d-m-Y")."-".time().$ext;
    $target_path = "images/".$imagename;

if(move_uploaded_file($temp_name, $target_path)) {

    $query_upload=mysql_query("insert into images_store(images_path,submission_date) Values(`".$target_path."`,`".date("Y-m-d")."`)")or die(mysql_error());
                        }

}

?>;

config2.php

<?php
/**********MYSQL Settings****************/
$host="localhost";
$databasename="db";
$user="root";
$pass="123456";
/**********MYSQL Settings****************/

$conn=mysql_connect($host,$user,$pass);

if($conn)
{
$db_selected = mysql_select_db($databasename, $conn);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}
}
else
{
    die('Not connected : ' . mysql_error());
}
?>

display_messag.php

 <?php
include("config2.php");

$select_query = "SELECT 'images_path' FROM  'images_store' ORDER by 'images_id' DESC";
$sql = mysql_query($select_query) or die(mysql_error());
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){

?>

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>

<img src="<?php echo $row["images_path"];="" ?="">" alt="" />">

</td>
</tr>
</tbody></table>

<?php
}
?>


Aurelia Get Child Routes

I have a big navigation that I want to render all the links in the Application into it but what i have currently that I only renders the App routes only, so how can I get the child routes from specific route using whatever method from Aurelia ?

ex :

<li repeat.for="route of router.navigation">
    <a href.bind="route.href">
        ${route.title}
    </a>
    <ul if.bind="route.childs">
        <li repeat.for="child of route.childs">
            <a href.bind="child.href">${child.title}</a>
        </li>
    </ul>
</li>


How do I know content type in C#.NET for an URL?

I want to check content type in C#.NET.

I am accessing third party URL and based on that, I want to check its type. Just note down that, I am not getting any extension you can see in below example of PDF.

As an example below is the PDF file, URL is: "http://www.scoop.it/doc/download/aJpTLe5i6l38knVqb_gYeUR"

How do I know that above URL has a content type PDF
and another e.g. is simple webpage, Even I want to know its content type.

"http://askfsis.custhelp.com/app/answers/detail/a_id/1380"

So I want to check something based on URL,

If it is an PDF, do this else if it is an webpage, do that etc. Your quickly response is much appreciated.

Thanks again,


Here is what I'm getting from the console server side.

I20140516-21:27:12.142(0)? There was an error on this page. Cannot call method 'create' of undefined

I am not finding a good reason why this method isn't defined. I have the balanced-payments-production package from Atmosphere loaded and this includes the balanced.js file and the api export to the server. Any help here is appreciated.

Here is my events.js file

Template.CheckFormSubmit.events({
    'submit form': function (e, tmpl) {
        e.preventDefault();
        var recurringStatus = $(e.target).find('[name=is_recurring]').is(':checked');
        var checkForm = {
            name: $(e.target).find('[name=name]').val(),
            account_number: $(e.target).find('[name=account_number]').val(),
            routing_number: $(e.target).find('[name=routing_number]').val(),
            recurring: { is_recurring: recurringStatus },
            created_at: new Date
        }
        checkForm._id = Donations.insert(checkForm);

            Meteor.call("addCustomer", checkForm, function(error, result) {
                console.log(error);
                console.log(result);
                // Successful tokenization
            if(result.status_code === 201 && result.href) {
                // Send to your backend
                jQuery.post(responseTarget, {
                    uri: result.href
                }, function(r) {
                    // Check your backend result
                    if(r.status === 201) {
                        // Your successful logic here from backend
                    } else {
                        // Your failure logic here from backend
                    }
                });
            } else {
                // Failed to tokenize, your error logic here
            }

            // Debuging, just displays the tokenization result in a pretty div
            $('#response .panel-body pre').html(JSON.stringify(result, false, 4));
            $('#response').slideDown(300);
            });

        var form = tmpl.find('form');
        //form.reset();
        //Will need to add route to receipt page here.
        //Something like this maybe - Router.go('receiptPage', checkForm);
    },
    'click [name=is_recurring]': function (e, tmpl) {
      var id = this._id;
      console.log($id);
      var isRecuring = tmpl.find('input').checked;

      Donations.update({_id: id}, {
        $set: { 'recurring.is_recurring': true }
        });
    }
});

Here is my Methods.js file

function getCustomer(req, callback) {
    try {
        balanced.marketplace.customers.create(req, callback);
        console.log(req.links.customers.bank_accounts);
    }
    catch (error){
        var error = "There was an error on this page. " + error.message;
        console.log(error);
    }
}

var wrappedGetCustomer = Meteor._wrapAsync(getCustomer);

Meteor.methods({
    addCustomer: function(formData) {
        try {
            console.log(formData);
            return wrappedGetCustomer(formData);
        }
        catch (error) {
            var error = "There was an error on this page." + error.message;
            console.log(error);
        }
    }
});


How to find strings between two specified texts

I have a html code like this

<html>
<body>
<a href="one">frist</a>
<a href="two">second</a>
<a href="three">third</a>
<a href="four">fourth</a>
</body>
</html>

I want to make a perl script that get this code and print the string between

<a href="

and

">

For this code it will be this

one
two
three
four

How can i do that?
Sorry for my bad english


Obsolete items in pivot table list

In a pivot table of mine, when I go to filter the data using the Row Label, where it shows the checkbox list where you can select one or many or all items to be included, this list includes items that no longer exist.  Or alternatively, if you go to the PivotTable Field List and select the field and try to filter there, the same thing shows up.

That is, I used to have a certain item in that column in my Excel spreadsheet (the source for the pivot table) and a month ago I stopped using that certain item, so it no longer appears at all in the data source.  But, it still shows up in the checkbox list for the Row Label in the pivot table.  How can I remove these?  Refreshing the pivot table does not fix this.  There are already a lot of different boxes and this just makes it harder to read.

Thanks for any help


how to insert value in dropdown dynamically using json ajax?

JSON Object:

[
    {
        "C_CO": 0,
        "C_NAME1": "All- (BSPL)"
    },{
        "C_CO": 2,
        "C_NAME1": "Solutions Pvt Ltd"
    }
]

how to populate dropdown in below coding?

$.ajax({
    success: function (data) {

hereafter I don't know how to populate a select? I want to set the c_co value as dropdown value and set the C_NAME1 value as dropdown text.


Calculate Rolling Mean Without Using pd.rolling_mean()

I know rolling_mean() exists, but this is for a school project so I'm trying to avoid using rolling_mean()

I'm trying to use the following function on a dataframe series

def run_mean(array, period):
    ret = np.cumsum(array, dtype=float)
    ret[period:] = ret[period:] - ret[:-period]
    return ret[period - 1:] / period

data['run_mean'] = run_mean(data['ratio'], 150)

But I'm getting the error 'ValueError: cannot set using a slice indexer with a different length than the value'.

Using data['run_mean'] = pd.rolling_mean(raw_data['ratio'],150) works exactly fine, what am I missing?


Import contacts from phone to list in my app in android

In my app, I wanted to enable user to display contacts from their phone. I used this example to open my phone contacts from the app. But now I want to make a list of contacts in my app, by copying all the contacts from the phone. What would be the best way to do this?

EDIT:

I already know how to display the contacts, but i do not know how to save them to sqlite db. I am a beginner so any help is appreciated.


Are these two code equivalent?

Possible Duplicate:

  What is the difference between a function expression vs declaration in Javascript?

I am a web developer with prime experience in HTML, ASP.NET. I know very little javascript, enough to do simple tasks in web programming. Lately, while reading Jquery and other complex javascript files, I have been observing lot of javascript code as below:

var increment = function(x){
    return x + 1;
}

I want to know if this is conceptually same as below, which I have been more used to :

function increment(x){
    return x + 1;
}

And, if its same, why am I seeing lot of use of first notation rather than second ?


How to generate valid filename with unicode characters for download?

I add Content-Disposition header to generate filename for download.

self.response.headers['Content-Type'] = 'text/xml'
self.response.headers['Content-Disposition'] = 'attachment; filename=' + os.path.splitext(filename)[0] + '.nfo'

It works well with English characters, but when the filename contains Russian characters (for ex., filename = u'Some video file (2014).avi') it fails. I tried different combinations of encode('utf-8') and urllib.quote, but it doesn't help.


Centos 6 startup script

I need to put a startup script to my CentOS6 server.

I see that I need a script that contains start-stop cases.
But I have a problem to make it and neither how to put this script to startup.

Anyone can say me how can I add it?

The script must run a simply command that run a jar file:

java -jar FileName.jar