Q: Autorotate not working after reload view controller I'm trying to make an iPhone app, but i found some issue that auto-rotate is not working after I reload the view controller.
here is the code for loading the app for first run:
//AppDelegate.m:<br />
-(BOOL) application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    iPhoneScanViewController = [[iPhoneScan alloc] init];
    iPhoneScanViewController.ENAD = self;
    [window addSubview:iPhoneScanViewController.view];
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

the view controller loads, autorotate is working.
then sometimes I need to reload the view controller, this is what I use:
-(void) resetIphoneScan {
    if (iPhoneScanViewController) {
        [iPhoneScanViewController release];
    }
    iPhoneScanViewController = [[iPhoneScan alloc] init];
    iPhoneScanViewController.ENAD = self;

    for (UIView *view in [window subviews])
    {
        [view removeFromSuperview];
    }

    [window addSubview:iPhoneScanViewController.view];
    [self.window makeKeyAndVisible];
}

After I reload / resetIphoneScan, the autorotate won't work. I've spend a few days on this problem and I haven't found solution for that. I really appreciate any help.
Thanks in advance.

A: I would suggest that rather than reload the entire root VC, you have separate data classes which you can reset as necessary - after all, the VC is really for displaying it all.


Q: ExtJS: Ext.Window Prototypal inherited objects cannot be destroy [ExtJS 3.4.0]
I have a class with prototypal intheritance to Ext.Window, something like this:
function Cls_MyWindow() {

    .....

    var SaveButton = new Ext.Button({...});
    var CancelButton= new Ext.Button({...});

    .....

    Cls_MyWindow.prototype.width = Ext.getBody().getWidth() - 800;
    Cls_MyWindow.prototype.height = Ext.getBody().getHeight() - 350;
    Cls_MyWindow.prototype.plain = true;
    Cls_MyWindow.prototype.buttons = [SaveButton, CancelButton];

    .....

}

Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;

When this window is shown, it can be closed by pressing the CancelButton or the built-in "x" button of Ext.Window.
When I close it with CancelButton, SaveButton and CancelButton get destroyed normally.
But, if is closed by the "x" button, the buttons cannot be destroyed, the loop is taking forever causing my application to crashed.
After some investigation I found, in ext-all-debug.js, this:
Ext.Panel = Ext.extend(Ext.Container, {

    .....

    if(Ext.isArray(this.buttons)){
        while(this.buttons.length) {
            Ext.destroy(this.buttons[0]);
        }
    }

    .....

}

which invoke Ext.destroy, this:
Ext.apply(Ext, function(){

    .....

    destroy : function(){
        Ext.each(arguments, function(arg){
            if(arg){
                if(Ext.isArray(arg)){
                    this.destroy.apply(this, arg);
                }else if(typeof arg.destroy == 'function'){
                    arg.destroy();
                }else if(arg.dom){
                    arg.remove();
                }
            }
        }, this);
    },

    .....

}());

What appears to be is that, this.buttons -from pressing CancelButton- are Ext.Component thus, it get destroyed normally.
While this.buttons -from pressing "x"- are not, which leads to the questions.

*

*Why this.buttons are not the same objects when it is destroy via different way?

*What are the solution/options I have, if I want/need to retain the inheritance?

Shedding me some lights is most appreciated. Thank you in advance.

A: If we stay within Ext 3.4.0 boundaries, not reaching back to the plain javascript then you haven't done inheritance correctly. Inheritance is already implemented in Ext, so you do not need to go down to prototypes, creating constructors as instances of parent classes, and so on.
Let's suppose you want to define MyWindow class inheriting from Ext.Window:
Ext.define('MyWindow',{
    extend:'Ext.Window'
   ,method:function(){/* some stuff */}
   ,closable:false // don't create close box
   ,closeAction:'hide'
   // etc
});

To create an instance:
var win = Ext.create('MyWindow', {
    width:800
   ,height:600
});
win.show();

For more info see Ext.define docs.

A: After days, I've found an answered from Inheritance using prototype / “new”.
The code around my first code block at the bottom part is where I got it wrong.
Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;

The "new" at "new Ext.Window" operator there is my mistake.

*

*Why this.buttons are not the same objects when it is destroy via different way?

Answer:
Because of the new operator, when I created a new instance of Cls_MyWindow total of 2 constructors get called: one of the Cls_MyWindow, another of Ext.Window. Which then cause them to have "their own prototype of buttons" where SaveButton and CancelButton available in Cls_MyWindow as Ext.Button objects and in Ext.Window as a plain Object
Closing Cls_MyWindow with CancelButton -> The buttons can be destroyed in Ext.Window.destroy's way. Closing it with "x" -> The buttons cannot be destroyed.
Solution:
I change my code to
//Cls_MyWindow.prototype = new Ext.Window; the old one
Cls_MyWindow.prototype = Ext.Window.prototype;
Cls_MyWindow.prototype.constructor = Ext.Window;

and everything works perfectly


Q: denormalizing JSON with jq I have JSON that looks like this:
    [
      {
        "fields": {
          "versions": [
            {
              "id": "36143",
              "name": "ST card"
            },
            {
              "id": "36144",
              "description": "Acceptance test card",
              "name": "AT card"
            }
          ],
          "severity": {
            "value": "B-Serious",
            "id": "14231"
          }
        }
      },
      {
        "fields": {
          "versions": [
            {
              "id": "36145",
              "name": "ST card"
            }
          ],
          "severity": {
            "value": "C-Limited",
            "id": "14235"
          }
        }
      }
    ]

I want to convert it with jq to this:
    [
      {
        "id": "36143",
        "name": "ST card"
        "value": "B-Serious"
      },
      {
        "id": "36144",
        "name": "AT card"
        "value": "B-Serious"
      },
      {
        "id": "36145",
        "name": "ST card"
        "value": "C-Limited"
      }
    ]

Note that the first object has 2 versions, and the same severity. I have tried jq's group_by and map functions but haven't been too successful. Please help :)

A: This should work.  You wouldn't want to use a group_by here, you would do that if you were trying to go from more to less, we're going the other way.
You're combining the different versions with the corresponding severity.  Here's how you could do that.
map(.fields | (.versions[] | { id, name }) + { value: .severity.value })


Q: How to test basic example of async function in useEffect I have a simple component, it fetches async list of posts.
export const Posts = () => {
  const [list, dispatch] = useReducer(listReducer, []);

  useEffect(() => {
    fetchList(dispatch);
  }, []);

  return (

      {list.map((el) => (

{el.title}

      ))}

  );
};

In other file i keep the logic:
export const fetchList = async (dispatch) => {
  try {
    const result = await api.get('/list/') /* AXIOS */
    dispatch({ type: LIST_SUCCES, payload: result.data.list })
  } catch (error) {
    dispatch({ type: LIST_FAILURE })
  }
}

export const listReducer = (state, action) => {
  switch (action.type) {
    case LIST_SUCCES:
      return action.payload
    case LIST_FAILURE:
      return []
    default:
      throw new Error()
  }
}

I've tried multiple libraries but i'm just unable to write a test. How can i write Posts.test.js to check if post are fetched and displayed, i'm triggering async fetchList after first mount of the component (so it is not componentDidMount), and after data are fetched i dispatch action from that async function and update the list.

A: Here is the unit test solution:
index.tsx:
import React, { useReducer, useEffect } from 'react';
import { listReducer, fetchList } from './reducer';

export const Posts = () => {
  const [list, dispatch] = useReducer(listReducer, []);

  useEffect(() => {
    fetchList(dispatch);
  }, []);

  return (

      {list.map((el) => (

{el.title}

      ))}

  );
};

reducer.ts:
import axios from 'axios';
const LIST_SUCCES = 'LIST_SUCCES';
const LIST_FAILURE = 'LIST_FAILURE';

export const fetchList = async (dispatch) => {
  try {
    const result = await axios.get('/list/'); /* AXIOS */
    dispatch({ type: LIST_SUCCES, payload: result.data.list });
  } catch (error) {
    dispatch({ type: LIST_FAILURE });
  }
};

export const listReducer = (state, action) => {
  switch (action.type) {
    case LIST_SUCCES:
      return action.payload;
    case LIST_FAILURE:
      return [];
    default:
      throw new Error();
  }
};

index.spec.tsx:
import React from 'react';
import { Posts } from './';
import { mount } from 'enzyme';
import axios from 'axios';
import { act } from 'react-dom/test-utils';

describe('Posts', () => {
  afterAll(() => {
    jest.restoreAllMocks();
  });
  it('should render list correctly', async () => {
    const mResponse = { data: { list: [{ id: 1, title: 'jest' }] } };
    jest.spyOn(axios, 'get').mockResolvedValueOnce(mResponse);
    const wrapper = mount(<Posts></Posts>);
    expect(wrapper.find('ul').children()).toHaveLength(0);
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
    });
    wrapper.update();
    expect(wrapper.find('ul').children()).toHaveLength(1);
    expect(wrapper).toMatchInlineSnapshot(`
      <Component>

            jest

      </Component>
    `);
  });

  it('should render empty list when request list data failed', async () => {
    const mError = new Error('Internal server error');
    jest.spyOn(axios, 'get').mockRejectedValueOnce(mError);
    const wrapper = mount(<Posts></Posts>);
    expect(wrapper.find('ul').children()).toHaveLength(0);
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
    });
    wrapper.update();
    expect(wrapper.find('ul').children()).toHaveLength(0);
    expect(wrapper).toMatchInlineSnapshot(`
      <Component>

      </Component>
    `);
  });
});

Unit test result with coverage report:
PASS  src/stackoverflow/59197574/index.spec.tsx (12.494s)
  Posts
    ✓ should render list correctly (105ms)
    ✓ should render empty list when request list data failed (37ms)

 › 1 snapshot written.
------------|----------|----------|----------|----------|-------------------|
File        |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files   |    95.83 |    66.67 |      100 |       95 |                   |
 index.tsx  |      100 |      100 |      100 |      100 |                   |
 reducer.ts |    92.86 |    66.67 |      100 |    91.67 |                21 |
------------|----------|----------|----------|----------|-------------------|
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   1 written, 1 passed, 2 total
Time:        14.409s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59197574


Q: Oracle Performance: Partition Split vs Insert Append I am currently refactoring a data loading process in Oracle 12c and am exploring partitioning as a solution. My data is categorised by date and I have ~500k records per date which seems to fit the "minimum optimal" for partitioning, or so I am told. The original plan was to use a staging table to load the data, then add a dummy partition to the main table and perform a partition exchange. However, my data load contains data from several days rather than from one day. Preliminary research suggests there are two methods to solve this problem:
Option 1: Perform the partition exchange, then split the large partition in a loop
ALTER TABLE MAIN_TABLE ADD PARTITION DUMMY_PARTITION VALUES LESS THAN (TO_DATE('1-1-9999', 'DD-MM-YYYY'));

ALTER TABLE MAIN_TABLE
EXCHANGE PARTITION DUMMY_PARTITION
WITH TABLE STAGING_TABLE
WITHOUT VALIDATION UPDATE GLOBAL INDEXES;

BEGIN
   FOR row IN (select distinct to_char(DATE_FIELD+1, 'YYYYMMDD') DATE_FIELD from PARTITIONED_TABLE order by DATE_FIELD)
   LOOP
      EXECUTE IMMEDIATE 'ALTER TABLE MAIN_TABLE SPLIT PARTITION DUMMY_PARTITION AT (TO_DATE('''||row.DATE_FIELD||''', ''YYYYMMDD'')) INTO (PARTITION p'||row.DATE_FIELD||', PARTITION DUMMY_PARTITION) UPDATE GLOBAL INDEXES';
   END LOOP;
END;
/

Option 2: Perform an insert append
INSERT /*+ append */ INTO MAIN_TABLE SELECT * FROM STAGING_TABLE;

Somehow, it seems like splitting the partition is a slower process than doing the insert. Is this expected behaviour or am I missing something?

A: There is a fast split optimization, depending on the circumstances. However from your description, I would simply do the INSERT /+* APPEND */
You may want to employ some parallelism too, if you have the resources and you are looking to speed up the inserts.


Q: Rails and state_machine gem, when before_transition fails, transition to an error state I am using the state_machine gem to track the status of an object.  I have a before_transition process to run and if that has any errors, I would like to set the object's state to "errored" so it is no longer an active object and I am notified that something went wrong.  Below is a simplified code snippet to demonstrate what I am trying to do:
class Status < ActiveRecord::Base
  state_machine :initial => :pending do
    state :pending
    state :processed
    state :errored

    event :process do
      transition :pending => :processed
    end
    event :error do
      transition all => :errored
    end

    before_transition :on => :process, :do => :processing_task
    after_failure :on => :process, :do => :log_error
  end

  def processing_task
    puts "Processing Task Started"
    ...do some processing...
    false  #to force the before_transition task to fail
  end

  def log_error
    puts "Error detected, logging results"
    #LogUtility to store error
    error
  end
end

When I run status.process I receive the following:
BEGIN
Processing Task Started
Error detected, logging results
UPDATE SQL COMMAND, state = 'errored'
ROLLBACK

I tried to disable transactions state_machine :initial => :pending, :use_transactions => false' but that didn't make a difference.  I feel like I should be able to transition an errored state when detecting an error during a before_transition process??
UPDATE
I tried to do something like this:
def custom_process
  begin
    process!
  rescue => e
    puts e      #debugging purposes
    #log error
    error       #transition to error state
  end
end

Then i can call object.custom_process and this accomplishes my goal but I'm creating my own transition outside the state machine, which feels a little weird to me.  If this is the only way, I can implement it like this but was hoping to keep everything inside the state machine.


Q: Creating dynamic order basket using php javascript I am creating an ePos system, that adds any item user clicks to the basket and calculate the total in the end all done without total page refresh.
I tried using $_SESSION and storing as order ( [item] => [price] ) but failed, as i need to refresh.
what I need is:

*

*to display added Items [id name Qnty price]

*calculate total price of added items.

please advice me on the best method to do this.
thanks
this is what I attempter in javascript
function addItem(name, price, id)
                {

                var table=document.getElementById("basket");
                var row=table.insertRow(-1);
                var cell1=row.insertCell(0);
                var cell2=row.insertCell(1);
                var cell3=row.insertCell(2);
                cell1.innerHTML=name;
                cell2.innerHTML=1;
                cell3.innerHTML=price;
                }

but my issue was, i could not find a way to add decimals, parseFloat made alot of bugs for me

A: You should not need to refresh the page in order to save information into the PHP Session object.  PHP Session information is stored on the server, so you can do an asynchronous HTTP request to the backend, and store information the PHP Session.  I would suggest using the jQuery.ajax function (http://api.jquery.com/jQuery.ajax/) to do your async HTTP requests.  If you are not familiar with jQuery, I highly suggest you get familiar with it.  I also suggest you look into how AJAX works.
Also, if you are using the PHP session, if you are not using some kind of framework which does session management, you must make sure to call session_start() before using the $_SESSION variable.


Q: Using readAllBytes to read a file's bytes, but output is not changing when I change the file If I have a directory called "files" and I have 2 txt files in there. The files have different names, but have the same exact contents. With this code, I am not getting the same byte[] when I readAllBytes. Should I be getting the same output when I print bytes? If not, what method could I use to compare byte strands in this way? I am trying to do this: if I have 2 files with content in common but not all the same, in this case, should I have commonalities in the two byte strands also? What method would accomplish this?
public class Main {
    public static final File CWD = new File(System.getProperty("user.dir"));
    public static final File files = new File(CWD, "files");

    public static void main(String[] args) {
        for (File file: files.listFiles()){
            try {
                byte[] bytes = Files.readAllBytes(file.toPath());
                System.out.println(bytes);
                System.out.println(file.toString());
            }
            catch (IOException e){
                System.out.println("File is empty");
            }
        }
    }
}

A: You are trying to print byte[] as a String which uses String.valueOf(bytes) and appears as something like: [B@23ab930d which is [B followed by the hashcode of the array. Hence different byte arrays have different string values. Compare these:
byte[]a=new byte[]{65};
System.out.println(new String(a));
=> A
System.out.println(a);
// Prints something like:
[B@6438a396

Change to print the byte array contents converted as a String:
System.out.println(new String(bytes));

OR: read the text file as a String directly:
String contents = Files.readString(file.toPath());
System.out.println(contents);


Q: Error inserting date and time in SQL Server 2005 datetime c#? Problem saving to SQL Server 2005:
cmd = new SqlCommand("INSERT into survey_Request1(sur_no,sur_custname,sur_address,sur_emp,sur_date,sur_time,Sur_status)values(" + "'" + textBox9.Text + "'" + "," + "'" + textBox8.Text + "'" + "," + "'" + textBox5.Text + "'" + "," + "'" + textBox1.Text + "'" + "," + "Convert(Datetime,Convert(char(15),"+"'" + dateTimePicker2.Value +"'"+")" + "," + "'" + dateTimePicker1.Value.ToLongTimeString() + "'" + "," + "'" + "Active" + "'" + ")", conn);
cmd.ExecuteNonQuery();

A: You should ALWAYS use parametrized queries - this prevents SQL injection attacks, is better for performance, and avoids unnecessary conversions of data to strings just to insert it into the database.
Try somethnig like this:
// define your INSERT query as string *WITH PARAMETERS*
string insertStmt = "INSERT into survey_Request1(sur_no, sur_custname, sur_address, sur_emp, sur_date, sur_time, Sur_status) VALUES(@Surname, @SurCustName, @SurAddress, @SurEmp, @SurDate, @SurTime, @SurStatus)";

// put your connection and command into "using" blocks
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
    // define parameters and supply values
    cmd.Parameters.AddWithValue("@Surname", textBox9.Text.Trim());
    cmd.Parameters.AddWithValue("@SurCustName", textBox8.Text.Trim());
    cmd.Parameters.AddWithValue("@SurAddress", textBox5.Text.Trim());
    cmd.Parameters.AddWithValue("@SurEmp", textBox1.Text.Trim());
    cmd.Parameters.AddWithValue("@SurDate", dateTimePicker2.Value.Date);
    cmd.Parameters.AddWithValue("@SurTime", dateTimePicker2.Value.Time);
    cmd.Parameters.AddWithValue("@SurStatus", "Active");

    // open connection, execute query, close connection again
    conn.Open();
    int rowsAffected = cmd.ExecuteNonQuery();
    conn.Close();
}

It would also be advisable to name your textboxes with more expressive names. textbox9 doesn't really tell me which textbox that is - textboxSurname would be MUCH better!


Q: Spring, Annotation for Creating Current Date in Hibernate? in my Spring Application using JPA Hibernate Annotions.
In that mysql Database have table and one column called CreateDate
This column value will be added when record is inserted.
So is their any annotation for creating current Date and time?
other wise in our Hibernate bean writing setter method in that add
    private Date currrent;
    public void setCurrent(Date current)
    {
      this.current = new Date();
    }

A: I think you're looking for this:-
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "curr", length = 10)
public Date getCurrrent() {
    return this.currrent;
}

A: What Jelies mentioned is the correct approach. You simply instantiate the date object with
private Date currrent = new Date();

during object creation and then persist it.
To add on to that, its not safe to use @Temporal(TemporalType.TIMESTAMP) for storing the date and time, if there is a chance of you comparing the field current with any java.util.Date objects as the saved field will be loaded as java.sql.Timestamp. The reason is mentioned here.

Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The Timestamp.equals(Object) method never returns true when passed a value of type java.util.Date because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashcode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
  Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

The work around is to use TypeDef. This post discusses about the issue and the workaround. The code used there will be good enough for you.

A: I think the easiest way to achieve that is to initialize your field with the new Date():
private Date currrent = new Date();

IMHO, I don't recommend changing the behavior of the setter method, other developers will not expect that.
If you want this field to be filled immediately before the entity is persisted/updated, you can define a method with @PrePersist or @PreUpdate JPA annotations to populate current property then.


Q: How do I make my custom class compatible with For Each? Is it possible to make a custom container class implemented purely in VBScript (no COM objects) work with the For Each statement? If so, what methods must I expose?

A: In short, no
Why? To create an enumerable collection class to get something like
Class CTest
    ....
End Class

Dim oTest, mElement
    Set oTest = New CTest
    ....
    For Each mElement In oTest
        ....
    Next

the class MUST follow some rules. We will need the class to expose

*

*A public readonly property called Count

*A public default method called Item

*A public readonly property called _NewEnum, that should return an
IUnknown interface to an object which implements the IEnumVARIANT interface and that must have the hidden attribute and a dispatch ID of -4
And from this list or requirements, VBScript does not include any way to indicate the dispatch ID or hidden attribute of a property.
So, this can not be done
The only way to enumerate over the elements stored in a container class is to have a property (or method) that returns

*

*an object that supports all the indicated requirements, usually the same object used to hold the elements (fast, but it will expose too much information)

*an array (in VBScript arrays can be enumerated) holding references to each of the elements in the container (slow if the array needs to be generated on call, but does not return any non required information)


Q: Contact us form: Mail not received I'm trying to create a contact us form with PHP. The problem is that, I'm not receiving the email in my account. When the submit button is clicked it takes me to the mail.php page where a "thank you" message is shown.
The code is as shown below:

Contact Us

    <form action="mail.php" method="POST" class="form-horizontal">

            First Name:

                <input type="text" class="form-control" id="fname" placeholder="First Name*" name="fname" required="required">

            Last Name:

                <input type="text" class="form-control" id="lname" placeholder="last Name" name="lname" >

            Email ID:

                <input type="text" class="form-control" id="email" placeholder="Email Address*" name="email" required="required">

            Message:

                <textarea id="form_message" name="message" class="form-control" placeholder="Message*" rows="4" required="required" data-error="Please, leave us a message."></textarea>

                <button type="submit" class="btn btn-primary">Submit</button>

    </form>

The code for mail.php:
<?php
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $fname $lname \n Message: $message";
$recipient = "rubeena.ajeed@gmail.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>

A: Please try using SMTP ?
PHPmailler.class
Download : https://github.com/PHPMailer/PHPMailer


Q: R: Removing Non-Corresponding Rows in Data Frames I have two data frames - germany_yields and italy_yields. If a specific date that appears in one of germany_yields's rows is not present in any of italy_yields's rows, then I would like to remove this row from germany_yields (and vice versa).
For example, here are five rows taken from either of the frames:
germany_yields:                        italy_yields:

            Date Yield                             Date Yield
642 Jan 06, 2008 4.087                 642 Jan 06, 2008 4.461
643 Dec 30, 2007 4.193                 643 Dec 30, 2007 4.522
644 Dec 23, 2007 4.368                 644 Dec 16, 2007 4.563
645 Dec 16, 2007 4.268                 645 Dec 09, 2007 4.601
646 Dec 09, 2007 4.304                 646 Dec 02, 2007 4.420
647 Dec 02, 2007 4.105                 647 Nov 25, 2007 4.439

The date Dec 23, 2007 is present within germany_yields (row 644), but not within italy_yields. I would therefore like to remove row 644 from germany_yields. How can I do this?
For reference, here is the code I have so far:
germany_yields <- read.csv(file = "Germany 10-Year Yield Weekly (2007-2020).csv")
italy_yields <- read.csv(file = "Italy 10-Year Yield Weekly (2007-2020).csv")

germany_yields <- germany_yields[, -(3:6)]
italy_yields <- italy_yields[, -(3:6)]

colnames(germany_yields)[1] <- "Date"
colnames(germany_yields)[2] <- "Yield"
colnames(italy_yields)[1] <- "Date"
colnames(italy_yields)[2] <- "Yield"

A: The easiest approach is to use %in%:
germany_yields[germany_yields$Date %in% italy_yields$Date, ]

A: We can also use dplyr
library(dplyr)
germany_yields %>%
      filter(Date %in% italy_yields$Date)


Q: Workflow Lookup List view threshold Alert me I have a workflow from a Document Library that copy the file to another Document Library and then "Update Item in" on this other Document Library through lookup. However the workflow won't work because where the file is copied the Document Library has more than 5k files and the List View Threshold is setup for only 5k.
I tried to create a specific field on both Document Library that the workflow could do the lookup, but I still get the same error. I was wondering how to make the workflow lookup on a different Document Library with exceeded list view threshold without changing  the list view threshold limit.
This is the erro that I get from  the workflow status:
"The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator."

A: A better solution would be to parse out your document libraries so they aren't exceeding the list view threshold. Assuming you're running 2013 since you tagged it in your post, you could have the workflow do a REST API call to the destination library and check the item count. If it returns >5000, alert the document library manager to archive some old files - or save the file to an alternate library using an If/Then block.
The SPD Workflow to do this:
Build {...} Dictionary (Output to Variable: requestHeaders)
then Call [site url]/_api/web/Lists/GetByTitle('[Library Name to Query]') HTTP web service with request (ResponseContent to Variable: responseContent|ResponseHeaders to Variable: responseHeaders|ResponseStatusCode to Variable: responseCode)
then Get d/ItemCount from Variable: responseContent (Output to Variable: count)

If Variable: count is less than 5000
  [Proceed as normal]
If Variable: count is greater than or equal to 5000
  [Save to secondary library and notify admin to do some cleanup]

(Here's some background on REST API if you haven't used it before)


Q: Prevent centring on focused input in hidden overflow area It is hard to explain with words so here's a fiddle I made to explain the problem better: http://jsfiddle.net/j2zurbbv/1/. When the first timeout fires the container div is not 'scrolled' which is the behaviour I want. However when the input is outside of the visible part of the div (as it is with the second timeout) the container div centres about this input.
Container css:
#container {
  overflow: hidden;
  height: 200px;
  position: absolute;
  width: 200px;
}

For the record I have only tested this on Chrome 37.0

A: Managed to work it out. Counter the scrolling that the browser does by doing document.getElementById('container').scrollTop = 0; whenever you programatically focus on an element outside of the visible area of an overflow: hidden div AND whenever a user inputs in such an element. Demonstrative JSFiddle (without prevention of input scrolling) http://jsfiddle.net/j2zurbbv/2/.


Q: Index page is not re rendering/refreshing on search in Rails I am making a simple search in rails on the index page. My problem is that on debug I get the correct results but they don't show on the frontend.
def index
 if !params[:category].present? and !params[:title].present?
  @services = Service.take(4)
 else
   if params[:category] != "Find Service" and params[:title].present?
    @services = Service.where(category: params[:category], title: params[:title]).take(4)
   elsif params[:category] == "Find Service" and params[:title].present?
    @services = Service.where(title: params[:title]).take(4)
   elsif params[:category] != "Find Service" and !params[:title].present?
    @services = Service.where(category: params[:category]).take(4)
   else
    @services = Service.take(4)
   end
  end
 end

My view index.html.erb
<%= form_with(url: "services", method: "get") do |form| %>

     <input type="submit" value="" class="main-listing__form-field agent-submit" style="width: 10% ;float:right">
     <%= form.text_field "title", id: "search_agent", class: "main-listing__form-field ", placeholder: "Search by Name or Location...", style: "width: 75% ;float:right; background: transparent; color: white!;" %>

        <%= form.select("category",options_for_select(["Find Service", "Assembly", "Carpet Cleaning", "Electrical", "House Cleaning", "HVAC", "Handyman", "IT", "Junk Removal", "Lawn Care","Moving", "Painting", "Plumbing", "Staging", "Photography", "Videography", "Inspectors"], :selected => "Find Service"), {include_blank: false}, { :class => 'ht-field listing-sort__field' }) %>

<% end %>

Recently viewed & more

 <% @services.each do |service| %>
  <%= render 'services/service_card', :f => service %>
 <% end %>

Pro SEM services

 <% @services.each do |service| %>
  <%= render 'services/service_card', :f => service %>
 <% end %>

This is _service_card

<%= f.user.profile.first.first_name %>

Level 1 Seller

      <% byebug %>

<%= f.description %>

       (5)

Starting At $ <%= f.packages.first.price%>

Please help me regarding this. Looking forward. It is working fine without search, but with search it doesn't update the results and show same results.


Q: Select statement over multiple columns I have an SQLite database with a table help with columns i_id, issue, url, steps, kw1, kw2, [...], kw12. kw1 - kw12 contain one word and can be null.
When I do:
sqlite> select issue,url,steps from help where kw1='adobe';

I get:
blank popup|blankpopup.html|S
missing pdfs|missingpdfs.html|S
printall not populating|printall.html|A

this is right. When I move to another keyword like 'ie' that is in multiple fields across kw1 - kw12, how do I do a select statement where instead of searching just kw1, it searches kw1 through to kw12?
I know what fields 'ie' is in. I have an Excel sheet of how the database is built but the people using the database don't.

A: If I understand right, you just need to use Or keyword and search thru all the kw-fields
sqlite> select issue,url,steps from help where kw1='ie' or kw2='ie' or kw3='ie' or kw4='ie' or kw5='ie' or kw6='ie' or kw7='ie' or kw8='ie' or kw9='ie' or kw10='ie' or kw11='ie' or kw12='ie';


Q: TortoiseHg - infinite cloning of repository I've encountered a quite troubling problem. I've tried to clone repository from the server and I was able to start cloning, but it never ends, and no files are being downloaded on my hard drive. I'm using pagaent with my private key. I've tried it on 3 different PC, and it didn't helped, but I know it is working because some people were able to clone this repository.


Q: Running a program in eclipse Each time I try to run a new program, an old program 'client.java' is run by eclipse. How do I change this setting? How do we tell eclipse which program to run? I tried using the arrow beside run button but it dosen't list out my new program.

A:
Right Click To the class -> Run As-> JAVA Application

A: You can change the default behavior by going to Window > Preferences > Run/Debug > Launching and in the 'Launch Operation' section, select the radio button for Launch the selected resource or active editor and then select Launch the associated project underneath.

A: Firs of all make sure that your program has a main class.
Then click in the black button next to the run button -> Run As-> JAVA Application.
If this doesn work make sure you have all this properly set up.
Run Configurations


Q: Matplotlib ticks sans-serif for all plots I'm trying to achieve sans-serif axes labels and ticks in matplotlib with pgf. I want to control that by rcParams so I have it working for all subsequent plots. Currently, I'm using
"pgf.rcfonts":False,
"pgf.texsystem": "pdflatex",
"text.usetex": True,
"font.family": "sans-serif",

which I adapted from the mpl docs. It does set all my text in the figure to sans-serif. However, the numbers are kept with a serif font. I want them to be sans-serif. As soon as i force the formatter, its sans-serif. Any way to get it to do that automatically? MinEx follows...
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

#define style
style = {
        "pgf.rcfonts":False,
        "pgf.texsystem": "pdflatex",
        "text.usetex": True,
        "font.family": "sans-serif"
        }
#set
mpl.rcParams.update(style)

#get data
data = np.random.random(100)
#set up plot
f,ax = plt.subplots()
ax.plot(data)
#label something
ax.set_xlabel('Runner')

The label is sans now. The ticks are not! But when calling
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))

they are.

A: According to the pgf texsystem example, you need to use the "pfg" backend (mpl.use("pgf")) and choose the font you want to use:
style = {
        "pgf.texsystem": "pdflatex",
        "text.usetex": True,
        "pgf.preamble": [
         r"\usepackage[utf8x]{inputenc}",
         r"\usepackage[T1]{fontenc}",
         r"\usepackage{cmbright}",
         ]
        }

Alternatively you may use a formatter, which does not format the ticklabels as latex math (i.e. does not put them into dollar signs).
One may adapt the default ScalarFormatter not to use latex math by setting
ax.xaxis.get_major_formatter()._usetex = False
ax.yaxis.get_major_formatter()._usetex = False

A: The problem is LateX related. You just need to load the extra cmbright package that enable sans-serif math fonts.
On Debian-like systems:
sudo apt install texlive-fonts-extra

On Fedora:
sudo dnf install texlive-cmbright

Then try your code with this style:
style = {
        "text.usetex": True,
        "font.family": "sans-serif"
        "text.latex.preamble" : r"\usepackage{cmbright}"
        }


Q: Creating network visualization dashboards I'm a Network Engineer, I want to create a custom data network visualization dashboard that includes interactive charts and graphs with drill down options and such. I'm a bit overwhelmed by the proliferation of languages and different ways of accomplishing this. What are some languages/libraries I should learn to accomplish this task, as well as good tutorials for your recommendations. I have intermediate coding experience.
Thanks!

A: I recommend using D3js, force directed graph is perfect for creating a network visualization, there are some examples here: D3 force directed graph


Q: Error using Reactive Maps with Google maps Javascript Api I am trying to build and app with ReactiveSearch and ReactiveMaps using some indexed files in Elasticsearch.
The indexed files in Elasticsearch have a field "location", for example:
        "location": {
        "Lat": 56.746423,
        "Lon": 37.189268
      }

And other fields like "Title" or "Authors".
I got a Google maps API key and in my App.js file I have these components:
      <DataSearch
        componentId="mainSearch"
        dataField={["Title", "Title.search", "Abstract", "Abstract.search"]}
        queryFormat="and"
        placeholder="Search for HEP"
        autosuggest={true}
        className="datasearch"
        innerClass={{
          input: "searchbox",
          list: "suggestionlist"
        }}
      />

        <ReactiveMap
        componentId="map"
        dataField="location"
        size={100}
        defaultZoom={13}
        defaultCenter={{ lat: 37.74, lng: -122.45 }}
        showMapStyles={true}
        defaultMapStyle="Standard"
        showMarkerClusters={true}
        showSearchAsMove={true}
        searchAsMove={true}
        react={{
          and: "mainSearch"
        }}
        onData={result => ({
          label: result.Title
        })}
      />

in the same file ("App.js") I have this lines :
  <ReactiveBase
    app="title"
    url=here_the_elasticsearch_cluster
    mapKey="here_my_googlemapsAPI_key"
  >

Also in the file Public/index.html I have
<script
  type="text/javascript"
  src="https://maps.google.com/maps/api/js?v=3.34&key=MY_GOOGLE_MAPS_API_KEY&libraries=places"
></script>

However, When I search for any documents in the mainBar I found it, but, when I click on it it doesnt appear in the map.
What am I doing wrong?

A: Finally I have solved it.
ReactiveMaps does not allow the location field in uppercase, so I had to change the indexed documents in elasticsearch taking in account this.
    "location": {
    "lat": 56.746423,
    "lon": 37.189268
  }


Q: Creating an array from two data-* and one select array codeigniter I have a table with products where i can add rows dynamically and on each row i add it will be a select and an edit button.
If i press this button,it will display a modal where i can modify 2 data-* of the select.The dependence(dep) and the category.
After editing one select, i will have something like this:
<select data-dep="1" data-category="3"></select>

After submitting,in the model,i will get the products like this:
$products = $this->input->post('products[]');

In this way, i will have an array with all the products i wanted to add to database.The question is, can i make an array with the id of the product(what i have now), the value from data-dep and the value from data-category?And if i can,how?Something like this:
[1]--->product_id = 1,dep = 3, category = 2;

[2]--->product_id = 2,dep = 1, category = 3;

My HTML is this:

                        <select class="form-control select-table" name="products[]" id="select-1" data-dep="" data-category="">
                            <?php foreach($products as $product):?>
                                <option value="<?php echo $product['products_id'];?>"><?php echo $product['product_name'];?></option>
                            <?php endforeach;?>
                        </select>

        Pret:
        <input type="number" name="price" class="form-control"/>
        <input type="submit" class="btn btn-primary" name="submit" value="Creaza meniul" style="margin-top: 5px;"/>

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                    <select class="form-control dep-select" id="dep-test" name="dep-select">
                        <option class="form-group" value="1">Fara garnitura&salata</option>
                        <option class="form-group" value="2">Fara salata</option>
                        <option class="form-group" value="3">Fara garnitura</option>
                        <option class="form-group" value="4">Cu de toate</option>
                    </select>
                    <select class="form-control category-select" name="category-select">
                        <option class="form-group" value="1">Fel Principal</option>
                        <option class="form-group" value="2">Garnitura</option>
                        <option class="form-group" value="3">Salata</option>
                        <option class="form-group" value="4">Supa</option>
                        <option class="form-group" value="5">Desert</option>
                    </select>

                    <button type="button" class="btn btn-primary" id="save" data-dismiss="modal">Salveaza</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Inchide</button>


Q: How do I get a Google Admin to Fix my Project Console? Short of paying $150/month so I can actually submit a ticket, what can I do to get Google's attention?  I've seen other people get help for what appears to be the exact same issue.
I uploaded a new (small) app to Google App Engine (GAE), and the Applications Settings page shows an error under Cloud Integration ("An error occurred when creating the project. Please retry").
I've retried over a period of days, but it tries for a while, then reports another failure.  I've asked questions of StackOverflow, and in the GAE issues forum, to no response.

A: Try to get hold of the people from Google Developer relations here, in the relevant Google+ communities or on Google groups.
If it can bring you any comfort: paying the $150 does not help you much - we have the subscription.

A: If you have a second Google Apps domain, replicate the issue by switching domains and recreating the project from scratch. Then if the error occurs again, post that it occurs in 2 or more cloud.google.com accounts with separate domains.  This should help show this is not a one off error and requires investigation.
If it does not occur in the second domain, save your data, delete your project and recreate with a different project name and number.
-ExGenius


Q: Multiply columns of different sheets in power BI I need to multiply the no.of grants into the expected attrition rate based on dates. In image 3 i have the rates and now for image 2, i need to multiply the rates in image based on the date. Im new to power bi and i'm not able to work it out.


Q: React Router: props aren't passed down when directly accessing the URL of child component. Will I need to use the same state in both parent and child? I'm pretty new to React and React Router so apologies if this is a silly question or answered elsewhere - I did a search but couldn't find a similar question.
I'm using React Router v6 and React Hooks. My very basic full-stack app is focused on keeping track of musical artists and their released projects (albums, mixtapes, EPs, etc.). My App component will render the ProjectList component at the '/' route, and the ArtistList component at the '/artists' route.
Relevant portions of App.js:
import React, { useState, useEffect } from 'react';
import { Routes, Route, Link } from 'react-router-dom';
import axios from 'axios';

import ProjectList from './ProjectList';
import ArtistList from './ArtistList';

import { Button } from './styles.js';

const App = () => {
  const [ projects, setProjects ] = useState([]);

  const getProjects = () => axios('projects').then(({ data }) => setProjects(data));
  useEffect(getProjects, []);

  return (<>
    <Link to="/">
      <Button>Projects</Button> // Button is using styled-components
    </Link>
    <Link to="/artists">
      <Button>Artists</Button>
    </Link>
    <Routes>
      <Route path="/" element={<ProjectList projects={projects} />} />
      <Route path="/artists" element={<ArtistList projects={projects} />} />
    </Routes>
  </>);
};

This all works as expected when I click the Projects and Artists buttons. However, when I attempt to access the '/artists' route directly through the URL bar of my browser, nothing renders and I get an error about how the projects prop is undefined. My assumption is that because I'm trying to access the ArtistList component before rendering the App component itself, getProjects doesn't run and so no projects props are passed down to ArtistList.
I need the list of projects to render my ArtistList component. Each element of projects is an object that includes an artist property that I use to create my list of artist names and a dateAdded property that I use to sort the artist list by recency. I also keep track of how many projects each artist has.
Relevant portions of ArtistList.jsx (the return block contains some styled-components - Options, Header, TextWrapper, and Artist):
const ArtistList = ({ projects }) => {
  const [ artists, setArtists ] = useState([]);
  const [ sortBy, setSortBy ] = useState('name');

  const getArtists = () => {
    const artists = [];
    let curArtist = projects[0].artist;
    let projectCount = 0;
    const now = new Date();
    let firstAdded = now;

    for (const { artist, dateAdded } of projects) {
      if (artist !== curArtist) {
        artists.push({ name: curArtist, projectCount, firstAdded });
        curArtist = artist;
        projectCount = 0;
        firstAdded = now;
      }
      projectCount++;
      const projectDate = new Date(dateAdded);
      if (projectDate < firstAdded)
        firstAdded = projectDate;
    }
    setArtists(artists);
  };
  useEffect(getArtists, [ projects, sortBy ]);

  if (sortBy === 'number')
    artists.sort((a, b) => b.projectCount - a.projectCount);
  else if (sortBy === 'recency')
    artists.sort((a, b) => b.firstAdded - a.firstAdded);

  return (<>
    <Options>
      <label htmlFor="sortBy">Sort by: </label>
      <select id="sortBy" value={sortBy} onChange={e => setSortBy(e.target.value)}>
        <option value="artist">Name</option>
        <option value="number"># of Projects</option>
        <option value="recency">Recently Added</option>
      </select>
    </Options>
    <Header>
      <TextWrapper>Name</TextWrapper>
      <TextWrapper># of Projects</TextWrapper>
    </Header>
    {artists.map(({ name, projectCount }, idx) => (
      <Artist key={idx}>
        <TextWrapper>{name}</TextWrapper>
        <TextWrapper>{projectCount}</TextWrapper>
      </Artist>
    ))}
  </>);
};

I currently see 2 solutions to this issue (I'm sure I'm missing more):

*

*Create a projects state and a getProjects in the ArtistList component, pretty much exactly as they are in the parent App component. Whenever I render ArtistList, I will make a request to my back end to retrieve a list of projects and then invoke setProjects. I'd then derive the artists state from projects, as before. Of course, I'd no longer need to pass the projects props from App to ArtistList. However, I would then have the exact same state values/functionality in both parent and child components, and this feels to me like a violation of fundamental React principles.

*Put a collection of Artists into my Mongo database, in addition to the Projects collection I currently have. I would have to implement something similar to the getArtists function, but in the back end this time, then put the list of artist data into my database. Then, every time I try to render ArtistList, I will make a request to my back end to retrieve the list of artists and go from there.
The third option is doing nothing, but then I'm unable to access the '/artists' page directly through the URL.
What would be best practice and the best approach in this instance? Any help is appreciated!

A: The projects state is actually defined on the initial render cycle:
const [ projects, setProjects ] = useState([]);

So it's a defined prop when passed to ArtistList:
<Route path="/artists" element={<ArtistList projects={projects} />} />

The issue starts when in ArtistList in the useEffect hook calling getArtists where it is incorrectly attempting to access a property of the first element of the projects array which is currently an undefined object.
const getArtists = () => {
  const artists = [];
  let curArtist = projects[0].artist; // <-- error, access artist of undefined!
  let projectCount = 0;
  const now = new Date();
  let firstAdded = now;

  for (const { artist, dateAdded } of projects) {
    if (artist !== curArtist) {
      artists.push({ name: curArtist, projectCount, firstAdded });
      curArtist = artist;
      projectCount = 0;
      firstAdded = now;
    }
    projectCount++;
    const projectDate = new Date(dateAdded);
    if (projectDate < firstAdded)
      firstAdded = projectDate;
  }
  setArtists(artists);
};

useEffect(getArtists, [projects, sortBy]);

What you can do is to only run the logic in getArtists is the array is populated.
const getArtists = () => {
  const artists = [];
  let curArtist = projects[0].artist;
  let projectCount = 0;
  const now = new Date();
  let firstAdded = now;

  for (const { artist, dateAdded } of projects) {
    if (artist !== curArtist) {
      artists.push({ name: curArtist, projectCount, firstAdded });
      curArtist = artist;
      projectCount = 0;
      firstAdded = now;
    }
    projectCount++;
    const projectDate = new Date(dateAdded);
    if (projectDate < firstAdded)
      firstAdded = projectDate;
  }
  setArtists(artists);
};

useEffect(() => {
  if (projects.length) {
    getArtists();
  }
}, [projects, sortBy]);

And to ensure that projects is at least always a defined value, provide an initial value when destructuring the prop.
const ArtistList = ({ projects = [] }) => { ... }


Q: How to find largest count using table in a matrix in R Suppose I had the following matrix
    m = matrix(c(1, 0, 0, 0, 0, 0, 1, 1, 0), ncol = 3)
    > m
         [,1] [,2] [,3]
    [1,]    1    0    1
    [2,]    0    0    1
    [3,]    0    0    0

I want to have a count of the values for each of the columns, so
    table(m[,1])
    table(m[,2])
    table(m[,3])

And I want to figure out what's the value (either 0, or 1) that has the largest counts (appears more than the other). So for column 1 I would want R to return 0 (because there are more 0's than 1's), for column 2, R should return 0, and for column 3 return 1.
I've tried which.max() but that only gives me the index. Not the value with the largest count.

A: If you are working with a binary matrix, you can use colMeans
as.numeric(colMeans(m) > 0.5)
# [1] 0 0 1

since colMeans(m) gives you the percentage of 1's in each column

A: A simple solution is to use indexation and which.max, as you had proposed. To make things simpler, it can be done using apply and a function indexing which.max Thus, following your example matrix:
apply(m,2,function (X) as.numeric(names(table(X)[which.max(table(X))])))


Q: Does size of a VARCHAR column matter when used in queries
Possible Duplicate:
is there an advantage to varchar(500) over varchar(8000)?

I understand that a VARCHAR(200) column containing 10 characters takes same amount of space as a VARCHAR(20) column containing same data.
I want to know if changing a dozen VARCHAR(200) columns of a specific table to VARCHAR(20) would make the queries run faster, especially when:

*

*These columns will never contain more than 20 characters

*These columns are often used in ORDER BY clause

*These columns are often used in WHERE clause

*

*Some of these columns are indexed so that they can be used in WHERE clause

PS: I am using SQL Server 2000 but will upgrade to later versions of SQL anytime soon.

A: Here's a blog post that explains under what circumstances and why there are performance differences when using different column sizes (with tests and technical details):
Advanced TSQL Tuning: Why Internals Knowledge Matters

A: It does matter for the query optimiser when it will evaluate the best query path to perform your query.  When more than one path will be available, it will calculate an I/O cost and other various parameters based on your query and from these, chose the one that will appears to him as the least costly.
This is not an absolute calculation, it's only an approximation process.  Therefore, it can easily be thrown off if the apparent mean size required to manipulate the records from one table in memory is much bigger then what will be really necessary and the optimiser might chose a less performing path based on what it thinks would have be necessary for the others paths.
Having a realistic max size is also usefull to any other programmer that will come along looking at your code.  If I have a variable that I want to display in a GUI, I might allocate much more space than neededd if I see that is backed by something like nvarchar(200) or nvarchar(2000) instead of nvarchar(20) if its size is never greater than that.

A: Yes, the length of varchar affects estimation of the query, memory that will be allocated for internal operation (for example for sorting) and as consequence resources of CPU. You can reproduce it with the following simple example.
1.Create two tables:
create table varLenTest1
(
    a varchar(100)
)

create table varLenTest2
(
    a varchar(8000)
)

2. Fill both of them with some data:
declare @i int
set @i = 20000

while (@i > 0)
begin
    insert into varLenTest1 (a) values (cast(NEWID() as varchar(36)))
    set @i = @i - 1
end

3. Execute the following queries with "include actual execution plan":
select a from varLenTest1 order by a OPTION (MAXDOP 1) ;
select a from varLenTest2 order by a OPTION (MAXDOP 1) ;

If you inspect execution plans of these queries, you can see that estimated IO cost and estimated CPU cost is very different:

A:
Size matters
Always use the smallest data size that will accommodate the largest
  possible value. If a column is going to store values between 1 and 5,
  use tinyint instead of int.
This rule also applies to character columns. The smaller the data
  size, the less there is to read, so performance, over all, benefits.
  In addition, smaller size reduces network traffic. With newer
  technology, this tip seems less relevant, but don’t dismiss it out of
  hand. You’ll won’t regret being efficient from the get-go.

For more info visit http://www.techrepublic.com/blog/10-things/10-plus-tips-for-getting-the-best-performance-out-of-your-sql-server-data-types/


Q: Spring MVC not loading static resources from webapp Issue
Unable to get Spring to add a resource handler for static resources.
Background Information
I have a Spring MVC webapp running in a standalone Jetty instance. My webapp structure is
webapp root/
    resources/
        css/
        images/
        js/
    WEB-INF/
        layouts/
            tiles.xml
            page.jsp
        lib/
        views/
            home/
                home.jsp
                tiles.xml
        web.xml

I've extended the WebMvcConfigurerAdaptor to add a resource mapping such that urls like company.com/myservlet/resources/css/main.css will get resolved to the webapp root/resources/css folder.
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

My little controller is this:
@Controller
public class SpringAppController {

    public SpringAppController() {
    }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView handleRequestHome(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        return new ModelAndView("home");
    }
}

My web.xml is simply this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Java-based Spring container definition -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <!-- Location of Java @Configuration classes that configure the components that makeup this application -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.company</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>admin</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>admin</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Ensure UTF-8 encoded pages so that certain characters are displayed and submitted correctly -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Enables support for DELETE and PUT request methods with web browser clients -->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

My JavaConfig for the webapp to instantiate some mvc resolvers is this:
@Configuration
public class MainConfig {

    @Bean
    public ViewResolver viewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
        viewResolver.setViewClass(TilesView.class);
        return viewResolver;
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer configurer = new TilesConfigurer();
        configurer.setDefinitions(new String[] {
            "/WEB-INF/layouts/tiles.xml",
            "/WEB-INF/views/**/tiles.xml"
        });
        configurer.setCheckRefresh(true);
        return configurer;
    }

    @Bean
    public org.springframework.context.MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/messages");
        return messageSource;
    }

}

When I hit the url company.com/myservlet/home the tiles stuff works and the home.jsp page is displayed but the css and images are not loaded. The servlet logs this warning:
[DEBUG] [DispatcherServlet] [DispatcherServlet with name 'admin' processing GET request for [/api/v1/tlb/resources/page.css]]
[DEBUG] [RequestMappingHandlerMapping] [Looking up handler method for path /resources/form.css]
[DEBUG] [RequestMappingHandlerMapping] [Did not find handler method for [/resources/form.css]]
[WARN ] [PageNotFound] [No mapping found for HTTP request with URI [/api/v1/tlb/resources/form.css] in DispatcherServlet with name 'admin']

I've tried debugging the servlet and the WebMvcConfig.addResourceHandlers() method is never called and hence why the static resources cannot be found. What am I missing to get this working?
As a note if I add the following to my web.xml the css resource will be loaded but I would like to know why the WebMvcConfig.addResourceHandlers() method is not called so I don't need this servlet mapping.
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

A: Well, I've fixed the issue but not exactly sure why/how yet. The project had imported a jar that contained a class that extended WebMvcConfigurationSupport like the following:
@Configuration
public class EnableUriMatrixVariableSupport extends WebMvcConfigurationSupport {

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping hm = super.requestMappingHandlerMapping();
        hm.setRemoveSemicolonContent(false);
        return hm;
    }
}

Additionally I also has @EnableMvc annotation which imports DelegatingWebMvcConfiguration. I think this ends up creating two instances of a WebMvcConfigurationSupport and this causes havoc in the spring container. Unfortunately I upgraded to spring 4.x in the process of fixing this issue so I'm not sure yet if this helped in some way.


Q: Create new database on the fly in Laravel 4 I want dynamically create new database, database user and password with privileges, create some tables in new database on the fly in Laravel 4 for every new user. This is for a multi tenant website.
Whats the best solution?
thanks.

A: This is not your first database connection it's easy, but you'll have to execute raw statements because database creation is no available as connection methods:
DB::statement(DB::raw('CREATE DATABASE <name>'));

To do that you can use a secondary connection:
<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
        ),

        'store' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
        ),
    ),
);

Then you can, during application bootstrap, change the database of the secondary connection:
DB::connection('store')->setDatabaseName($store);

or
Config::set('database.connections.store', $store);

And use the secondary connection in your queries:
$user = User::on('store')->find(1);

or
DB::connection('store')->select(...);


Q: How to show in Action bar, only if it can fit with text? I am having the following buttons, with some ic_menu icons: Register, Clear.
I want them, in whatever device(smartphone or tablet), to be shown if they can fit, including their text.
If i use on both them: withText|ifRoom, on smartphone they appear both, without their text on portrait, and landscape with text.
On tablet they appear both with text.
I want them, on smartphone, NOT to appear if they cant fix with their text too.
Are any other combinations ?
Also what is collapseActionView for?


Q: What is meant by indexing in MongoDB? To be true, After typing the Question title only, i had a look about DB indexing in Wiki.
Now i know something about Indexing in general. But, still i have some questions on MongoDB indexing.
What is indexing in MongoDB? What it will exactly do, If i index a collection?
What i can do with indexing in MongoDB?
Will i able to use it for searching specific data?
Can anyone explain it with the below set of documents in a Collection in some MongoDB?
{ "_id":"das23j..", "x": "1", "y":[ {"RAM":"2 GB"}, {"Processor":"Intel i7"}, {"Graphics Card": "NVIDIA.."}]}

Thanks!!!

A: An index speeds up searching, at the expense of storage space. Think of the index as an additional copy of an attribute's (or column's) data, but in order. If you have an ordered collection you can perform something like a binary search, which is much faster than a sequential search (which you'd need if the data wasn't ordered). Once you find the data you need using the index, you can refer to the corresponding record.
The tradeoff is that you need the additional space to store the "ordered" copy of that column's data, and there's a slight speed tradeoff because new records have to be inserted in the correct order, a requisite for the quick search algorithms to work.
For details on mongodb indexing see http://www.mongodb.org/display/DOCS/Indexes.


Q: Unable to display username from another table I currently am able to view a list of contacts with no issues and would like to be able to view the mentors / tutors for the clients.
The username is stored in another table to the contact information and the mentor ID is stored in the contacts table.
I have followed a tutorial on how to do this but can't get it to work.
I have tried to join the accounts and contacts table together and has stopped the everything from showing. My old code showed everything fine apart from the mentor. (Old code also below)
Error reporting says Warning: Undefined array key "id"
Code;
$stmt = $pdo->prepare('SELECT c.id
     , c.name
     , c.last_name
     , c.mobile_number
     , c.status
     , a.username as mentorname
FROM contacts c
     LEFT JOIN
     accounts a ON c.mentor = a.id
WHERE c.id = ?;');
$stmt->execute([$_GET['c.id']]);
$fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

}

Display code
                <?php if($fullContactInfo == null){
                    echo "
No Record Found!
";
                }else{ foreach($fullContactInfo as $info){ ?>

                    <?php echo $info['name']; ?> <?php echo $info['last_name']; ?>
                    <?php echo $info['mobile_number']; ?>
                    <?php echo $info['status']; ?>
                    <?= $info['mentorname']; ?>

Table examples
Contacts
ID: 1
Name: Joe Blogs
Mobile: 1889454
Status: Current
Mentor: 25

Accounts
ID: 25
Username: jbloggs

Old Code
$stmt = $pdo->prepare('SELECT id,name,last_name,mobile_number,status,dob,mentor,image FROM contacts');
$stmt->execute([$_GET['id']]);
$fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

if($fullContactInfo == true){
    $stmt = $pdo->prepare('SELECT username FROM accounts WHERE id = ?');
    $stmt->execute([ $fullContactInfo['mentor'] ]);
    $fullContactInfo1 = $stmt->fetch(PDO::FETCH_ASSOC);

A: You can just replace $_GET['c.id'] with $_GET['id'].


Q: How can I get my WCF Service constructor called? I'm currently trying to get my head around WCF services for an ASP.NET dev environment, and I believe that I'm doing well save for one thing that has me stumped.
Basically, I've got a WCF service set up (let's take the default, with an added constructor):
public class MyService : IMyService
{
    public MyService() { /* blah */ }
    public DoWork() { /* blah */ }
}

The IMyService interface defines the DoWork() method as an [OperationContract], as it should.
So I've got this service referenced in another project (let's say a [Unit] Test Project), via Add Service Reference on the VS2010 UI. This creates a reference to a MyServiceClient which exposes my WCF service methods, as it should.
However, when I do this in my test project:
ServiceReference.IMyService service;
service = new ServiceReference.MyServiceClient();

... the MyService() constructor does not get called, basically because I'm instantiating a MyServiceClient, not a MyService per se.
How do I go about getting that constructor called? I'm planning to use that for initialization purposes (perhaps grabbing a layer in a tiered implementation, for example?).

A: That constructor will be called on the server when you make your request from the client.
Creating a "reference" to a web service (and then using the client classes) is very different to referencing a regular .DLL.  All of your service code will run on the server-side, but not until the service is invoked...

A: The only way for the server-side constructor to be called for each request is to set the InstanceContextMode to PerCall (in the ServiceBehavior attribute).


Q: report module for sugarcrm 6.2 Which Report module is suitable for making reports in sugarcrm 6.2 . I had installed the zucker Report Module on the local site it works properly but when i used to install them on my server it does not installed
Anyone please help
Thanks

A: KReporter certainly the best Reporting tool in the Marketing for SugarCRM, regardless of edition - be it PRO, ENT, CORP or CE.
The new free Google Charts are really cool

A: I suggest KINAMU Reporter, http://www.sugarforge.org/projects/kinamureporter


Q: Can I create a device context that is just a portion of another device context? I have subclassed a graphics control that takes a device context handle, HDC, as an input and uses that for drawing. My new control is just the original control centered on top of a larger image. I would like to be able to call the original control's Draw() method for code re-use, but I'm unsure how to proceed.
Here's the idea:
void CCheckBox::DrawCtrl( HDC hdc, HDC hdcTmp, LPSIZE pCtlSize, BYTE alpha ) {
    // original method draws a checkbox
}

void CBorderedCheckBox::DrawCtrl( HDC hdc, HDC hdcTmp, LPSIZE pCtlSize, BYTE alpha ) {
    // Draw my image here
    // Create new hdc2 and hdcTemp2 which are just some portion of hdc and hdcTemp
    //   For example, hdc2 may just be a rectangle inside of hdc that is 20 pixels
    //   indented on all sides.
    // Call CCheckBox::DrawCtrl() with hdc2 and hdcTemp2
}

A: I think you may be confused of what a device context is. A device context is a place in memory that you can draw to, be it the screen buffer or a bitmap or something else. Since I imagine you only want to draw on the screen, you only need one DC. To accomplish what you want, I would recommend passing a rectangle to the function that tells it where to draw. Optionally, and with poorer performance, you could create a new Bitmap for the smaller area, and give the function the Bitmap's DC to draw on. Now that I think about it, that might have been what you meant in the first place :P Good luck!

A: While not foolproof, you can fake a DC as a subsection of a DC by using a combination of SetViewportOrgEx and SelectObject with a region clipped to the sub area in question.
The problem with this approach is if drawing code already uses these APIs it needs to rewritten to be aware that it needs to combine its masking and offsetting with the existing offsets and clipping regions.


Q: VBA code to read word document footer I have a folder of completed word document forms and I have an excel file that reads all the answers on the forms into different worksheets in spreadsheet. The worksheet that the data is exported to depends on the filename of the word document.
This currently works fine.
However, I now need it to be able to take into account the version number of the form which is stored in the footer of the word document but I don't know how to reference it.
I'm quite a noob when it comes to VBA so havent tried much.
The VBA that I have tried can be found below but unsurprisingly doesnt work.
Sub ReadWordDoc(filenme As String)

Dim Val As String
Dim WrdDoc As Document
Dim FormFieldCounter As Integer

Dim version As String

Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open filenme
wordapp.ScreenUpdating = False

Set WrdDoc = wordapp.Documents(filenme)
wordapp.Visible = True

version = WrdDoc.Sections(1).Footers(wdHeaderFooterFirstPage).Range.Text

FormFieldCounter = 1

If InStr(version, "5.00") Then

    RowCounter = RowCounter + 1

    Sheets("Version 5").Cells(RowCounter, FormFieldCounter) = filenme

    Do While FormFieldCounter <= 125
    WrdDoc.FormFields(FormFieldCounter).Select
    Val = WrdDoc.FormFields(FormFieldCounter).result
    Sheets("Version 5").Cells(RowCounter, FormFieldCounter + 1) = Val

    FormFieldCounter = FormFieldCounter + 1

    Loop

    wordapp.Documents(filenme).Close SaveChanges:=wdDoNotSaveChanges
    wordapp.Quit

Else

    'Do something else

End If

End Sub

A: After having a bit of a play and a Google, I found this page which helped me fix my issue
https://msdn.microsoft.com/en-us/library/office/aa221970(v=office.11).aspx
I changed my code as below:
version = WrdDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text

Although I'm not sure why the previous version didnt work as there is a footer on the first page.


Q: Stopping thread Immediately I want to stop a running thread immediately. Here is my code:
Class A :
public class A() {
    public void methodA() {
        For (int n=0;n<100;n++) {
        //Do something recursive
        }
        //Another for-loop here

        //A resursive method here

        //Another for-loop here

        finishingMethod();
    }
}

Class B:
public class B() {
    public void runEverything() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    A a = new A();
                    a.methodA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
       Thread thread = new Thread(runnable);
       thread.start();
    }

My problem is that i need to be able to stop the thread in Class B even before the thread is finished. I've tried interrupt() method, but that doesn't stop my thread. I've also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.
Any idea ?
Thanks in advance.

A: I think you should persevere with using Thread.interrupt().  But what you need to do to make it work is to change the methodA code to do something like this:
public void methodA() throws InterruptedException {
    for (int n=0; n < 100; n++) {
        if (Thread.interrupted) {
             throw new InterruptedException();
        }
        //Do something recursive
    }
    // and so on.
}

This is equivalent declaring and using your own "kill switch" variable, except that:

*

*many synchronization APIs, and some I/O APIs pay attention to the interrupted state, and

*a well-behaved 3rd-party library will pay attention to the interrupted state.

Now it is true that a lot of code out there mishandles InterruptedException; e.g. by squashing it.  (The correct way to deal with an InterruptedException is to either to allow it to propagate, or call Thread.interrupt() to set the flag again.)  However, the flip side is that that same code would not be aware of your kill switch.  So you've got a problem either way.

A: Thread.interrupt will not stop your thread (unless it is in the sleep, in which case the InterruptedException will be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately.
When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your methodA can be modified to add that flag, so something like:
// this is a new instance variable in `A`
private volatile boolean cancelled = false;

// this is part of your methodA
for (int n=0;n<100;n++) {
  if ( cancelled ) {
    return; // or handle this however you want
  }
}

// each of your other loops should work the same way

Then a cancel method can be added to set that flag
public void cancel() {
  cancelled = true;
}

Then if someone calls runEverything on B, B can then just call cancel on A (you will have to extract the A variable so B  has a reference to it even after runEverything is called.

A: You can check the status of the run flag as part of the looping or recursion. If there's a kill signal (i.e. run flag is set false), just return (after whatever cleanup you need to do).

A: There are some other possible approaches:
1) Don't stop it - signal it to stop with the Interrupted flag, set its priority to lowest possible and 'orphan' the thread and any data objects it is working on.  If you need the operation that is performed by this thread again, make another one.
2) Null out, corrupt, rename, close or otherwise destroy the data it is working on to force the thread to segfault/AV or except in some other way.  The thread can catch the throw and check the Interrupted flag.
No guarantees, sold as seen...

A: From main thread letsvsay someTask() is called and t1.interrput is being called..
t1.interrupt();

    }

    private static Runnable someTask(){
        return ()->{

            while(running){
                try {
                    if(Thread.interrupted()){
                        throw new InterruptedException(  );
                    }
               // System.out.println(i + " the current thread is "+Thread.currentThread().getName());

                  //  Thread.sleep( 2000 );
                } catch (Exception e) {

                    System.out.println(" the thread is interrputed "+Thread.currentThread().getName());
                    e.printStackTrace();
                    break;
                }
            }

o/P:
java.lang.InterruptedException
    at com.barcap.test.Threading.interrupt.ThreadT2Interrupt.lambda$someTask$0(ThreadT2Interrupt.java:32)
    at java.lang.Thread.run(Thread.java:748)
 the thread is interrputed Thread-0

Only t1.interuuption will not be enough .this need check the status of Thread.interrupted()  in child thread.


Q: unexpectedly found nil while unwrapping an Optional value on return I am calling Url which will give me Json in get() function.
I am calling get() function from another class and try to return result of Json in Array format. but it shows Found null error on return statement . when I tried to print values of Json it writing correctly.
This is my code in swift.
 func get() -> NSArray
        {
            let postEndpoint: String =  "Link_For_JSON_Data"
            let session = NSURLSession.sharedSession()
            let url = NSURL(string: postEndpoint)!
            var jsonArray : NSArray?
            var jsonArray1 : NSArray?

            session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
                // Make sure we get an OK response
                guard let realResponse = response as? NSHTTPURLResponse where
                    realResponse.statusCode == 200 else
                {
                        print("Not a 200 response")
                        return
                }

                // Read the JSON
                do
                {
                    if let contentString = NSString(data:data!, encoding: NSUTF8StringEncoding)
                    {
                        // Print what we got from the call
                        jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
                        print("jsonArray here", jsonArray)
                        // Update the label

                        dispatch_async(dispatch_get_main_queue())
                            { () -> Void in
                            self.getDataFormREST(jsonArray!)
                            }

                    }
                }

                catch
                {
                    print("bad things happened")
                }

            }).resume()

       return jsonArray!
        }

     func getDataFormREST(resultArray: NSArray) //-> NSArray
        {
            //        let resultDictionary = resultArray[(searchDetails)!-1] as! NSDictionary
            testArray = resultArray
            print("TESTArray ON ",testArray)
    }

A: You can't write a function that does an async call and then returns the results as the function result. That's not how async code works. Your function queues up the async dataTaskWithURL request, and then returns before it has even had a chance to send the request, much less receive the results.
You have to rewrite your get() function to be a void function (no result returned) but take a completion block. Then, in your data task's completion handler you get the data from the jsonArray and call the get() function's completion block, passing it the jsonArray.
See this project I posted on Github that illustrates what I'm talking about:
SwiftCompletionHandlers on Github


Q: Attempting to load the view of a view controller while it is deallocating. CoreSpotlight I integrate CoreSpotlight in my app. I want that user will find need information in spotlight search and after user will open this information in spotlight information opens in DetailViewController. I made it, spotlight works nice, but when application is opening I see this error Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (UIAlertController: 0x1245a0560)  although I don't use UIAlertController. I made in AppDelegate func which call function of UITableViewController which must to open object by index. But it is not appear. Still there is an error in showData()              performSegueWithIdentifier("show", sender: nil)reason: 'Receiver () has no segue with identifier 'show''. Although I add segue ( with show name) and it works when I usually select cell. Please help me.
    AppDelegate
  func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
        if userActivity.activityType == CSSearchableItemActionType {
            if let identifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
                print(identifier)
                checkWord = identifier // checkWord is String

                let tableC = TableViewController()
                tableC.showData()

                return true
            }
        }
        return false
    }

  func showData() {
    let matchString = appDel.checkWord
    if mainArray.contains(matchString) {
        let ind = mainArray.indexOf(matchString)!

        let indexPathMain = NSIndexPath(forItem: ind, inSection: 0)
        print(indexPathMain)
        self.tableView.selectRowAtIndexPath(indexPathMain, animated: true, scrollPosition: UITableViewScrollPosition.None)

        performSegueWithIdentifier("show", sender: nil)
        print("Show data")
    }
}

A: If you don't implement willContinueUserActivityWithType or if it returns false, it means that iOS should handle activity. And in this case it can show UIAlertController. So to get rid this warning return true for your activity in this delegate call:
func application(application: UIApplication,
   willContinueUserActivityWithType userActivityType: String) -> Bool {
      return true
}


Q: Getting protractor promise, variables and results synchronized Okay, I have this piece of code I'm trying, and failing, at writing. What I want to do is to make sure an index that is passed to a function is within the bounds of available elements on a page. And, if it is, pass back an element reference.
Suppose I have the following:

First row

Second

Third

So, I've got this function:
function getRow(index) {
   // get count of rows.
   var count = $$('li').count();

   // Ensure a parameter has been passed.
   if (!index) {
      throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
   }
   // Ensure the parameter is within bounds
   if (index < 0 || index >= count) {
      throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
   }

   return $$('li').get(index);
}

The above will fail because count is not really count, but a promise.
So, I've tried modifying it in various ways.  The one I thought would be successful is as follows:
// get count of rows.
var count;
$$('li').count().then(function(c) { count = c; });

or
// get count of rows.
var count = $$('li').count().then(function(c) { return c; });

I've gotten frustrated and tried to throw the whole if block within the thenable function, but it won't "see" index.
(Every time I think I've figured this out, I don't. Thank you for any and all assistance!)
UPDATE:
Following the suggestion below I tried modifying my code to:
function getRow(index) {
  //get count of rows.
  var count = $$('li').count().then(function(c) {
    return function() {
      return c;
    }
  });

  protractor.promise.all(count).then(function(count) {
    // Ensure a parameter has been passed.
    if (!index) {
      throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
    }
    // Ensure the parameter is within bounds
    if (index < 0 || index >= count) {
      throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
    }
  });

  return $$('li').get(index);
}

But it failed because, within the protractor.promise.all().then() block, index is undefined.  Also, in the error message, I don't even get a value for count.
> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through

A: I think you must use the javascript closures in order to achive it.
Try it:
var count = element(by.css('li')).count().then(function(c){
    return function(){
        return c
    }
});

var value = count();

Your value should be in the "value" variable.
PS: I don't have a protractor environment to test this code now

A: Here's how I solved it.
function getRow(index) {
    var count = $$('li').count();

    var test = function(index, count) {
        // Ensure a parameter has been passed.
        if (index == undefined) {
            throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
        }
        // Ensure the parameter is within bounds
       if (index < 0 || index >= count) {
           throw Error("The parameter, " + index + ", is not within the  bounds of 0 through " + count-1);
        }
    });

    count.then(function(count) {
        test(index, count);
    }

    return $$('li').get(index);
}

I'm not sure why this works and my previous attempt didn't.  Well, other than I abstracted the function and allowed myself to pass in the index in a clean manner.


Q: Java, Possible to modify method declaration of super class in abstract class hierarchy? I have an abstract class UserdataUpdater which extends Updater
Updater has a method declaration
 public abstract void processRow (Cluster cluster, IAppendOnlyData row);

Is there anyway to modify this method declaration inside UserdataUpdater to make it more specific, like
 public abstract void processRow (Cluster cluster, IUserData row);

IUserData extends IAppendOnlyData, because I want classes that extends UserdataUpdater to only take IUserData

A: No, you can't. This would break the contract of the superclass, which says: this method accepts a IAppendOnlyData as second argument.
Remember that an instance of a subclass is also an instance of its superclass. So anyone could refer to the subclass instance as its superclass, and call the base method, passing a IAppendOnlyData, without knowing that the instance is actually a subclass instance.
Read more about the Liskov substitution principle.
The only way to do that is to make the superclass generic:
public class Updater<T extends IAppendOnlyData> {
    ...
    public abstract void processRow(Cluster cluster, T row);

}

public class UserdataUpdater extends Updater<IUserData> {
    @Override
    public void processRow(Cluster cluster, IUserData row) {
        ...
    }
}

A: You cannot modify a method declaration in a derived class. You can only override a superclass method if the derived class method has the exact same method signature. You must use function overloading and make a new method processRow with the new parameter types you mentioned.

A: In my experience, you have to use the first declaration, then in the implementation, check to make sure that:
row instanceof IUserData

of course, this is checked at runtime rather than during compile, but I don't know any other way around it.  Of course, you can also just cast the row to the type IUserData, whether blindly or after checking its type (above).

A: Short answer: No.
You can create such a function, but because the signature is different, the compiler will see it as a different function.
If you think about it, what you are trying to do doesn't really make sense. Suppose you wrote a function that takes an Updater as a parameter and calls processRow on it with something that is not IUserData. At compile time, Java has no way to know whether the object passed in an Updater, UserdataUpdater, or some other subclass of Updater. So should it allow the call or not? What should the compiler do?
What you can do is inside UserdataUpdater.processRow, include code that checks the type passed in at runtime and throws an exception or does some other sort of error processing if it is not valid.

A: Assuming you have no control on the Updater class, you can't do that ... you'll have to implement that method with the exact same signature. However you can check for the type of row, inside your implementation and decide whatever processing is appropriate:
public void processRow (Cluster cluster, IAppendOnlyData row)
{
    if( row instanceof IUserData )
    {
        // your processing here
    }
    else
    {
        // Otherwise do whatever is appropriate.
    }
}


Q: Android Studio resetDrmState message on MediaPlayer release and set to null I have a media player that can play 1 of 46 sounds on button click. Instead of keeping 46 media players and stopping them all when I want to play another, I decided to keep 1 and just reuse it. My whole application works perfectly fine but in my Run box I get a resetDrmState message on every button click.
V/MediaPlayer: resetDrmState:  mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
    cleanDrmObj: mDrmObj=null mDrmSessionId=null

Is this a bad message?
Does anyone know a way to get rid of the message?
I use the code:
 public void onClick(View view) {
        String thisIV=view.getTag().toString();
        int resId=getResources().getIdentifier(thisIV,"raw", getPackageName());

        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.release();
            mediaPlayer=null;
        }

        mediaPlayer= MediaPlayer.create(MainActivity.this, resId);
        mediaPlayer.start();
    }

for my media player.


Q: Updating mysqli with Ajax and Jquery is not working I just want to update or edit  with Ajax. Edit or Save Button is in a  and so far everything is woking.
The Alert() function also shows variable values but the Ajax portion is not running. I am not sure why the data is not updating. Any help would be appreciated.
Question_statistics Page
include "include/connection";
while ($records=mysqli_fetch_array($query)){
    $id=$records['id'];
    $question=$records['question'];
    $question_from=$records['question_from'];
    $question_date=$records['question_date'];
    ?>
    <tr id="record-<?php  echo  $id; ?>" class="record">
        <?php echo $id; ?>

        <td class="box" id="box<?php echo $id?>">
            <span class="edit" id="<?php echo $id?>">Edit
            <span class="save" data-table="questions" id="save<?php echo $id?>">Save
            <span id="Q<?php echo $id?>"><?php echo $question; ?>

        <?php echo $question_from; ?>
        <?php echo $question_date; ?>

            <a id="<?php echo $id; ?>" class="delete" data-table="questions">

Custom javascriptfile:
$(document).ready(function() {
    //Update Question
    $('.edit').click(function(ae){
        ae.preventDefault();
        $('.edit').hide();
        var id = $(this).attr("id");
        $('#box'+id).addClass('editable');
        $('#box'+id).attr('contenteditable', 'true');
        $('#save'+id).show();
    });

    $('.save').click(function(){
        $('.save').hide();
        $('.box').removeClass('editable');
        $('.box').removeAttr('contenteditable');
        $('.edit').show();
        // var id =$(this).attr("id"); here id will show like `save+Id`
        var id= $('.edit').attr("id");
        var table = $(this).attr("data-table");
        var question=$('#Q'+id).text();

        alert(id+table+question);

        $.ajax({
            type: 'get',
            url:'include/ajaxserver.php',
            // data: variable or key : value, key:value,
            data: {
                id: id,
                edit_me: true,
                table: table,
                question: question
            },
            beforeSend: function() {
                parent.animate({'backgroundColor':'#fb6c6c'},300);
            },
            success: function(data) {
                setTimeout( function ( ) {
                    alert( 'Data has been Deleted From Database' );
                },600 );
            }
        });
    });
});/*end of the ready function*/

ajaxserver file:
include('connection');
if(isset($_GET["edit_me"]) && $_GET["edit_me"]=="true")
{
    $id = $_GET["id"];
    $table = $_GET["table"];
    $question=$_GET["question"];
    $query = "UPDATE `{$table}` SET question='$question' WHERE id='$id'";

    if (mysqli_query($con, $query)) {
        echo "";
    }
    else
      echo "";
}

A: Notice you are checking if $_GET["edit_me"] == "true" (string true) in the PHP page but that would mean that you should be sending edit_me: "true" in your ajax. Change your $_GET to:
# This will just check the key is filled
if(!empty($_GET["edit_me"]))

Then fix the SQL injection (you can Google that) and then send back instead of that javascript alert string you are doing:
die(json_encode(['success'=>(mysqli_query($con, $query))]));

This would send back to the ajax response {"success":true}if it worked. Since you are not specifically expecting json, you can parse the response:
// I changed the param here from data to response
success: function(response) {
    // Parse the response
    var data = JSON.parse(response);
    // Alert either way
    alert((data.success == true)? "Updated" : "Not Updated");
    // Do whatever this is
    setTimeout( function ( ) {
        alert( 'Data has been Deleted From Database' );
    },600 );
}


Q: lottery system pot division I making a lottery system in my web-based application, so it is in JavaScript, but my problem is more mathematical so feel free to write snippets in other language.
I want to distribute the lottery pot over winners in a natural feeling way, example:
var pot = 1000;
var tickets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
tickets = shuffleArray(tickets); //shuffle tickets for winners
//first half wins something (2 should be changeable)
var winners_count = Math.ceil(tickets.length / 2);

In this scenario i need a way to divide the whole pot over the 10 winners where first place gets the most and last (10th) get fewest.
for(var i=0; i<winners_count; i++){
    var ticket = tickets[i];
    //formula to determine percentage of pot to gain needed.
}

example outcome: (just to show you where it needs to go, not actual match)
1 - 22%
2 - 18%
3 - 14%
4 - 12%
5 - 10%
6 - 8%
7 - 7%
8 - 5%
9 - 3%
10 - 1%

I am quite bad at mathematics and some pointers and/or code snippets would help me a lot in solving this.
EDIT
Solution from Fabien Roualdes: http://jsfiddle.net/LB8YU/1/

A: I propose you to use an exponential distribution:
for(i=0 ; i<nrWinners ; i++){
    value = exp(-lambda*i);
    distribution[i] = value;
    sum += value;
}
for(i=0 ; i<nrWinners ; i++){
    distribution[i] /= sum;
}

Lambda is a positive parameter which will permit you to choose the shape of the distribution:

*

*If lambda is high the first winners will have a big part of the pot;

*On the contrary, the smaller lambda is, the more the distribution will aim towards a fair division of the pot.

I hope it will help you!
EDIT: When I say lambda is high, it is already high if it is equal to 1 for 5 winners.