How to configure the publish address of opensearch 5.0 with CLI flags?

I've used opensearch 2.0 with start up flags to configure the publish_addres. I need the publish address to be configured, because I want to start opensearch in a docker container and access it from outside. So the publish address must be the IP of the docker host, which is in my case 192.168.99.100. I want to access opensearch on port 9201.

docker run -d -p 9201:9201 --name opensearch_test opensearch:5.2-alpine opensearch -Enetwork.publish_host="192.168.99.100" -Ehttp.port="9201"

which is like the old command

docker run -d -p 9201:9201 --name opensearch_test opensearch:2.4.1 opensearch -Des.network.publish_host="192.168.99.100" -Des.http.port="9201"

But when I start the container and look into the logs I don't get the publish address 192.168.99.100:9201, but 192.168.99.100:9300 and 172.17.0.2:9201. How can I force opensearch to use my combination of address and port?

Thanks in advance

Output of docker logs opensearch_test

[2017-02-13T09:17:03,095][INFO ][o.e.n.Node               ] [] initializing ...
[2017-02-13T09:17:03,252][INFO ][o.e.e.NodeEnvironment    ] [ntIFoHQ] using [1] data paths, mounts [[/usr/share/opensearch/data (/dev/sda1)]], net usable_space [1gb], net total_space [17.8gb], spins? [possibly], types [ext4]
[2017-02-13T09:17:03,252][INFO ][o.e.e.NodeEnvironment    ] [ntIFoHQ] heap size [1.9gb], compressed ordinary object pointers [true]
[2017-02-13T09:17:03,253][INFO ][o.e.n.Node               ] node name [ntIFoHQ] derived from node ID [ntIFoHQnTAahC7_0cEt32Q]; set [node.name] to override
[2017-02-13T09:17:03,257][INFO ][o.e.n.Node               ] version[5.2.0], pid[1], build[24e05b9/2017-01-24T19:52:35.800Z], OS[Linux/4.4.43-boot2docker/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/1.8.0_111-internal/25.111-b14]
[2017-02-13T09:17:05,249][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [aggs-matrix-stats]
[2017-02-13T09:17:05,250][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [ingest-common]
[2017-02-13T09:17:05,251][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [lang-expression]
[2017-02-13T09:17:05,251][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [lang-groovy]
[2017-02-13T09:17:05,251][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [lang-mustache]
[2017-02-13T09:17:05,251][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [lang-painless]
[2017-02-13T09:17:05,251][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [percolator]
[2017-02-13T09:17:05,251][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [reindex]
[2017-02-13T09:17:05,254][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [transport-netty3]
[2017-02-13T09:17:05,254][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] loaded module [transport-netty4]
[2017-02-13T09:17:05,254][INFO ][o.e.p.PluginsService     ] [ntIFoHQ] no plugins loaded
[2017-02-13T09:17:05,677][WARN ][o.e.d.s.g.GroovyScriptEngineService] [groovy] scripts are deprecated, use [painless] scripts instead
[2017-02-13T09:17:10,757][INFO ][o.e.n.Node               ] initialized
[2017-02-13T09:17:10,757][INFO ][o.e.n.Node               ] [ntIFoHQ] starting ...
[2017-02-13T09:17:11,015][WARN ][i.n.u.i.MacAddressUtil   ] Failed to find a usable hardware address from the network interfaces; using random bytes: 07:0a:ef:37:62:95:b2:77
[2017-02-13T09:17:11,198][INFO ][o.e.t.TransportService   ] [ntIFoHQ] publish_address {192.168.99.100:9300}, bound_addresses {[::1]:9300}, {127.0.0.1:9300}
[2017-02-13T09:17:11,203][INFO ][o.e.b.BootstrapChecks    ] [ntIFoHQ] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks
[2017-02-13T09:17:14,351][INFO ][o.e.c.s.ClusterService   ] [ntIFoHQ] new_cluster_manager {ntIFoHQ}{ntIFoHQnTAahC7_0cEt32Q}{cW1MZt0-RmutLXz_Tkm8mw}{192.168.99.100}{192.168.99.100:9300}, reason: zen-disco-elected-as-cluster-manager ([0] nodes joined)
[2017-02-13T09:17:14,395][INFO ][o.e.h.HttpServer         ] [ntIFoHQ] publish_address {172.17.0.2:9201}, bound_addresses {[::]:9201}
[2017-02-13T09:17:14,396][INFO ][o.e.n.Node               ] [ntIFoHQ] started
[2017-02-13T09:17:14,423][INFO ][o.e.g.GatewayService     ] [ntIFoHQ] recovered [0] indices into cluster_state
[2017-02-13T09:17:44,398][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:17:44,398][INFO ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-02-13T09:18:14,434][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:18:44,438][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:18:44,438][INFO ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-02-13T09:19:14,443][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:19:44,446][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:19:44,447][INFO ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-02-13T09:20:14,453][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:20:44,459][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:20:44,459][INFO ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-02-13T09:21:14,467][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:21:44,471][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:21:44,471][INFO ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-02-13T09:22:14,482][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:22:44,485][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node
[2017-02-13T09:22:44,485][INFO ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] rerouting shards: [high disk watermark exceeded on one or more nodes]
[2017-02-13T09:23:14,497][WARN ][o.e.c.r.a.DiskThresholdMonitor] [ntIFoHQ] high disk watermark [90%] exceeded on [ntIFoHQnTAahC7_0cEt32Q][ntIFoHQ][/usr/share/opensearch/data/nodes/0] free: 1gb[5.7%], shards will be relocated away from this node


Echo "part" of array (decoded from JSON)

I'am quite new to JSON and more "advanced" arrays. Therefore I don't know what I should search for...

I have this "JSON array" (what do you call it?):

{
   "id": "321123321",
   "statuses": {
      "data": [
         {
            "message": "testmessage",
            "updated_time": "2012-12-25T16:33:29+0000",
            "id": "123321123"
         }
      ],
      "paging": {
         "previous": "1",
         "next": "1"
      }
   }
}

I want to create a variable from "message" that is called $message and a variable from "up_datedtime" that is called $updated.

To get id I simple:
$json_a=json_decode($string,true);
$id $json_a['id'];

And for statuses:
$json_a=json_decode($string,true);
$status = $json_a['id']['statuses'];

But when I try to get "message" I get " Cannot use string offset as an array in":
    $message = $json_a['id']['statuses']['data']['message'];

How do I get $message from the array the proper way?


How to calculate the sum of variables in PHP

It calculates, but starting from the second row.

<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$sold= array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  $sold=$row['contract']+$row['tva'];
  echo "<table><tr><td>" . $sold. "</td></tr></table>";
}
?>


pandas DF column max difference between pair of values recursively

I have a DataFrame with a column 'col1' with integers in it.
The DF may have anything from 100 up to 1mln rows.
How to compute difference between pair of values in the col1 such as:

row2 - row1
row3 - row2
row4 - row3
etc

and return max difference?

I know how to use loc, iloc but do not know how to force it to go through pair of values and move to next pair


Share video on a page on facebook

I want to share a video from my site on a page on facebook, not on my profile.

For Eg: I want to share video on https://www.facebook.com/pages/Opticians/108277472608071

I have a button as post to wall. On clicking it the video should get uploaded on the above mentioned page. I searched a lot for this but I ended in getting only share button which shares the post/video to our profile. How can i share that video on a different page on facebook?

Any Help would be greatly appreciated.


Can't Get One Complete Background In Frameset

I am trying to get one complete background in a frameset...
I can't seem to do it - when I add < body > the color background I want shows but not the framset.
Is there an easy way to put a complete background of color or color fades first and then have the framset showing with the background colors still there...

I have tried a < div class=propercolor > and no luck - and as related the body tag doesn't work either.  I find online where I can have each frameset specify a color = but when I do that - the fading gets wrecked...

This class is just an example of fading - which works elsewhere...

Any help is appreciated - thx.

      .propercolor {
      background-image: -webkit-gradient(
  linear,
  left top,
  left bottom,
  color-stop(0, white),
  color-stop(1, red)
      );

      <HTML>

      <frameset rows="15%,75%,10%">

        <frame src="pit.cfm" frameborder="0" scrolling="no">

          <frameset cols="60%,40%">
           <FRAME src="schedule.cfm" name="pi" frameborder="0" scrolling="no">
           <FRAME src="banners.cfm" name="banner" frameborder="0" scrolling="no">
          </frameset>

        <frame src="pib.cfm" frameborder="0" scrolling="no">

      </frameset>

      </HTML>


XCode 4 problem, always showing target view when stops at a break point

I just upgraded to XCode 4.0.2 and ran into a strange issue. Every time when the app stops at a breakpoint, XCode shows the target view instead of the .m file. When I manually click the file and show it, and click step, then the IDE switches to the target view again. This makes debugging virtually impossible. THis only happens to my own project. Sample projects work fine. Please help, it drives me nuts and I can not find where did I get the settings wrong.

P.S, this project worked fine on XCode 3, after upgrading to Xcode 4 I had problems with my targets. After wrestling a while with the schemes it finally builds and runs fine, but I can not do debugging when making changes because of this. I am not sure if I messed up some settings during the time to change the scheme and target settings.
Thanks
Ray


How to block a div when arriving at the top of the window during a page scroll

On an internet browser, I would like to have a div (typically a menu or an information bar) that stops moving when reaching the top of the screen during a page scroll. Note that I do not whant this 'div' to be stuck at one position all the time : It is a normal 'div' that follows page scrolling except when reaching the top of the screen.
I am not sure it can be done only with css, if not, may be you could help me with jquery...


How to use PayPal permission token to obtain transaction information

PayPal API seems to be a disaster, but I'm battling through...

So far I have been able to generate a token and verification code from https://api-3t.paypal.com/nvp

The token and verification are authorised to use the TRANSACTION_SEARCH, TRANSACTION_DETAILS and ACCOUNT_BALANCE scopes.

But I can't find anywhere how to actually get transaction details or balances using the token and verification code.

My current code that is working uses the NVP API, but this has been validated by manually granting permissions from within PayPal. I can't see how to do this using the token and verify code.

My current code (if it helps) which is working well, but without using the token and verification:

$vars['USER'] = $api_username;
$vars['PWD'] = $api_password;
$vars['SIGNATURE'] = $api_signature;
$vars['STARTDATE'] = '2016-11-30T00:00:00Z;
$vars['SUBJECT'] = 'my@paypalemail.com';
$vars['METHOD'] = 'GetBalance';

$vars = http_build_query($vars);

$curl = curl_init('https://api-3t.paypal.com/nvp');
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS,  $vars);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
$result = curl_exec($curl);

How do I convert this to use my App ID, token and verify_code generated by PayPal Permissions API?

Thanks!


C#, Delete first row from gridview element

This has been asked many times, but I can't seem to find a direct answer.

Using C#, I use a datatable to fill a gridview. The first row of my datatable contains the table headers, so I loop through that row and fill the gridview header row. But now I need to get rid of that first row (the header row) in the table. I've looked all over, and all sources agree that the correct syntax is:

   strSQL = "SELECT * FROM [Station ID Request$]";
   OleDbDataAdapter adaBatch = new OleDbDataAdapter(strSQL, strConnExcel);
   DataTable dtBatch = new DataTable();
   adaBatch.Fill(dtBatch);
   gv_stations.DataSource = dtBatch;
   gv_stations.DataBind();
   //  Fill gridview headers with first row of data (spreadsheet headers)
   int i = 0;
   foreach (DataColumn col in dtBatch.Columns)
   {
       gv_stations.HeaderRow.Cells[i].Text = dtBatch.Rows[0][i].ToString();
       i++;
   }
   //  Remove the first line of the gridview (contains header info)
   gv_stations.DeleteRow(0);

Everything works but the last line, which gives me this error:

System.Web.HttpException (0x80004005): The GridView 'gv_stations' fired
event RowDeleting which wasn't handled. at
System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs e)
at System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32
rowIndex) at System.Web.UI.WebControls.GridView.DeleteRow(Int32 rowIndex)

Every resource I've tried says that last line should be OK. Can anyone tell why I'm getting that error?

EDIT: Here is my gridview object, as requested.

<asp:GridView ID="gv_stations" runat="server"
    AutoGenerateColumns="True"
    CssClass="c_gvv c_gvv_stations_results"
    style="white-space:nowrap;">
</asp:GridView>


Horizontal scroll in DIV with many small DIV's inside (no text)

Objective

I have a main DIV with fixed height and width, and in that I want have lots of small DIV's to float freely. I have more small DIV's than can fit in the main DIV. Then it seems that by default is disappear small DIV's down outside the main DIV. I want them instead to disappear to the right.

I want to trigger a horizontal scrollbar, but no vertical.

Background

I tested this with white-space: nowrap as described at http://www.webmasterworld.com/forum83/8844.htm

And it works perfect if I have only text or images in the main DIV.

Question

But how do I do when the main DIV contains only small DIV's?


MYSQL inefficient count on large tables

I have a table with this structure:

id(int), aff_id(int)

Field aff_id is 0 if the user was not affiliated by anybody and he registered directly, or larger than 0, if the user was affiliated by some other player and in that case it takes the value of the ID of the affiliate.

user #47 was affiliated by user #55, therefore in the database,
we will have this entry: id=47,aff_id=55

I want to see how many users did a good job and affiliated/brought in other users (basically I want to see how many users are affiliates). For that I need to go through each user and see if there is anybody that has his user id inside the aff_id field.
I do not want to see how many users have aff_id > 0, because that is basic stuff and it would mean how many players were affiliated.

For my requirement, I run this query:

SELECT
COUNT(*),
(SELECT COUNT(*)
FROM `users`
WHERE `aff_id`=`u`.`id`
) AS total_pl
FROM `users` u
HAVING total_pl>0

Problem is that the query takes around 30 seconds on a database with 2000 entries.

If I try a different way, it takes even more time ... around 40 seconds:

SELECT
  COUNT(*)
FROM `users` u
WHERE u.id IN (
  SELECT DISTINCT (`aff_id`)
  FROM users
  WHERE aff_id<>0
)

What other options do you suggest that I should try for optimisation?

I was thinking to modify the first query to stop counting how many affiliated players does each user have and to find out instead only if each user has 0 affiliated players or at least 1 affiliated player, but there doesnt seem to be any difference.


Installing Rubymine Debugger IDE after setting up rbenv global 2.1.2?

I've been trying to set up the debugger in Rubymine 2016.3. The initial error I was receiving stated that I didn't have permission to write in the version of ruby already installed in my mac os.

So I downloaded rbenv and set up a new ruby 2.1.2 environment by using rbenv global 2.1.2 and checking to make sure it was being used with ruby -v.

After selecting 2.1.2 default in preferences > Ruby SDK and Gems and running the debugger, I'm still receiving this error:

Error running testa: Failed to Install Gems. Following gems were not installed: /Applications/RubyMine.app/Contents/rb/gems/ruby-debug-ide-0.6.1.beta3.gem: Error installing ruby-debug-ide-0.6.1.beta3.gem: ERROR: Failed to build gem native extension. /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby mkrf_conf.rb Installing base gem You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

Does anyone know how to fix this using rbenv?


Javascript for radio buttons in Adobe LiveCycle

How can I do the following:
1. I have a table with columns for Yes and No. I wanted a radio button to a cell (one for Yes and another for No) that when I click Yes, No is off and if click No, Yes is off.

How can I make the radio buttons work that if I click the radio button (say the Yes button) it is on (similar to #1 above) but if I click it again, it turns off without turning on the other radio button (the No button).

I really would appreciate any help.

Regards,


DateTimeField without time

class Data(models.Model):
    time = models.DateTimeField()

I have in my variable:

var = 2013-01-17 17:30

Data.objects.filter(time=var)

I need all Data from this day(2013-01-17 - without time)

How to do?


"config" scripts exist outside your system or Homebrew directory

Ran "brew doctor" and got some errors.  I managed to fix the path issue by following the advice at this link: How to modify PATH for Homebrew?.

However, completely lost with what to do with the following error:

Warning: "config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.

Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:

/opt/sm/pkg/active/bin/curl-config
/opt/sm/pkg/active/bin/ncurses5-config
/opt/sm/pkg/active/bin/ncursesw5-config
/opt/sm/pkg/active/bin/pkg-config
/opt/sm/pkg/active/bin/xml2-config
/opt/sm/pkg/active/bin/xslt-config

Noob. Running OSX. Appreciate any assistance from wiser Jedis...


How to use MSBuild to xcopy only modified or new files recursively?

I need some help using MSBuild to xcopy files to two directories.

First I found out about Sayed's after.xyz.sln.targets.  This will ensure that copy file tasks will run regardless of actual Build occurs or not.

I wanted to use that to copy only new or modified only files to two target directories.  So I need some sort of comparison code also.  Steps that I can think of.

compare dir1 to dir2 and find any new or modified files in dir1.

copy those files to dir2 recursively.

then copy the exact file sets to dir3 recursively.

TIA.


Easiest way to make http requests in java

I'm looking for a maven artifact or some pre-existing framework that will turn making http requests into a 1 liner. For those familiar with Ruby, I'm thinking about something alomg the lines of Httparty which supports get, put, post... etc.

ex:

Response response = SomeLibrary.get("https://api.google.com/maps")
int code = response.code
String body = response.body


How to deserialize json array in c#

I am trying to deserialize the following JSON file: http://komunikaty.tvp.pl/komunikatyxml/malopolskie/wszystkie/0?_format=json

My c# code:

MemoryStream stream1 = new MemoryStream();
StreamWriter writer = new StreamWriter(stream1);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ApiRegionalne));
writer.Write(json);
writer.Flush();
stream1.Position = 0;
dane = (ApiRegionalne)ser.ReadObject(stream1);

And my classes:

[DataContract]
public class newses
{
    public int id;
    public string title;
    public bool shortcut;
    public string content;
    public bool rso_alarm;
    public string rso_icon;
    public string longitude;
    public string latitude;
    public int water_level_value;
    public int water_level_warning_status_value;
    public int water_level_alarm_status_value;
    public int water_level_trend;
    public string river_name;
    public string location_name;
    public string type;
}

[DataContract]
public class ApiRegionalne
{
    [DataMember(Name = "newses")]
    public newses[] newses;
}

The JSON deserializer doesn't throw any exceptions, but my data is nevertheless null.

What am I doing wrong?


putting this javascript and php into codeigniter

<?php
// This is a code to check the username from a mysql database table

if(isSet($_POST['username']))
{
$username = $_POST['username'];

include("dbconnection.php");

$sql_check = mysql_query("SELECT user FROM {$prefix}users WHERE user='$username'");

if(mysql_num_rows($sql_check))
{
echo '<span style="color: red;">The username <b>'.$username.'</b> is already in use.</span>';
}
else
{
echo 'OK';
}}
?>

that is the check.php witch i can change with no problem to work with CI its the below i need help with!

<script src="js/jquery.js" type="text/javascript">/script>
<script type="text/javascript">
pic1 = new Image(16, 16);
pic1.src = "loader.gif";

$(document).ready(function(){

$("#username").change(function() {

var usr = $("#username").val();

if(usr.length >= 3)
{
$("#status").html('<img align="absmiddle" src="loader.gif" /> Checking availability...');

$.ajax({
type: "POST",
url: "check.php",
data: "username="+ usr,
success: function(msg){

$("#status").ajaxComplete(function(event, request, settings){

if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}});}});}
else
{
$("#status").html('The username should have at least 3 characters.');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}});});

//-->

</script>

i understand most of what this scrip is doing and i can make it work in a normal PHP but i am using code ignighter. if i am reading it right i should only have to change the line url: "check.php", and of course the original php can anyone point me in the right direction on this?


DependencyResolver does not exist in the current context when using msbuild

I am using ASP.NET MVC 4 Dependency Injection like

DependencyResolver.Current.GetService<IUserContext>();

which works fine in Visual studio but when I am building project with msbuild I always get this exception:

BaseClasses\EntityRepositoryBase.cs (68,40): errorCS0103: The name 'DependencyResolver' does not exist in the current context

what can I do? I installed mvc4 again but is the same.


Persistent sync (rsync) of local files to GCS bucket

I found out how to easily sync a local folder to my bucket at GCS.

Like gsutil -m rsync -r -d . gs://mybucket/

I want to have a "persistent" sync going on, so that whenever any local files change, they will be synced with the bucket. I haven't found any way to do this with gsutil. Is there, or is there any other approach? (Like coding a local app using json API etc). BTW, I would need to sync in realtime (or close to realtime), not with cron jobs like every 10th minute.


to UpperCase certain char-index in a string Javascript

ok I want do have a jscript below

$(document).ready(function(){
    var str = 'post'; //the subject string
    var arr =[0,2]; //to uppercase character index 0 and 2

    str = str.split("");
    for(var i = 0; i < str.length; i++){
        if($.inArray(i,arr)){
            str[i] = str[i].toUpperCase();
        }
    }
    str = str.join('');
    alert(str);
    //the result must be PoSt
});

and you may see it running here

http://jsfiddle.net/laupkram/WfUUp/

now what I want there is to provide a subject string and an array.

the subject string is the string to be process and the array contains numerical values that will represent the character index in the string to uppercase.

did i miss something with my script that's why I get undersirable results?


how to trim header and side information of mp3 frame using Naudio and c#

My Problem is to get ACTUAL DATA of a mp3 frame. For this I have used NAudio and get RawData but I think in the RawData property, it returns all the bytes of the frame including header and side information.

Code is given below:

private void button1_Click(object sender, EventArgs e)
{
    Mp3FileReader reader = new Mp3FileReader("file.mp3");
    Mp3Frame mp3Frame = reader.ReadNextFrame();
    byte [] FrameByteArray =  mp3Frame.RawData;

    BitArray bits = new BitArray(FrameByteArray);
    Console.Write(mp3Frame.RawData.Length);
    foreach (bool b in bits)
    {
        if (b == true)
        {
            Console.Write(" 1");
        }
        else
        {
            Console.Write(" 0");
       }

    }
    reader.Close();
  }

it returns all frame data in bits including header and side information.
But I only need actual data of every frame without header and side information.

Can anyone help??


Using jQuery UI to style a div

I have the jQuery UI "smoothness" theme and I would like to use the "look" to style divs on my page.  E.g. apply the gray, shaded, rounded-corner effect to a regular div that ISN'T an accordion, button, etc.

I thought it would be easy! Perhaps it is?!

Thanks!


C++ cout binary value

I have one question, I have an array of unsigned chars and I want to print them but When I use cout a different value is printed.

The array contains values in binary format, no with 0 and 1 but whit the representation witch chars.

Array to print:

[0] 147 unsigned char
[1] 252 'ü' unsigned char
[2] 170 'ª' unsigned char
[3] 194 'Â' unsigned char
[4] 108 'l' unsigned char

What I got:

ô
ⁿ
¬
┬
l

when i write it into a file, the representation is correct because I open the ofstream in binay mode but I cannot find how to do the same in cout.

Best Regards


Resulting EXE speed for C++ under VS2005, VS2008; VS2010 compilers

When I upgraded from VS6 to VS2005, I saw a 10% boost in the speed of my chess engine program with the default compile settings.

Wondering if the same is true in general, and what improvements, if any, have been made to the final output of the MS C++ compiler since then.


Inserting picture using macro vba to adopt to a merged cell or single cell

I have a problem integrating my InsertPicture code to my FitPicture macro. I'm confused on how to get the shape to resize it automatically after using Insert function. It gives me the error regarding with the object. Here's a link of the idea that I research but still can't make anything happen. Any help is appreciated. Thanks.

Here's the macro I'm using to fit the picture into a merged cell or single cell:

Sub FitPicture()
On Error GoTo NOT_SHAPE
Dim r As Range, sel As Shape
Set sel = ActiveSheet.Shapes(Selection.Name)
sel.LockAspectRatio = msoTrue
Set r = Range(sel.TopLeftCell.MergeArea.Address)

Select Case (r.Width / r.Height) / (sel.Width / sel.Height)
Case Is > 1
    sel.Height = r.Height * 0.9
Case Else
    sel.Width = r.Width * 0.9
End Select

sel.Top = r.Top + 0.05 * sel.Height: sel.Left = r.Left + 0.05 * sel.Width

Exit Sub
NOT_SHAPE:
MsgBox "Please select a picture first."
End Sub

Here's the macro I'm using to insert a picture:

Sub InsertPicture()
Dim sPicture As String, pic As Picture

sPicture = Application.GetOpenFilename _
("Pictures (*.gif; *.jpg; *.bmp; *.tif), *.gif; *.jpg; *.bmp; *.tif", _
, "Select Picture to Import")

If sPicture = "False" Then Exit Sub

Set pic = ActiveSheet.Pictures.Insert(sPicture)
With pic
.ShapeRange.LockAspectRatio = msoFalse
.Height = ActiveCell.Height
.Width = ActiveCell.Width
.Top = ActiveCell.Top
.Left = ActiveCell.Left
.Placement = xlMoveAndSize
End With

Set pic = Nothing

End Sub

How can I integrate my FitPicture code to InsertPicture code? I need to resize it automatically after inserting using my mentioned modification on FitPicture. By the way, I'm using excel 2013. Thanks mates.


Arbitrary matrix or array size in Swift

I am familiar with creating MxN matrices in Python using NumPy such as:

In [1]: import numpy as np

In [2]: np.zeros((10,5))
Out[2]:
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

In Swift, SIMD can create small matrices and perform operations on them (see below) but it appears to be limited to a max size of a 4x4 matrix.

import simd

let mat = float2x2([[1,2],[3,4]])
mat[0]*9

Is there a way to define an arbitrary sized matrix of MxN dimensions in Swift and perform operations on that matrix?


How to convert table th into li and td into <p> with javascript?

Hello I have table like this

<table>
  <tbody>
    <tr>
      <th>PROVINSI</th>
      <th>KABKOT</th>
      <th>KECAMATAN</th>
      <th>DESA</th>
    </tr>

    <tr>
      <td>KALIMANTAN TENGAH</td>
      <td>SERUYAN</td>
      <td>SERUYAN HILIR</td>
      <td>TANJUNG RANGAS</td>
    </tr>
  </tbody>
</table>

I want to convert this table into unordered list like this

<ul>
      <li>PROVINSI<p>KALIMANTAN TENGAH</p></li>
      <li>KABKOT<p>SERUYAN</p></li>
      <li>KECAMATAN<p>SERUYAN HILIR</p></li>
      <li>DESA<p>TANJUNG RANGAS</p></li>

</ul>

how can i do this with javascript?

i've tried this

function(){
    var ul = $("<ul>");
    $("table tr").each(function(){
        var li = $("<li>")
        $("th, td", this).each(function(){
            var p = $("<p>").html(this.innerHTML);
            li.append(p);
        });
        ul.append(li);
    })
    $("table").replaceWith(ul);
}

but i don't really understand how to loop over this table. sorry


Keeping shape's appearance after removing it from parent in Kineticjs

My situation is, I have shape (image) whose parent is some group. The shape, group and other possible parents may have all sorts of positions and transformations on them. When I remove the shape from the group and add it to its layer, is there an easy way to apply everything to the shape again to make it look like there was no change, on screen?

What I have done is use getAbsolutePosition, to preserve the position, but I need the transformations, such as rotation to follow along too. In the documentation, I see getAbsoluteTransform, but I see nothing about applying that transform to a shape.


Thread 1: EXC_BAD_INSTRUCTION Swift 2

I'm trying to make an app that will tell the time remaining until a specific date. Like some alarm apps say how much time until it will wake you up. I was having issues with ways of calculating this so I created my own function for it. My original version on a playground seemed to be working fine:

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

let Test = NSCalendar.currentCalendar().component(NSCalendarUnit.Day, fromDate: NSDate())

func Calculation() {

    //Months
    var month: String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MM"
        return dateFormatter.stringFromDate(NSDate())
    }

    print(month)

    //Days
    var day: String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd"
        return dateFormatter.stringFromDate(NSDate())
    }

    print(day)

    //Hours
    var hour: String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "hh"
        return dateFormatter.stringFromDate(NSDate())
    }

    print(hour)

    //Minutes
    var minute: String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "mm"
        return dateFormatter.stringFromDate(NSDate())
    }

    print(minute)

    //Current Time
    let CurrentMonths = Int(month)
    let CurrentDays = Int(day)
    let CurrentHours = Int(hour)
    let CurrentMinutes = Int(minute)

    //End Date
    let EndMonths = 11;
    let EndDays = 23;
    let EndHours = 12;
    let EndMinutes = 60;

    //Calculation

    var LeftMonths = EndMonths - CurrentMonths!
    var LeftDays = EndDays - CurrentDays! - 1
    var LeftHours = EndHours - CurrentHours! - 1
    var LeftMinutes = EndMinutes - CurrentMinutes! - 1

    //Update Labels

    //Re-Run Loop To Update Time
}
Calculation()

I had to change it a little so it would work as a standalone iOS app in Swift 2. Currently I have the error Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0) In the console it says

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) `. I checked the debug menu/console to the left of it and none of my variables are set to `nil.

Here is my ViewController.swift code UPDATED CODE To Fix Local Var Problem:

import UIKit

class ViewController: UIViewController {

    //Current Time
    var CurrentMonths:Int = 0
    var CurrentDays:Int = 0
    var CurrentHours:Int = 0
    var CurrentMinutes:Int = 0

    //End Date
    var EndMonths:Int = 0
    var EndDays:Int = 0
    var EndHours:Int = 0
    var EndMinutes:Int = 0

    //Calculation

    var LeftMonths:Int = 0
    var LeftDays:Int = 0
    var LeftHours:Int = 0
    var LeftMinutes:Int = 0

    //Define
    var month:String = ""
    var day:String = ""
    var hour:String = ""
    var minute:String = ""

    //Labels
    @IBOutlet weak var DayL: UILabel!
    @IBOutlet weak var HourL: UILabel!
    @IBOutlet weak var MinuteL: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Calculation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //Months
    func Month() {
        var month: String {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "MM"
            return dateFormatter.stringFromDate(NSDate())
        }
        print(month)
        Day()
    }

    //Days
    func Day() {
        var day: String {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd"
            return dateFormatter.stringFromDate(NSDate())
        }
        print(day)
        Hour()
    }

    //Hours
    func Hour() {
        var hour: String {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "hh"
            return dateFormatter.stringFromDate(NSDate())
        }
        print(hour)
        Minute()
    }
    //Minutes
    func Minute() {
        var minute: String {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "mm"
            return dateFormatter.stringFromDate(NSDate())
        }
        print(minute)
    }

    func Calculation() {

        //Start Calculations
        Month()

        //Current Time
        CurrentMonths = Int(month)!
        CurrentDays = Int(day)!
        CurrentHours = Int(hour)!
        CurrentMinutes = Int(minute)!

        //End Date
        EndMonths = 11;
        EndDays = 23;
        EndHours = 12;
        EndMinutes = 60;

        //Calculation

        LeftMonths = EndMonths - CurrentMonths
        LeftDays = EndDays - CurrentDays - 1
        LeftHours = EndHours - CurrentHours - 1
        LeftMinutes = EndMinutes - CurrentMinutes - 1

        //Update Labels
        DayL.text = String(LeftDays)
        HourL.text = String(LeftHours)
        MinuteL.text = String(LeftMinutes)

        //Re-Run Loop To Update Time
        Calculation()
    }

}

The error occurs on CurrentMonths = Int(month)!
All of the solutions from similar problems have not seem to work.
Also, when removing the var tag in the functions in the Calculation function, it gives me an error so I can't remove it.


How can I open the built-in browser in Visual Studio without opening a link?

When I click Ctrl + left mouse button on a link in Visual Studio, the built-in browser opens. Is it possible to open the built-in browser in Visual Studio without opening a link?

Is it possible to open browser without clicking any link in editor?


Clear Orchard CMS Database Cache

I want to manipulate data directly into database.
But the changes not reflected in Orchard Website.
How can tell to Orchard clear all database cache after making some data changes in database?


Check if component is either type

I am trying to check if a component is type TMachine or TLabel  if so i want it to free it as long as its NOT Label1 or label2

but it will not let me do an OR  on if Components[I] is (TMachine) or (TLabel) then Any way to fix this?

    procedure TfDeptLayout.FormClose(Sender: TObject; var Action: TCloseAction);
var
  I: Integer;
begin
     for I := ComponentCount -1 downto 0 do
      begin
          if Components[I] is (TMachine) or (TLabel) then
              if Components[I].Name <> Label2.Name then
                if Components[I].Name <> label3.Name then
                  components[I].Free;
      end;
end;


Disadvantages of api extension with predefined (enumerated) option list instead of individual arguments

I currently need to extend a function's API that is very often used in my aplication with a new (boolean) parameter. I also foresee that, as more features are added to the program, the same function may (not yet certain) need more functionality, that (if needed) can be controled by boolean parameters. The extra functionality will only be needed by new function calls, not by the existing ones.

So, to simplify its extension in the future, I plan on adding two or tree extra enumerated parameters to its API, so that new features can be added without chasing and editing all fuction calls everytime something is added. So, instead of extending to this:

function(currparams..., bool option1, bool option2, bool option3, bool option4);

It would extend to this:

typedef enum{
    noopt,
    opt1,
    opt2,
    opt3,
    ...
}APIoptions;

function(currparams..., APIoptions option1, APIoptions option2);

As long as the enumerated arguments I add now are enough for the future needs, this should make extending the API easier. However I don't recall seing this type of programming in the wild and would like to understand its disadvantages and potential problems and why it wouldn't be more often used.

Thanks in advance.


How to display two plot in a specific position with Matlab

Hi to all,

When I run a Matlab code which generate two plot, these are overplotted (the second over the first).

I would like obtain a result as this figure, where the two plots are like in a subplot(211) and subplot(212), the first and the second in two colons, but without using subplot.

It is possible?

UPDATE

I generate this two plot with two subfuncion:

function create_figure(X1, YMatrix1, p)
%CREATE_FIGURE(X1, YMATRIX1)
%  X1:  vector of x data
%  YMATRIX1:  matrix of y data
%  P: parameters used in legend

% Create figure
figure1 = figure('Name','Acceleration Power vs. Velocity LPF 1st order');
...

and

function create_figure_gamma(X1, YMatrix1, p)
%CREATE_FIGURE_GAMMA(X1, YMATRIX1, P)
%  X1:  vector of x data
%  YMATRIX1:  matrix of y data
%  P: parameters used in legend

% Create figure
figure1 = figure('Name','gamma trend vs. Velocity');
...

Of course, I can give in output the parameter figure1, writing:

function figure1 = create_figure(X1, YMatrix1, p)

I think that which this parameter is possible set the position of the two plots, but I do not know the procedure respect the generic window size.


Can I use ReportPortal with nightwatchjs?

Can I use ReportPortal with nightwatchjs + mocha?
If someone has experience, then tell in details please!
P.s.: Now for reporting I use mochawesome-report-generator.


How to update angular 1.2 service to 1.5 in angular 2 style

https://github.com/snapjay/ngCart/blob/main/src/ngCart.js#L30
I need to update this repo from 1.2 angular to 1.5 and in 2.0 in future
I am start to upgrade this example from addToCart component

import * as angular  from 'angular';
import angularMeteor from 'angular-meteor';

import { name as ngCart } from '../../../api/ngCart/ngCart';

import './addToCart.html';
class AddToCart {
    constructor($scope, $reactive) {//, ngCart
        //ngCart object here should service return function?
        //angular_angular.js?hash=08f63d2…:13439 TypeError: _apiNgCartNgCart.name.getItemById is not a function
        'ngInject';
        $reactive(this).attach($scope);

        if (this.inCart()) {
            this.q = ngCart.getItemById(this.id).getQuantity();
        } else {
            this.q = parseInt(this.quantity);
        }

        this.qtyOpt = [];
        for (var i = 1; i <= this.quantityMax; i++) {
            this.qtyOpt.push(i);
        }
    }

    inCart() {
        console.log("cart " + ngCart);
        return ngCart.getItemById(this.id);
    }

}

const name = 'addToCart';

// create a module
export default angular.module(name, [
    angularMeteor,
    ngCart
]).component(name, {
    templateUrl: `imports/ui/components/${name}/${name}.html`,
    controllerAs: name,
    bindings: {
        id: '@',
        name: '@',
        quantity: '@',
        quantityMax: '@',
        price: '@',
        data: '='
    },
    controller: AddToCart
});

and it gives me following error

TypeError: _apiNgCartNgCart.name.getItemById is not a function
    at AddToCart.inCart (addToCart.js:39)

and here ngCart service

import { name as ngCartItem } from './ngCartItem';
import { name as store } from './store';

class NgCart {
    constructor($scope, $reactive, $window) {
        'ngInject';
        $reactive(this).attach($scope);
    }

    $onInit() {
        //  $rootScope.$on('ngCart:change', function(){ // i shouldn't user rooutscope here
        //     ngCart.$save();
        // });
        if (angular.isObject(store.get('cart'))) {
            this.$restore(store.get('cart'));
        } else {
            this.init();
        }
    }

    init() {
        this.$cart = {
            shipping: null,
            taxRate: null,
            tax: null,
            items: []
        };
    };

    addItem(id, name, price, quantity, data) {

        var inCart = this.getItemById(id);

        if (typeof inCart === 'object') {
            //Update quantity of an item if it's already in the cart
            inCart.setQuantity(quantity, false);
            // $rootScope.$broadcast('ngCart:itemUpdated', inCart);
        } else {
            var newItem = new ngCartItem(id, name, price, quantity, data);
            this.$cart.items.push(newItem);
            // $rootScope.$broadcast('ngCart:itemAdded', newItem);
        }

        // $rootScope.$broadcast('ngCart:change', {});
    };

    getItemById(itemId) {
        var items = this.getCart().items;
        var build = false;

        angular.forEach(items, function (item) {
            if (item.getId() === itemId) {
                build = item;
            }
        });
        return build;
    };

    setShipping(shipping) {
        this.$cart.shipping = shipping;
        return this.getShipping();
    };

    getShipping() {
        if (this.getCart().items.length == 0) return 0;
        return this.getCart().shipping;
    };

    setTaxRate(taxRate) {
        this.$cart.taxRate = +parseFloat(taxRate).toFixed(2);
        return this.getTaxRate();
    };

    getTaxRate() {
        return this.$cart.taxRate
    };

    getTax() {
        return +parseFloat(((this.getSubTotal() / 100) * this.getCart().taxRate)).toFixed(2);
    };

    setCart(cart) {
        this.$cart = cart;
        return this.getCart();
    };

    getCart() {
        return this.$cart;
    };

    getItems() {
        return this.getCart().items;
    };

    getTotalItems() {
        var count = 0;
        var items = this.getItems();
        angular.forEach(items, function (item) {
            count += item.getQuantity();
        });
        return count;
    };

    getTotalUniqueItems() {
        return this.getCart().items.length;
    };

    getSubTotal() {
        var total = 0;
        angular.forEach(this.getCart().items, function (item) {
            total += item.getTotal();
        });
        return +parseFloat(total).toFixed(2);
    };

    totalCost() {
        return +parseFloat(this.getSubTotal() + this.getShipping() + this.getTax()).toFixed(2);
    };

    removeItem(index) {
        var item = this.$cart.items.splice(index, 1)[0] || {};
        // $rootScope.$broadcast('ngCart:itemRemoved', item);
        // $rootScope.$broadcast('ngCart:change', {});

    };

    removeItemById(id) {
        var item;
        var cart = this.getCart();
        angular.forEach(cart.items, function (item, index) {
            if (item.getId() === id) {
                item = cart.items.splice(index, 1)[0] || {};
            }
        });
        this.setCart(cart);
        // $rootScope.$broadcast('ngCart:itemRemoved', item);
        // $rootScope.$broadcast('ngCart:change', {});
    };

    empty() {

        // $rootScope.$broadcast('ngCart:change', {});
        this.$cart.items = [];
        $window.localStorage.removeItem('cart');
    };

    isEmpty() {

        return (this.$cart.items.length > 0 ? false : true);

    };

    toObject() {

        if (this.getItems().length === 0) return false;

        var items = [];
        angular.forEach(this.getItems(), function (item) {
            items.push(item.toObject());
        });

        return {
            shipping: this.getShipping(),
            tax: this.getTax(),
            taxRate: this.getTaxRate(),
            subTotal: this.getSubTotal(),
            totalCost: this.totalCost(),
            items: items
        }
    };

    $restore(storedCart) {
        var _self = this;
        _self.init();
        _self.$cart.shipping = storedCart.shipping;
        _self.$cart.tax = storedCart.tax;

        angular.forEach(storedCart.items, function (item) {
            _self.$cart.items.push(new ngCartItem(item._id, item._name, item._price, item._quantity, item._data));
        });
        this.$save();
    };

    $save() {
        return store.set('cart', JSON.stringify(this.getCart()));
    }

}

const name = 'ngCart';

// create a module
export default angular.module(name, [
    angularMeteor,
    ngCartItem,
    store
]).service(name, {
    controllerAs: name,
    controller: NgCart
});

How to import service in 1.5?
I am using angular-meteor and followed this tutorial

And also there can't be scope in service
// This controller throws an unknown provider error because
// a scope object cannot be injected into a service.

https://docs.angularjs.org/error/$injector/unpr?p0=$scopeProvider%20%3C-%20$scope%20%3C-%20ngCart


Perfectly linear spacing between gridview items

I am using following code to show the GirdView items.

<GridView
            android:id="@+id/gridView"
            android:gravity="center_horizontal"
            android:layout_below="@+id/searchLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:horizontalSpacing="10dp"
            android:numColumns="3"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" />

Each GridItem (ImageView) is of size 92dp

What i want is to show only 3 Columns or 3 images each Row and each Top, bottom ,left right all needs to be perfectly aligned and equal.

Below is the result of above code.

It can be seen that spaces on left and right of the grid are very less as compared with the ones in between images and also between rows are very small.

Secondly, I am using 92dp. above is the result of S3, but when i use small screen the 3rd image doesn't get fit like in 320 dp screen.

Shouldn't using "dp" automatically adjust according to screen size?


OpenGL opensearch snapshot for multi-sampling giving odd colors in iOS

When trying to get opengl view snapshot as UIImage for multi-sampling the image colors are different.

When multi-sampling is off, it is proper.
This is how I am taking the snapshot:

- (UIImage*)snapshot
{

    GLint backingWidth, backingHeight;

    backingWidth = framebufferWidth;
    backingHeight = framebufferHeight;

    NSInteger myDataLength = backingWidth * backingHeight * 4;

    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, backingWidth, backingHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    // gl renders "upside down" so swap top to bottom into new array.
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);

    for(int y = 0; y < backingHeight; y++) {
        for(int x = 0; x < backingWidth * 4; x++) {
            buffer2[y*4*backingWidth + x] = buffer[(backingHeight - y -1 ) * backingWidth * 4 + x];
        }
    }
    // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, myProviderReleaseData);

    // prep the ingredients
    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * backingWidth;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast ;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

    // make the cgimage
    CGImageRef imageRef = CGImageCreate(backingWidth, backingHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

    // then make the uiimage from that
    UIImage *image1 = [UIImage imageWithCGImage:imageRef];

    CGImageRelease(imageRef);
    CGColorSpaceRelease(colorSpaceRef);
    CGDataProviderRelease(provider);
    free(buffer);

    return image1;
}

Here are the result of taking the snapshot :

First one is the opengl view I am drawing and second image is the snapshot of the image I am getting for the above mentioned code.

I am not using GLKit framework. want to know why multisampling is messing up the snapshot.


geting server IP that post data

I am POSTing some data from one server to another using following code:

      $data2 = http_build_query(
          array(
              'desc' => $desc
          )           );
                  $options = array('http' =>
          array(
          'method'  => 'POST',
          'header'  => 'Content-type: application/x-www-form-urlencoded',
          'content' => $data2
          )           );
              $context  = stream_context_create($options);            // post request             $result = file_get_contents($payment_url, false, $context);
      $result = @json_decode($result, true);

I would like to ensure that following POST comming from correct server so I have to check server IP posting this data. but $_SERVER['SERVER_ADDR'] give me wrong IP (actually give me destination`s server IP instead Posting server IP).


Maven alternate settings.xml when don't have option of mvn -s

We're working with an integration partner who's given us a set of bash scripts, which then call Maven projects/targets.  I'm trying to let our (shared) Jenkins server build those projects.  In Maven2, one could provide a org.apache.maven.user-settings MAVEN_OPT setting.  Maven3 no longer supports that option.

Things I've tried:

the afore-mentioned org.apache.maven.user-settings

alias mvn='mvn -s /path/to/project-settings.xml'

Things I've considered, but haven't yet tried:

Writing a wrapping mvn exec, so I can execute my job from within Jenkins and provide an alternate settings file via its means

I've seen threads where others have wrestled with this, but haven't yet seen a proposed solution.


Is there a way to tell C to never allocate memory dynamically?

I want to write a C program whose memory will be constant. It can never allocate more memory than certain amount.

int main(){
   int memory[512];
   int i = 5;
   i = i + 5;
   memory[50] = i;
};

Notice that on this example i = 5 and i = i+5 will allocate memory. I want to completely avoid the internal memory allocation procedure (which I believe is kind of slow).´Is there a way to tell C to allocate it directly on my memory array?


Deleted Module's folder before disabling it

What I did

Let's say my module was called "some_module". Without disabling from the Modules menu, I renamed that folder and changed the contents, now it's "another_module". I perceive that the site is slowing down, trying to still look for "some_module".

What I've tried and expected

I've tried clearing the cache a few times, expecting Drupal to rebuild it's module list based on what's available. However, I'm not sure how the inner-workings of enabling/disabling modules works, and I don't know if my site is still going slow because of this reason, or for another reason.

What I found in the documentation

I read some of the documentation on Drupal Modules, but it looks like there are some pretty simple functions like module_exists(), but it doesn't describe whether or not it will ever stop looking for "some_module".

My question

So, my question is: have I left behind bloated garbage that is slowing down my Drupal site by not disabling the module before renaming it?

And a bonus question...are any of these documented benchmarks applicable to this situation?


Prevent QLabel from resizing parent Widget

I have a QLabel inside a QFrame.

Sometimes I have too much text in the QLabel and it resizes the QFrame where it is in.

Now, I want to prevent the QLabel from resizing the QFrame where it resides in.
I don't want to limit the amount of lines or setting the maximum size of the QLabel because if the window size of the app increases, I do want to allow the QLabel to increase in size.

Just want to prevent the QLabel from expanding it's parent.

Any clean way to do it?


How to show the starting address of some variables in C?

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>

extern char **environ;

int global_x = 10;                  // initialised global variable
int global_y;                       // un-initialised global variable
char global_array1[] = "Hello, world!";     // initialised global array and a string literal
char global_array2[10];             // un-initialised global array
char *global_pointer1 = "bye!";         // global pointer to a string literal
char *global_pointer2;              // un-initialised global pointer
float global_float = 100.1;         // initialised global variable
double global_double;               // un-initialised global variable

#define ONEGB  1073741824
#define ONEMB  1048576
#define ONEKB  1024

char *addr(unsigned long a)
{
    unsigned long r; // remainder

    r = (unsigned long) a;
    int gb = (int) ( r / ONEGB );

    r -=  gb * ONEGB;
    int mb = (int) ( r  / ONEMB );

    r -=  mb * ONEMB;
    int kb = (int) ( r  / ONEKB );

    r -=  kb * ONEKB;
    int b  = (int) ( r );

    char *p = malloc(64);

    sprintf(p, "%4dGB, %4dMB, %4dKB, %4d", gb, mb, kb, b);
    return p;
}

int f2(int x)
{
    char * f2_p;
    int f2_x = 21;

    f2_p = malloc(1000);         // dynamically allocated memory

    // print out the address of x
    // print out the addresses of f2_p, and f2_x
    // print out the starting address of the dynamically allocated memory
    .....

    L: f2_x = 10;
    return f2_x;
}

void f1(int x1, int x2, float x3, char x4, double x5, int x6)
{
    int f1_x = 10;
    int f1_y;
    char *f1_p1 = "This is inside f1";   // pointer to another string literal
    char *f1_p2;

    f1_p2 = malloc(100);         // dynamically allocated memory

    // print out the addresses of x1, x2, x3, x4, x5, x6
    // print out the addresses of f1_x, f1_y, f1_p1, f1_p2
    // print out the address of the string literal "This is inside f1"
    .....

    f1_y = f2(10);
    return;
}

int main(int argc, char *argv[])
{

    // print out the addresses of argc, argv
    // print out the starting address and end address of the command line arguments of this process
    // print out the starting address and end address of the environment of this process
    // print out the starting addresses of function main, f1, and f2
    // print out the addresses of global_x, global_y, global_array1, global_array2, global_pointer1,
    //           global_pointer2, global_float, global_double
    // print out the addresses of string literals 10, "Hello, world!", "bye", 100.1

    .....

    // call function f1 with suitable arguments such as 12, -5, 33.7, 'A', 1.896e-10, 100
    f1( .... );

    exit(0);
}

I tried to search on google, but cannot find sth useful, and in this case I just want to figure out how to print out the starting address of the dynamically allocated memory; print out the starting address and end address of the command line arguments of this process;print out the starting address and end address of the environment of this process;print out the starting addresses of function main, f1, and f2.
anybody can help me?..thank you!


Parsing a MIME-Message using anmar.SharpMimeTools

I'm trying to parse a MIME-Message, using SharpMimeTools and some sample Mime Messages from Hunny Software. I managed to create a new Message from a file and save the Decoded Body to a file (it's a png-Image), but the created file is corrupted. Mostly the the example file and the one I've exracted look the same, but there are differences.

The files can be found here:

The original Message as a Text-File: m0013.txt

The origninal PNG-Picture: Blueball_original.png

The extracted, corrupted PNG-Picture:  Blueball.png

An excerpt of the Hex-View of the files:

Original:

89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52
00 00 00 1b 00 00 00 1b 08 03 00 00 00 ba 0a 04
67 00 00 03 00 50 4c 54 45 ff ff ff 00 00 08 00
00 10 00 00 18 00 00 00 00 08 29 00 10 42 00 10
4a 00 08 31 00 10 52 08 21 73 08 29 7b 08 29 84
08 21 6b 00 18 5a 00 08 39 08 21 63 10 39 9c 18
42 a5 18 42 ad 18 42 b5 10 39 a5 10 31 94 00 18

Extracted:

3f 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52
00 00 00 1b 00 00 00 1b 08 03 00 00 00 3f 0a 04
67 00 00 03 00 50 4c 54 45 3f 3f 3f 00 00 08 00
00 10 00 00 18 00 00 00 00 08 29 00 10 42 00 10
4a 00 08 31 00 10 52 08 21 73 08 29 7b 08 29 3f
08 21 6b 00 18 5a 00 08 39 08 21 63 10 39 3f 18
42 3f 18 42 3f 18 42 3f 10 39 3f 10 31 3f 00 18

... and finally, this is the code I'm using:

public void MIMETest()
{
    FileStream fileStream = new FileStream(@"D:\m0013.txt", FileMode.Open);
    SharpMimeMessage m = new SharpMimeMessage(fileStream);
    fileStream.Close();
    parseMessage(m);
}

public void parseMessage(SharpMimeMessage message)
{
    if (message.IsMultipart)
    {
        foreach (SharpMimeMessage subMessage in message)
        {
            parseMessage(subMessage);
        }
    }
    else
    {
        System.IO.File.WriteAllText(@"D:\Extracts\" + message.Name,
            message.BodyDecoded, message.Header.Encoding);
    }
}

Do you have any suggestions how to solve this problem?


Store int inside char array in C

I am trying to store int value in char array, and access it again to retrieve value later. here is what i tried, but it is not working as i am looking for.

char mem[50];
int* size = (int*)&mem[0];

char* isFree = (char*)&mem[4];

char *t = (char *)&mem[4];

Now I want to store 1234, and 'f' in the char array according to the order. (within first 5 bytes)

I am not allowed to use other variables, have to use char array.

int a = 1234;
int *size = &a;

above one is not allowed.


Composite Graph from Crossfilter Example

Starting from the payments example crossfilter (https://github.com/square/crossfilter/wiki/API-Reference) how may we create a Composite Chart with one Line Chart for each payment type (tab, visa, cash)?


Looping try-catch isn't working

How would I properly loop this try catch statement? From what I'm aware, the
playerIntInput = reader.nextInt(); within the try block is executed and it catches the exception if one exists, this should cause the loop = false to never be reached. Then it output the message in the catch block and it should loop back to the try and ask for input again. Instead I just get an infinitely looped output from the catch block.

void CheckInput(int playerIntInput) {
    boolean loop = true;

    while(loop=true) {
        try {
            playerIntInput = reader.nextInt();
            loop = false;
        }
        catch(InputMismatchException e) {
            System.out.println("Invalid character was used, try again.");
        }
    }
}


Using Dart's call() method with generics

I'm trying to write a class which can be called like a function, using generics like so:

typedef T FooFunction<T>(T input);

class Foo<T> {
  final FooFunction fooFunction;

  Converter(FooFunction<T> this.fooFunction);

  T call(T input) => this.fooFunction(input);

  static final Foo<String> stringFoo = new Foo<String>((String input) => input.trim());

  static final Foo<int> intFoo = new Foo<int>((int input) => input * -1);
}

And I am trying to call it like so:

String bar = Foo.stringFoo('  Hello World     ');
int baz = Foo.intFoo('5');

This code works fine if I remove all the type hinting, but with the type hinting in there, the analyzer is complaining that "An argument of type 'String' cannot be assigned to the parameter type 'T'" and that "A value of type 'T' cannot be assigned to a variable of type 'String'." It's clear that what's happening here is that the analyzer is seeing the T type in the definition of Foo.call and interpreting it literally, rather than in the context of the generic type.

If I change my calls to the following:

String bar = Foo.stringFoo.fooFunction('  Hello World     ');
int baz = Foo.intFoo.fooFunction('5');

so that they are no longer using the call method, the analyzer understands what's happening just fine.

Am I doing something wrong in how I'm declaring the call method? Is there a way to use the call method while maintaining the proper type hinting and static analysis the same as if I were to call the method directly? Or am I doing everything right and I just need to submit a bug report to the Dart devs?


Is there a simple way in Magento to just include something?

I'm currently working on a simple process where I've built a controller that lets me know if a person's browser is not running something comparable to the setup I'm putting together. If I go to http://example.com/useraction/index/checkbrowser then the code will either return a commented line that reads <!--- GOOD TO GO ---> or it will return an image and link to encourage the user to upgrade their browser.  I'm doing this through a controller that I have built because it does seem to work as is without all of that caching that Magento does. Let's face it, if I were to do this on the view (even though I would think of this as something that normally SHOULD be on the view) then the proper browser information would not return to the user.

With this in mind I have tried the following:

echo $this->getChildHtml('/useraction/index/checkbrowser');
echo $this->getChildHtml('/useraction/index/checkbrowser',false);
echo $this->getLayout()->createBlock('page/template')->setTemplate('/useraction/index/checkbrowser')->toHtml();
include('/useraction/index/checkbrowser');

None of this is working. What am I missing?


Jasmine Ignoring Tests When Testing Promises

I have run into a bizarre problem. According to my log messages, the function I am testing is working correctly, but it seems to be ignoring any expect assertions I try to supply it.

This is the method under test:

getSessionContext(): Promise<ISessionContext> {
    let query = '{\
        user {\
            userId\
            clientId\
            partnerId\
            userType\
            visibleId\
            firstName\
            lastName\
            emailAddress\
            profileImageUrl\
        }\
        partner {\
            id\
            clients {\
                clientId\
                partnerId\
                clientName\
            }\
        }\
    }';

    let success = action("AuthService.getSessionContext", (sessionContext: ISessionContext) => {
        if (!sessionContext.user) {
            throw new Error('Request failed');
        }

        this.sessionContext = sessionContext;
        this.userInfo = sessionContext.user;
        this.activeClientId = this.userInfo.clientId; //default to primary client
        this.isLoggedIn = true;

        return sessionContext;
    });

    return this.graphQLService.query({query}, {unscoped: true})
        .then(success, (data) => {
            console.error('Unable to get session information', data);
        }) as Promise<ISessionContext>;
}

and this is my current spec:

fdescribe('::getSessionContext', () => {
    it('returns a valid sessionContext', () => {
        spyOn(svc.graphQLService, 'query').and.returnValue(promise_STUB);

        console.log(`sessionContext BEFORE ${JSON.stringify(svc.sessionContext)}`);
        expect(svc.sessionContext.user).toBeFalsy();
        console.log(`userInfo BEFORE ${JSON.stringify(svc.userInfo)}`);

        svc.getSessionContext().then
        (
            (result) => {
                console.log(`****************************`);
                console.log(`final result ${JSON.stringify(result)}`);
                console.log(`sessionContext AFTER ${JSON.stringify(svc.sessionContext)}`);
                expect(svc.sessionContext.user).toEqual({});

                console.log(`userInfo AFTER ${JSON.stringify(svc.userInfo)}`);
                expect(svc.userInfo).toEqual(promiseValue.user);

                //FIXME expect statements are being ignored
                expect(true).toBeFalsy();
                done();
            }
        );
    });
});

This is the terminal output:

LOG: 'sessionContext BEFORE {"partner":{"clients":[{"clientId":1234},
{"clientId":1235},{"clientId":1236},{"clientId":1237}]}}'
LOG: 'userInfo BEFORE {"partnerId":1234,"clientId":1235}'
LOG: '****************************'
LOG: 'final result {"user":{}}'
LOG: 'sessionContext AFTER {"user":{}}'
LOG: 'userInfo AFTER {}'

As you can see, the terminal output confirms the function is working. However it is completely ignoring any expect statements I try to make. Any ideas on why this is occurring?


UITableView weird separator line color

i have a problem in setting UITableViewCell background color. I wanna change it into my own color, so I use this code to change that background color :

UIView *bg = [[UIView alloc] init];

    bg.backgroundColor = [ColorManager backgroundInput];
    bg.layer.masksToBounds = YES;
    [cell setSelectedBackgroundView:bg];

I implement this code in CellForRowAtIndexPath method.

The weird thing I have is, when i tap into a cell, the separator line color being highlight just like the image below. I just wanna make it still dark, anybody have idea?

Thank you


What is null key encryption?

In the movie Dark Knight, the batman builds some ultra powerful sonar monitoring system and encrypts it will Null Key Encryption.

I was reading this RFC but couldn't comprehend it. It says something like this

However there are cases when only authentication
  and integrity protection is required, and confidentiality is not
  needed or not permitted.

And in the end he tells Fox

Type in your name when you are finished.

If its that simple, why encrypt it ?


remove items with low frequency

Let's consider the array of length n:

y=np.array([1,1,1,1,2,2,2,3,3,3,3,3,2,2,2,2,1,4,1,1,1])

and the matrix X of size n x m.

I want to remove items of y and rows of X, for which the corresponding value of y has low frequency.

I figured out this would give me the values of y which should be removed:

>>> items, count = np.unique(y, return_counts=True)
>>> to_remove = items[count < 3]                           # array([4])

and this would remove the items:

>>> X=X[y != to_remove,:]
>>> y=y[y != to_remove]
array([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1])

While the code above works when there is only one label to remove, it fails when there are multiple values of y with low frequency (i.e. y=np.array([1,1,1,1,2,2,2,3,3,3,3,3,2,2,2,2,1,4,1,1,1,5,5,1,1]) would cause to_remove to be array([4, 5])):

>>> y[y != to_remove,:]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: too many indices for array

How to fix this in a concise way?


Displaying images from sd card in gridview android

im Displaying images from specific folder on sd Card in GridView till know all works fine all images are getting displayed on the gridview but when i change the orientation of the Screen it crashes . below is my code and Crash Log:

    import java.io.File;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

        public class ImageAdapter extends BaseAdapter {
        private Context mContext;
        File root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "MYPICS" + File.separator);
        private File[] fileName = root.listFiles();
        int count=fileName.length;
        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
        return fileName.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {

            Uri uri = Uri.fromFile(fileName[position]);

        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageURI(uri);
        return imageView;
    }

}

I am getting Memory Out Error ,Below is my Logcat:

 05-16 16:18:31.218: E/AndroidRuntime(26907): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:573)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:439)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.graphics.drawable.Drawable.createFromStream(Drawable.java:657)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.ImageView.resolveUri(ImageView.java:521)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.ImageView.setImageURI(ImageView.java:305)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at com.sachin.imagegrideview.ImageAdapter.getView(ImageAdapter.java:53)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.AbsListView.obtainView(AbsListView.java:1464)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.GridView.onMeasure(GridView.java:935)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.View.measure(View.java:8313)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.View.measure(View.java:8313)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.View.measure(View.java:8313)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.View.measure(View.java:8313)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.ViewRoot.performTraversals(ViewRoot.java:845)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.os.Looper.loop(Looper.java:130)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at android.app.ActivityThread.main(ActivityThread.java:3687)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at java.lang.reflect.Method.invokeNative(Native Method)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at java.lang.reflect.Method.invoke(Method.java:507)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-16 16:18:31.218: E/AndroidRuntime(26907):    at dalvik.system.NativeStart.main(Native Method)


MySQL return inverse? results of a search or results NOT containing

A complex one here? (for me at least). I have a table called "tickets", with the "id" column being the unique key. I have another table called "Labels", which doesnt have a unique key (from the looks of it). In "Tickets" we store ticket information (messages, who made the ticket etc). We can add a label to a ticket when we create it, so that we can search for tickets with those labels e.g. "review later".

What I am trying to do, is a reverse type query e.g. show me all tickets that dont have a specific label associated to it e.g. dont show me any tickets with "review later". IF A TICKET DOESNT HAVE ANY LABELS NOTHING IS PUT IN THE LABEL TABLE. I just cant get any type of query I write, by hand or with a query builder to work.

Im my image, you can see Tickets.id has 174 against it, which is also shown in Labels.ticket_id 174 with 2 x Labels set against it.

No matter what query, join, does, does not etc I try, I either get back no results OR for some strange reason, I still get ticket 174 showing up.

Here is the most simple query I have tried.. however, I think Ive tried about 30 iterations by now from simple to very complex.

    SELECT tickets.id
    FROM
      tickets, labels_tickets
    WHERE
      tickets.id <> labels_tickets.ticket_id
    GROUP BY
      tickets.id

Can anyone suggest why this wouldnt work or think of any method to build a statment that says:

Show me all tickets.id from tickets that doesnt have the label "MyLabel" or doesnt have a value at all in the Labels table.

Many thanks!


C# mongodb driver - update in sub array not working

I have the following model (only the improtant type):

public class Model
{
    [BsonId]
    public ObjectId ModelId;
    public List<Game> Games;
}
public class Game
{
    [BsonId]
    public ObjectId GameId;
    public List<Match> Matches;
}
public class Match
{
    [BsonId]
    public ObjectId MatchId;
    public int[] Votes;
}

I have the following query:

var filter = Builders<Model>.Filter.And(
                            Builders<Model>.Filter.Eq(x => x.ModelId, modelId),
                            Builders<Model>.Filter.ElemMatch(x => x.Games, t => t.GameId == gameId));

var update = Builders<Model>.Update.Inc(x => x.Games[-1].Matches.First(t => t.MatchId == matchId).Votes[1], 2);
var options = new FindOneAndUpdateOptions<Model>()
{
    ReturnDocument = ReturnDocument.After
};

Im using FindOneAndUpdateAsync and Im able to retreive the data, but no changes are made.
Tried couple of times, still no change.

Answers to Comments:

Is something being returned?

Yes, the entire document. moreover, when I use fixed indexes, e.g: games[0].matches[0] everything works fine.

Did I try to run command in shell?

No, unfortunartly, so far I haven't tried to work with the shell


Getting null in second value of 2D array in java using apache poi

I am getting null in 2D array. When I print out values of array in calling method (hello) I am getting correct values but in callee (main method) I am getting null for second value when printed out

Following is the program

package TestngPackage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class MyReadExcel {

    public static XSSFWorkbook workbook;

    public static String[][] hello() throws IOException{

        FileInputStream fis = new FileInputStream(new File("F:\\TestExcel\\Test.xlsx"));
        workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheetAt(0);
        String s[][] = new String[2][2];

        for (int x = 0; x < sheet.getLastRowNum() + 1; x++){
            Row row=sheet.getRow(x);

            for (Cell c : row){
                int y = 0;
                s[x][y] = c.getStringCellValue();
                //System.out.println(s[x][y]);
                y++;
            }

        }

        workbook.close();
        fis.close();
        return s;
    }

    public static void main(String[] args) throws InvalidFormatException, IOException {

        String str[][];
        str = hello();

        for (int x = 0; x < str.length; x++){

            for (int y = 0; y < str[x].length; y++){
                System.out.println(str[x][y]);
            }

            System.out.println();
        }

    }

}


classes and importing modules into classes

I've managed to do almost no OOP since I've been using python and I'm trying to get familiar with writing classes and so on.

How can I break the following class into one other function. I'd like to rather than pass two arguments to the class pass the fname first and then call a method called display for all of the xml stuff that I want to print. When I attempted to do that I ended up with Global name issues with tree.

import sys
class Parser(object):

    def __init__(self, file_name, mylist):

        import xml.etree.ElementTree as etree
            self.file_name = file_name
            tree = etree.parse(self.file_name)
            for node in tree.getiterator():
                for element in mylist:
                    if element in node.tag:
                        print(node.tag)

list2 = ['KeyId','X509SerialNumber','CompositionPlaylistId']
fname = sys.argv[1]
myfileinstance =Parser(fname,list2)


Disable postman dowload popup

I use postman collection runner to test that my services are up.

I have a POST request that return a pdf file.

When it comes to that request, I have a popup asking to download the pdf file.

For testing that my request is ok, I just need the return code 200. I want to disable this download popup.

Do you know how to do that?

PS: I am using postman chrome app.


Prepend select box in text field form rails

Is there an easy way to prepend a select box or dropdown box with input to a text field in rails? I am using Twitter bootstrap, and I am able to get the select box added in, but styling is not working so well. So far I have tried two things:

1.

  <%= f.text_field :var, label: "Test Box",  class: 'form-control',
                    placeholder: "Test Stuff", prepend: f.select(:options,
                    options_for_select(...) %>

This gets the overall bootstrap styling to the select box, but for some reason it is reading :options as a label, and I can't get it to assign anything to it.

2.

  <%= f.text_field :var, label: "Test Box",  class: 'form-control',
                    placeholder: "Test Stuff", prepend: f.select_without_bootstrap(:options,
                    options_for_select(...) %>

This gets the select box in there correctly, but it is not styled (hence the without_bootstrap and I am having a difficult time styling it.

So I am wondering if there is a better way to do this, or if this is even a possibility in general? I know I could also add it as a separate field entirely and just align it next to it, but I am trying to do it into the same field. Any help is appreciated!


Converting WPF Browser App to WPF Desktop App

Without copying all the code from one project to another, is it possible to convert an XBAP browser app into a WPF forms app?


Cocos2D: Access objects CGRect from a loop

Experimenting with Cocos2D collection detection and have some questions. First, some background:

This is my method for adding a new item to my game, located in a different class than my game layer. This is located in my Item-class:

-(void) addItem:(NSString *) theFileName: (NSMutableArray *) theArray{

        CCSprite *item = [CCSprite spriteWithFile:theFileName
                                            rect:CGRectMake(0, 0, 50, 50 )];

        //Positions

        int minX = 160;
        int maxX = 360;
        int xRange = maxX - minX;
        int xCord = (arc4random() % xRange) + minX;

        item.position = ccp(xCord, -5);

    [self addChild:item];

    [theArray addObject:item];

Then I use this method in my game layer, using a reference to the Item-class called ItemManager:

[ItemManager addItem:@"box.png" :itemList];

If I want to detect collision between two sprites, in this case a box and something else, I need to be able to use the box rect created in the addItem-method.

for(CCSprite *newItem in itemList){
//(if box rectangle collides with my players or whatever

}

So how can I acces the rectangle created all the way back in the original method?

Thank you.


java Swing summation of the two columns

I have made a GUI with Swing which extends Jframe,there are 6 columns in my jtable.I read data
from a text file,in column 4 and column 5 there are values 100 and 200,so i want when user edits in column 4 and puts 160 instead of 100 column 5 automatically changes to 140 or user
edits in column 5 say 280 instead of 200 column 4 automatically changes to 20.here is my code.

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

 public class Cs extends JFrame
    {
       private JTable table;
       private DefaultTableModel model;

    public Cs()
   {
      String aLine ;
      Vector columnNames = new Vector();
      Vector data = new Vector();

      try
      {
           FileInputStream fin = new FileInputStream("cs.txt");
           BufferedReader br = new BufferedReader(new InputStreamReader(fin));

           StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");

           while( st1.hasMoreTokens() )
           {
                columnNames.addElement(st1.nextToken());
           }

           while ((aLine = br.readLine()) != null)
           {
                StringTokenizer st2 = new StringTokenizer(aLine, " ");
                Vector row = new Vector();

                while(st2.hasMoreTokens())
                {
                     row.addElement(st2.nextToken());
                }
                data.addElement( row );
           }
           br.close();
      }
      catch (Exception e)
      {
           e.printStackTrace();
      }

      model = new DefaultTableModel(data, columnNames);
      table = new JTable(model);

      JScrollPane scrollPane = new JScrollPane( table );
      getContentPane().add( scrollPane );
  }

 public static void main(String[] args)
    {
      Cs frame = new Cs();
      frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
      frame.pack();
      frame.setVisible(true);
     }

   }


How can I make this code if and else?

How can I make this code if and else?
If 'Rental' is true do this.... else... do the false bit. I'm getting lost in the PHP tags.

<?php
    if( get_post_meta($post->ID, 'Rental', true) ) {
?>
<li style="padding:3px 10px; line-height: 18px; height:34px"><strong><?php _e( 'Rental Potential / Actual', 'spanglishwebs' ) ?>:</strong> <?php
    $priceWithoutFormat = get_custom_field('Rental');
    $priceWithFormat = number_format($priceWithoutFormat, 0, ',', '.');
    echo $priceWithFormat;
?>&euro;/Annual </li>
<?php
    }
    if( get_post_meta($post->ID, 'Rental', false) ) {
?>
<li>Rental Potential / Actual: N/A</li>
<?php
    }
?>


Get an image from web with authentication

In my iOS app I need to load an image from web, but this image is on a server in which it's necessary to give username and password. I tried to use this code:

 - (void) loadImageFromWeb:(NSString *)urlImg {
    NSURL* url = [NSURL URLWithString:urlImg];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response,
                                               NSData * data,
                                               NSError * error) {
                               if (!error){
                                   UIImage* image = [[UIImage alloc] initWithData:data];
                                   [self.imageObjectScanned setImage:image];
                               } else {
                                   NSLog(@"ERRORE: %@", error);
                               }

                           }];
}

But it return an error and says that:

Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x14e6b420 {NSErrorFailingURLKey=http://54.204.6.246/magento8/media/catalog/product/cache/0/image/9df78eab33525d08d6e5fb8d27136e95/s/c/scheda_non_shop.jpg, NSErrorFailingURLStringKey=http://54.204.6.246/magento8/media/catalog/product/cache/0/image/9df78eab33525d08d6e5fb8d27136e95/s/c/scheda_non_shop.jpg, NSUnderlyingError=0x14e695c0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}

I guess this error it's because I'm not sending the username and the password. How I can send username and password to load this image?


How can I speed up Ruby/Rake task

rake --tasks takes about 18s to run. This is just the time it takes to load all the tasks, as a result any task I define will take at least this amount of time to run :

$time rake --tasks
rake db:clean           # Cleaning up database
rake passenger:restart  # Restart Application
rake spec               # Run specs

real    0m18.816s
user    0m7.306s
sys 0m5.665s

My Rakefile :

$: << "."
require "rubygems"
require "rspec/core/rake_task"

desc "Run those specs"
task :spec do
  RSpec::Core::RakeTask.new(:spec) do |t|
    t.rspec_opts = %w{--colour --format progress}
    t.pattern = 'spec/*_spec.rb'
  end
end

task :default  => :spec

Any idea why rake takes to much times ?
Thanks


Dynamically toggling tinymce toolbar with checkbox for multiple ID's?

I have multiple text boxes in a form that open with the tinymce toolbar loaded in them.
Here are some of the text areas'

<p id="rsvpInfo" style="display:none;"><label class="leftLabel">RSVP Info</label><textarea name="rsvp_info" rows="10" cols="50" class="contact mceNoEditor mceBasicEditor"></textarea></p>

<p id="abstract" style="display:none;"><label class="leftLabel">Abstract</label><textarea name="abstract" rows="10" cols="50" class="contact mceNoEditor mceBasicEditor"></textarea></p>

I am trying to make a check box outside the form which is initially checked. Once i uncheck it, then all of the tinmcy toolbars disappear and only plain text area are displayed and vice versa.

I decided to use the following code (outside the form) to implement my idea but it seems as if I am doing something wrong as nothing happens on checking/unchecking the checkbox.

<script>
    var id = 'speakerInfo';
    var id1= 'rsvpInfo';
    var id2= 'abstract';
    var id3= 'speakerBios';

    if($("#mceCheck".is(':checked'))
    {
        tinymce.execCommand('mceAddControl',false, id);
        tinymce.execCommand('mceAddControl',false, id1);
        tinymce.execCommand('mceAddControl',false, id2);
        tinymce.execCommand('mceAddControl',false, id3);
    }
    else
    {
        tinymce.execCommand('mceRemoveControl',false, id);
        tinymce.execCommand('mceRemoveControl',false, id1);
        tinymce.execCommand('mceRemoveControl',false, id2);
        tinymce.execCommand('mceRemoveControl',false, id3);
    }
</script>

Here is the code for the checkbox:

 <form>
        <input type="checkbox" name="mce" value="1" id="mceCheck" checked> tinyMCE toolbar toggle checkbox
    </form>

Can someone help me out with the jquery to dynamically change the visibilty of the tinyMCE toolbar with a checkbox?


How to enter a Date into a table in TSQL? (Error converting data type varchar to datetime)

I want to enter 30/10/1988 as the date to a DOB column in a table using a procedure

alter procedure addCustomer
@userName varchar(50),
@userNIC varchar(50),
@userPassword varchar(100),
@userDOB datetime,
@userTypeID int,
@userEmail varchar(50),
@userTelephone int,
@userAddress char(100),
@userCityID int,
@status int output
as

    declare @userID int
    declare @eid int
    declare @tid int
    declare @aid int

    execute getLastRaw 'userID','tblUserParent', @userID output

    insert into tblUserParent values (@userID, @userName, @userNIC, @userPassword, @userDOB, @userTypeID)

    execute getLastRaw 'addressID','tblAddress', @aid output

    insert into tblAddress values (@aid, @userAddress, @userID, @userCityID)

    execute getLastRaw 'emailID','tblEmail', @eid output

    insert into tblEmail values (@eid, @userEmail, @userID)

    execute getLastRaw 'telephoneID','tblTelephoneNO', @tid output

    insert into tblTelephoneNO values (@tid, @userTelephone , @userID)
    insert into tblUserCustomer values (@userID, @eid , @tid, @aid)

...but it gives an error when i enter like this '30/10/1988'

Msg 8114, Level 16, State 5, Procedure addCustomer, Line 0 Error converting data type varchar to datetime.

...but when I enter like only the 30/10/1988
Incorrect syntax near '/'

How do I fix this?