text:
Q: How to update JSON column with new attribute value? I have a situation where I need to update json column dynamically in my table. See structure below
create table tjson ( jsoncol CLOB CONSTRAINT tjson_chk CHECK (jsoncol IS JSON) );

insert into tjson (jsoncol) VALUES ( '{"name" : "Kunal", "LName" : "Vohra" ,
                                       "salary" : "10000", "Age" : "25"}');

insert into tjson (jsoncol) VALUES ( '{"name" : "Rahul", "LName" : "Sharma" ,
                                       "salary" : "20000", "Age" : "35"}');

Now I need to change salary to a dynamic value for complete table on the basis of some_condition
I can read data using JSON_VALUE(jsoncol, '$.Age')
update tjson
   set jsoncol = '"salary":$JustChangeSalary'
 where some_condition;

salary is dynamic and not fixed. I am willing to change just salary.
I tried json_mergepatch but that is available only from Oracle version 19. We are using Oracle version 12.2

A: Before json_mergepatch you can use basic string functions like replace.
But you need to take care with these - formatting differences may cause these to fail. It's also possible you can update multiple attributes which match your criteria.
You can do safely in pure SQL by:

*

*Converting the JSON object to rows-and-columns with json_table

*Reconstructing the document with json_object(agg) and json_array(agg), passing the new values as needed.

For example:
create table tjson (
  jsoncol CLOB CONSTRAINT tjson_chk CHECK (jsoncol IS JSON)
);

insert into tjson (jsoncol) VALUES (
  '{"name" : "Kunal", "LName" : "Vohra" , "salary" : "10000", "Age" : "25"}'
);

insert into tjson (jsoncol) VALUES (
  '{"name" : "Rahul", "LName" : "Sharma" , "salary" : "20000", "Age" : "35"}'
);

commit;

select json_object (
  'name' value j.name,
  'LName' value j.LName,
  'salary' value 30000, -- put new salary here
  'Age' value j.Age
)
from   tjson, json_table (
  jsoncol, '$'
  columns (
    name path '$.name',
    LName path '$.LName',
    Age int path '$.Age'
  )
) j
where  j.name = 'Kunal';

JSON_OBJECT('NAME'VALUEJ.NAME,'LNAME'VALUEJ.LNAME,'SALARY'VALUE30000,--PUTNEWSALARYHERE'AGE'VALUEJ.AGE)
{"name":"Kunal","LName":"Vohra","salary":30000,"Age":25}

select t.jsoncol.name, t.jsoncol.salary
from   tjson t;

NAME    SALARY
Kunal    10000
Rahul    20000

update tjson t
set    jsoncol = (
  select json_object (
    'name' value j.name,
    'LName' value j.LName,
    'salary' value 30000, -- put new salary here
    'Age' value j.Age
  )
  from   tjson, json_table (
    jsoncol, '$'
    columns (
      name path '$.name',
      LName path '$.LName',
      Age int path '$.Age'
    )
  ) j
  where t.jsoncol.name = j.name
)
where t.jsoncol.name = 'Kunal';

select t.jsoncol.name, t.jsoncol.salary
from   tjson t;

NAME    SALARY
Kunal    30000
Rahul    20000

Clearly this is... cumbersome! It's impractical for complex documents.
Luckily from 12.2 you can manipulate a JSON document using PL/SQL object types:
declare
  jdoc tjson.jsoncol%type;
  jobj json_object_t;
begin
  select t.jsoncol
  into   jdoc
  from   tjson t
  where  t.jsoncol.name = 'Kunal';

  jobj := json_object_t.parse ( jdoc );
  jobj.put ( 'salary', 40000 );
  jdoc := jobj.to_clob();

  update tjson t
  set    jsoncol = jdoc
  where  t.jsoncol.name = 'Kunal';
end;
/

select t.jsoncol.name, t.jsoncol.salary
from   tjson t;

NAME    SALARY
Kunal    40000
Rahul    20000

A: Assuming that you want to update the salary of Kunal to 15000, then use JSON_EXISTS() function in the WHERE condition to bring the record of him only, and use traditional REPLACE() function next to the SET clause with the literal excerpt containing key-value combinations related to salary as
UPDATE tjson
   SET jsoncol = REPLACE( jsoncol, '"salary" : "10000"', '"salary" : "15000"' )
 WHERE JSON_EXISTS(jsoncol, '$.name?(@ == "Kunal")');

Demo


text:
Q: Health Swap Mechanic in HearthStone I want to understand how the health swap mechanic works when using the Reversing switch in HearthStone.
If i played Cogmaster Followed by a mech to activate his effect, then switched his attack and health with Reversing switch , would he have the buffed number or the original swapped?

If so, when the mech is destroyed would the health go back to the original?

A: If you swapped his health when he was a 3/2 (from the buff), he would turn into a 4/3 (with the buff).  If he lost the buff he would then turn into a 2/3.
I had a similar situation with another card and that's how it worked.  I can't remember what card but it was definitely pretty much the same scenario.

A: Reversing Switch will use the buffed stats of 3/2, boosting Cogmaster to 4/3.  In effect, the Cogmaster's buff will be applied twice.  The mechanics of this can be found in the description of Crazed Alchemist.

The Battlecry works by taking the minion's Attack and Health values, and creating an enchantment specifically granting the minion the opposite values. Because this enchantment is created based upon the minion's current values, any bonuses such as other enchantments and auras (such as the one granted by Stormwind Champion) are incorporated into the enchantment. The enchantment will sit 'on top of' previous enchantments, overriding their effects on the minion's Health.
However, because auras are automatically re-applied following each game event, once the new enchantment is granted, any aura effects will be reapplied, on top of the Alchemist's enchantment. This allows minions with Crazed Alchemist's buff to effectively benefit from auras twice - once through their inclusion in the Alchemist's buff, and then again through being reapplied after the buff has been granted.

When all mechs are destroyed, the Cogmaster would revert to 2/3 (assuming no injuries)

Because the Alchemist's buff overrides any previously applied stat-modifying buffs and sets the minion's stats to specific values, the expiry of any previously applied buffs will not affect the minion's stats. For example, a minion affected by Abusive Sergeant's Battlecry which is then buffed by a Crazed Alchemist will lose the Sergeant's buff at the end of the turn, but will not lose any Attack or Health as a result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Meteor Handlebars: #if this equals - load different templates with helperfunction I'm quite new to Meteor and just trying to build my first meteor App also using Transitioner.
So what I'm trying to do is load different templates when a string passed to another template is equal to something.
The HTML code:
<template name="onePage">
  {{#if itIs "teams"}}
    {{> teams}}
  {{/if}}
  {{#if itIs "players"}}
    {{> players}}
  {{/if}}
</template>
<template name="teams">

These are the TEAMS

</template>
<template name="players">

These are the PLAYERS

</template>

The JS code:
Template.onePage.itIs = function(passed) {
  return this === passed;
};

This does not work for some reason and I just don't understand why.
The only point really is that "this" passed to the onePage template is some string (coming from the URL). And if this string is "teams" I want to load the teams template, if it is "players" I want to load the players template.
As easy as that! :-)
Unfortunately I just can't solve this simple problem.
Hope you guys understand my problem and you can help!
best regards
Patrick

A: What is this in the Template.onePage.itIs callback?
If you change that to a Session (which you set from a URL for example, maybe using the Meteor Router), then the code will probably work just fine!
So, for example, the /teams URL would set a session named showThisPage to 'teams', and the /players URL would set the showThisPage session to 'players', and the Template.onePage.itIs would check the passed value against this session insetead.
Something like this (I'm just typing this straight into stack overflow without testing it, but it should work):
Meteor.Router.add({
   '/teams': function() { Session.set('showThisPage', 'teams'); },
   '/players': function() { Session.set('showThisPage', 'players'); }
});

Template.onePage.itIs = function(passed) {
  return Session.get('showThisPage') === passed;
};

Not tested like I said, but it should point you in the right direction.
(And instead of using the session you could just use Meteor.Router.page(), but you can read all about that on the Meteor Router page.)


text:
Q: Difference between "inflammable" and "flammable"
Possible Duplicate:
Why are not infamous and inflammable the opposite of famous and flammable like incomplete, inactivity, inappropriate and so on?

I'm very confused by the existence of these apparently antonymous words, which actually mean the same thing. Which word should I use? Can both words be used interchangeably?

A: The Free Dictionary advises using only flammable to give warnings:

Usage Note: Historically, flammable
  and inflammable mean the same thing.
  However, the presence of the prefix
  in- has misled many people into
  assuming that inflammable means "not
  flammable" or "noncombustible." The
  prefix in- in inflammable is not,
  however, the Latin negative prefix
  in-, which is related to the English un- and appears in such words as indecent and inglorious. Rather, this
  in- is an intensive prefix derived from the Latin preposition in. This
  prefix also appears in the word
  enflame. But many people are not aware
  of this derivation, and for clarity's
  sake it is advisable to use only
  flammable to give warnings.

A: Both words mean the same thing, i.e. that something can be set on fire.
The reason for the confusion comes from people thinking that the prefix in- of inflammable is the Latin negative prefix in- (which is commonly used in English, e.g. indecent). In actual fact, in this case it is derived from the Latin preposition in. It's easier to think about it with the word inflame. If you can inflame something, it is inflammable (inflame-able).
In most cases, it is better to just use flammable to avoid confusion and accidents.

A: Both are correct in all situations.
Same with regardless and irregardless (although the latter is more informal, and often declared incorrect: http://en.wikipedia.org/wiki/Irregardless)


text:
Q: java HashMap containsKey is returning false though key is present I am using a HashMap data structure to store a SqMatrix (square matrix), where the key is of type MatrixIndex (which contains row and col) and the value is of type Integer.
But when I am getting false as output of "if (mat.containsKey(key))" though the HashMap has the corresponding key in it.
The main code:
public static void main(String[] args) {

    Random generator = new Random();
    int val = 0;
    Types.MatrixIndex key, key1;
    int matSz = (int) Math.floor(Math.sqrt(10));
    Types.SqMatrix mat = new Types().new SqMatrix(matSz); //matSz*matSz elements
    //HashMap<Types.MatrixIndex,Integer> hMap= new HashMap<Types.MatrixIndex,Integer>(10);
    for (int r=0; r<matSz; r++) {
        for (int c=0; c<matSz; c++) {
            if (r<c) {
                val = generator.nextInt(2) > 0? -1 : val;
                key =(new Types()).new MatrixIndex(r, c);
                key1 = (new Types()).new MatrixIndex(c, r);
                mat.put(key, val);
                mat.put(key1, val);
                generator.setSeed(System.currentTimeMillis());
            }
        }
    }

    for (int r=0; r<matSz; r++) {
        val = 0;
        for (int c=0; c<matSz; c++) {
            if (r!=c) {
                key = (new Types()).new MatrixIndex(r, c);
                if (mat.containsKey(key)) {
                    val = val + mat.get(key);
                }

            }
        }
        key1 = (new Types()).new MatrixIndex(r, r);
        mat.put(key1, val);
    }

Do anybody have an idea on why the containsKey is returning false though it is present in the HashMap?
Thanks in advance,
Somnath

A: I have no idea what MatrixIndex is, but if it's hashcode implementation isn't overridden, then every instance of MatrixIndex has it's own hashcode, and is considered unique.  Therefore, you can't pass in a new instance of MatrixIndex to do a containsKey() check.
If you want that exact code snippet to work, you need to override equals() and hashcode() in your MatrixIndex class, and make it so that it always creates a reproducible, unique value for that class.
If you haven't done this before, definitely read up on overriding these two methods.  A quick search will bring up a great deal of help.  If you can add new libraries to your project, look at: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/HashCodeBuilder.html

A: Have you (correctly) defined equals() and hashCode() in your MatrixIndex class?

A: For containsKey() to succeed, the two objects (the one you test and the one found in the Map's keys) MUST have the same hashCode() (for non-null objects) AND equals() MUST [symmetrically] succeed for them.

containsKey() "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.)" (reference).

A: Most probably you forgot to override MatrixIndex.hashCode() and/or MatrixIndex.equals(). The default versions inherited from Object class compare object identity, not the objects' contents and will not do what you might be expecting.


text:
Q: black area above navigation bar appears when search bar is not active? I have a search controller added to navigationController.searchController. When the screen initially loads there is a black space above the navigation bar. Only when I tap on the search bar this space correctly shows white. When I tap off the search bar, this area shows black again.
import UIKit
import Foundation
import InstantSearch

class AlgoliaViewController: UIViewController, UISearchBarDelegate {

let userHitsInteractor: HitsInteractor<User> = .init(infiniteScrolling: .off, showItemsOnEmptyQuery: false)
let businessHitsInteractor: HitsInteractor<Business> = .init(infiniteScrolling: .off, showItemsOnEmptyQuery: false)

let multiSearch = MultiIndexSearcher(appID: APP_ID, apiKey: APP_KEY, indexNames: ["dev_USERS","dev_BUSINESS"])
lazy var multiConnector: MultiIndexSearchConnector = .init(searcher: multiSearch, indexModules: [
    .init(indexName: "dev_USERS",
          hitsInteractor: userHitsInteractor),
    .init(indexName: "dev_BUSINESS",
          hitsInteractor: businessHitsInteractor)
  ], searchController: searchController, hitsController: hitsTableViewController)

  lazy var searchController: UISearchController = .init(searchResultsController: hitsTableViewController)

let hitsTableViewController = MultiIndexController()
  let statsInteractor: StatsInteractor = .init()

override func viewDidLoad() {
    super.viewDidLoad()

    multiConnector.connect()
    multiSearch.search()
    statsInteractor.connectController(self)
    setupUI()
}

func setupUI() {
    view.backgroundColor = .white

    navigationItem.searchController = searchController
    navigationController?.navigationBar.backgroundColor = .white

//        navigationItem.titleView = searchController.searchBar

    navigationController?.navigationBar.backgroundColor = .white
    navigationController?.navigationBar.isTranslucent = false
    navigationController?.hidesBarsOnSwipe = false

    searchController.hidesNavigationBarDuringPresentation = false
    searchController.showsSearchResultsController = true
    searchController.automaticallyShowsCancelButton = false
    searchController.searchBar.delegate = self
    searchController.obscuresBackgroundDuringPresentation = false

    hitsTableViewController.view.backgroundColor = .white
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchController.isActive = true
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchController.isActive = false
}

}

extension AlgoliaViewController: StatsTextController {

  func setItem(_ item: String?) {
title = item
  }
}

class MultiIndexController: UITableViewController, MultiIndexHitsController {
var hitsSource: MultiIndexHitsSource?

let cellID = "cellID"

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(ResultsItemCell.self, forCellReuseIdentifier: cellID)
    setupUI()

    self.tableView.keyboardDismissMode = .onDrag
}

func setupUI() {
    view.backgroundColor = .white
    tableView.backgroundColor = .white
    tableView.separatorStyle = .none
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return (hitsSource?.numberOfSections())!
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return (hitsSource?.numberOfHits(inSection: section)) ?? 0
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
    let sectionTitle = UILabel(frame: CGRect(x: 0, y: 0, width: headerView.frame.width, height: headerView.frame.height))
    Utilities.styleLblFont(sectionTitle, fontName: "Cabin-SemiBold", fontSize: 18, color: .black)
    var headertitle = ""
    switch section {
    case 0:
        print("section 0")
        headertitle = "People"
    case 1:
        print("section 1")
        headertitle = "Businesses"
    default:
        break
    }
    headerView.backgroundColor = .white
    sectionTitle.text = headertitle
    headerView.addSubview(sectionTitle)
    return headerView
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! ResultsItemCell

    switch indexPath.section {
    case 0:
        if let item: User = try? hitsSource?.hit(atIndex: indexPath.row, inSection: indexPath.section) {
            cell.nameLbl.text = item.userName
            cell.avatar.loadImage(item.profilePhotoUrl)
            cell.jobTitleLbl.text = item.userType
      }

    case 1:
        if let business: Business = try? hitsSource?.hit(atIndex: indexPath.row, inSection: indexPath.section) {
            cell.nameLbl.text = business.businessName
            cell.avatar.loadImage(business.businessAvatarUrl)
            cell.jobTitleLbl.text = business.mission
      }
    default:
        break
    }

    return cell

}

override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
    let seeResultsBtn = UIButton(frame: CGRect(x: 0, y: 0, width: footerView.frame.width, height: footerView.frame.height))
    var footerTitle = ""
    switch section {
    case 0:
        footerTitle = "See all people"
    case 1:
        footerTitle = "See all businesses"
    default:
        footerTitle = "See all results"
    }

    footerView.addSubview(seeResultsBtn)
    seeResultsBtn.translatesAutoresizingMaskIntoConstraints = false
    seeResultsBtn.centerYAnchor.constraint(equalTo: footerView.centerYAnchor).isActive = true
    seeResultsBtn.centerXAnchor.constraint(equalTo: footerView.centerXAnchor).isActive = true
    Utilities.buttonTitle(seeResultsBtn, title: footerTitle, titleColour: .jabiMain, fontName: "Cabin-Medium", fontSize: 16)
    footerView.backgroundColor = .white
    return footerView
}

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 50
}

}

Please see the screenshots:


text:
Q: Java to C # code translation error in huffman encryption Well you will see the problem is that I am translating a C # java code that encrypts a text file by the huffman method, in java where the original program runs perfect but the question here is that I need it in C #.
I'm trying to translate it to C # but it generates 4 errors inside the setPrefixCodes and buildTree methods which I don't understand anything and I don't know what I'm translating wrong, or I need to implement something else.
I really need to know how to translate it correctly
Help!!!!!!
namespace Huffman_v2
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        String documento;

        private static IDictionary<char, string> charPrefixHashMap = new Dictionary<char, string> ();

        internal static HuffmanNode root;

        private void btnCifrar_Click(object sender, EventArgs e)
        {
            string txtText = documento;
            IDictionary<char, int> freq = new Dictionary<char, int> ();
            for (int i = 0; i < txtText.Length; i++)
            {
                if (!freq.ContainsKey(txtText[i]))
                {
                    freq[txtText[i]] = 0;
                }

                freq[txtText[i]] = freq[txtText[i]] + 1;
            }

            txtFrecuencia.Text = freq.ToString();
            root = buildTree(freq);
            setPrefixCodes(root, new StringBuilder());
            StringBuilder s = new StringBuilder();

            for (int i = 0; i < txtText.Length; i++)
            {
                char c = txtText[i];
                s.Append(charPrefixHashMap[c]);
            }
            string xs = decode(s.ToString());
            txtPrefijos.Text = charPrefixHashMap.ToString();
            txtCifrado.Text = xs.ToString();
        }

        private static void setPrefixCodes(HuffmanNode node, StringBuilder prefix)
        {
            if (node != null)
            {
                if (node.left == null && node.right == null)
                {
                    charPrefixHashMap[node.data] = prefix.ToString();
                }
                else
                {
                    prefix.Append('0');
                    setPrefixCodes(node.left, prefix);
                    prefix.deleteCharAt(prefix.Length - 1); //error en .deleteChatAt
                    prefix.Append('1');
                    setPrefixCodes(node.right, prefix);
                    prefix.deleteCharAt(prefix.Length - 1); //error en .deleteChatAt
                }
            }
        }

        private static string decode(string s)
        {
            StringBuilder stringBuilder = new StringBuilder();
            HuffmanNode temp = root;

            for (int i = 0; i < s.Length; i++)
            {
                int j = int.Parse(s[i].ToString());
                if (j == 0)
                {
                    temp = temp.left;
                    if (temp.left == null && temp.right == null)
                    {
                        stringBuilder.Append(temp.data);
                        temp = root;
                    }
                }

                if (j == 1)
                {
                    temp = temp.right;
                    if (temp.left == null && temp.right == null)
                    {
                        stringBuilder.Append(temp.data);
                        temp = root;
                    }
                }
            }
            return stringBuilder.ToString();
        }

        private static HuffmanNode buildTree(IDictionary < char, int > freq)
        {
            PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<HuffmanNode>(); // esta linea tiene el error en PriorityQueue<HuffmanNode>
            ISet<char> keySet = (ISet<char>) freq.Keys;

            foreach(char ? c in keySet) {
                HuffmanNode huffmanNode = new HuffmanNode();
                huffmanNode.data = (char) c;
                huffmanNode.frequency = freq.get(c); //aqui en .get
                huffmanNode.left = null;
                huffmanNode.right = null;
                priorityQueue.offer(huffmanNode);
            }

            Debug.Assert(priorityQueue.size() > 0);
            while (priorityQueue.size() > 1)
            {
                HuffmanNode x = priorityQueue.peek();
                priorityQueue.poll();
                HuffmanNode y = priorityQueue.peek();
                priorityQueue.poll();
                HuffmanNode sum = new HuffmanNode();
                sum.frequency = x.frequency + y.frequency;
                sum.data = '-';
                sum.left = x;
                sum.right = y;
                root = sum;
                priorityQueue.offer(sum);
            }
            return priorityQueue.poll();
        }
    }
}


text:
Q: Attempting to SELECT, reduce by 1 then UPDATE with php/mysql Just trying to find a Value of a table field and then reduce it by one using MySQL via PHP?
Is there an simple way to do this?
Below code will not process...
Cheers, J
<?php
$conn = connectToDB();
/* DECLARE remaining AS INTEGER  */
settype($screenings, "integer");
/* SELECT CURRENT screenings VALUE AND ASSIGN TO remaining VARIABLE */
$findquery("SELECT screenings FROM screener_users WHERE user_id = '" . $userId . "';");
$screenings = $conn->query($findquery);
/* REDUCE THAT VALUE BY ONE */
$screenings--;
/* UPDATE screener_users WITH THAT NEW VALUE */
$updatequery = "UPDATE screener_users SET screenings = '" . $screenings . "' WHERE user_id = '" . $userId . "';";
$result = $conn->query($updatequery);
?>

A: It's fairly easy to do it in one command:
"UPDATE screener_users SET screenings = screenings - 1 WHERE user_id = '$userId'"

By the way, you're open for SQL injection. Take advantage of prepared statements and parameter binding for the user_id.

A: You are making a mistake on query call. As you can see at the documentation , it returns an PDOStatement, so you should call a resultset to get the value that you want. Something like this should work:
<?php
$conn = connectToDB();
settype($screenings, "integer");
$findquery("SELECT screenings FROM screener_users WHERE user_id = '" . $userId . "';");
foreach ($conn->query($findquery) as $row)
{
    $screenings = $row[0];
    $screenings--;
    $updatequery = "UPDATE screener_users SET screenings = '" . $screenings . "' WHERE user_id = '" . $userId . "';";
    $result = $conn->query($updatequery);
}
?>

Now you are calling the query to be executed and saying that it should get the resultset of wich row and assing it to $row while iterating over it. There, you call the first column of the query's return ($row[0]) and do the rest of the job.


text:
Q: A question about measuring light externally from an optical fiber I know that there are clamp meters to measure currents for electrical wires externally without almost not interfering the circuit.
I was wondering whether in the case of an optical fiber(single mode silica optical fiber), is there a technique or device/component which can detect the laser light power externally or wrapping a sensor around ect?

A: The light is trapped in the fibre due to the refractive index mismatch between the core and the cladding. Some light enters the cladding as an evanescent field and can be used to excite a thin film of fluorophore which may be externally detected.
Another method is to disolve or polish away the cladding and immerse the fibre into an fluid with an refractive index close to the core which allows light to escape the core and then can be detected.
Bending the fibre can cause light to enter the cladding and be externally detected.

A: The field in most SM fibers is contained within the core and surrounding cladding, so unless you're going to strip away the cladding you don't have access to the fields you're trying to measure. If you are willing to strip away the cladding you can make a coupler and measure energy by taking a few percent of the energy out of the core, but I think that's your only option.


text:
Q: How to play multiple live streaming in android application? I should develop an android app to play multiple rtsp live streaming in android application. The target is obviously a security multiple cams viewer as an app for an android mobile device. So far I got several solutions for either live streaming or single streaming, but none seems to work with both requirements. In particular:
a) android VideoView class can handle multiple movies but can't handle live streams (it seems to be waiting forever for the end of the stream?)
b) libVLC handles multiple live streams but overlaps them all on the same video area (I tried different layout schemas that may push the video on different screen areas, but in any case all videos are rendered overlapped
my goal is to have each live stream rendered over its own portion of the screen (either stretched or clipped, so far any solution would be good) with (in)decent frame rate (anything above 1 frame per second could be ok) and minimal delay. How would that be possible?

A: I think you may want to use ExoPlayer for this kind of purpose. There are some libraries out there that decode RTSP but I personally used ExoPlayer for RTSP and I was very happy with it.
Read more here: ExoPlayer - RTSP Support


text:
Q: About GCP Console login audit I wonder How to get "audit log" GCP Management Console (https://console.cloud.google.com) loggin failure ?
Thank you.

A: To access the logs in the Console you must access in the dashboard to the Stackdriver tab > Logs. It will show the logs in the Console without the need of accessing Stackdriver webpage.


text:
Q: Empty view is added to linear layout I want to inflate a given layout, add text to the textviews inside it and then add this view to a LinearLayout dynamically and this view is to be added multiple times in the linearLayout.
The view to be inflated is this :-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="5dp"
        android:layout_weight="1">
       <TextView
           android:textSize="13sp"
           android:id="@+id/tv1"

           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="5dp"
        android:layout_weight="3">
        <TextView

            android:id="@+id/tv2"
            android:textSize="13sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:padding="5dp"
        android:layout_weight="3">
        <TextView
            android:textSize="13sp"
            android:id="@+id/tv3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:textSize="13sp"
            android:id="@+id/tv4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

The LinearLayout inside which it has to be added is this :-
    <LinearLayout
    android:id="@+id/pass_info"
    android:layout_below="@+id/booking_title"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

</LinearLayout>

The final view should be like this :-
1 mark 50%
2 sam  30%
3 ava  45%

The view is added dynamically one below the other. The code which I used was this :-
 for(int i = 0; i <  getStudentCount(); i++){
        LayoutInflater vi=(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout insertPoint=(LinearLayout)findViewById(R.id.pass_info);
        View v=vi.inflate(R.layout.pass_item,insertPoint,false);

        TextView textView1=(TextView)v.findViewById(R.id.tv1);
        TextView textView2=(TextView)v.findViewById(R.id.tv2);
        TextView textView3=(TextView)v.findViewById(R.id.tv3);
        TextView textView4=(TextView)v.findViewById(R.id.tv4);

        textView1.setText(getRollNum(i));
        // likewise for other textviews
        insertPoint.addView(v);
        }

The views are added but it shows nothing, the textviews are blank. What is the probable cause?

A: Problems in your code
Your code has several issues regarding layout inflating and view binding. What you want to achieve is different from what your code implements.
Steps to achieve what you desire
What you want to do is:

*

*Create a class that inflates the layout with tv1, tv2... Let us say this class is called TextsClass. You can learn more about it here. This is where you will inflate the layout with the textviws.

*Then, inside this class, you do findViewById to tv1, tv2 and so on (tv1 = (TextView) findViewById(R.id.tv1); to bind them to the parent layout)

*Create methods to set the text in these TextViews, such as
public TextView setTv1Text(String text) tv1.setText(text);

*Then, in the for loop, you have to instance new TextClass objects. After you instance them, you get each of the TextViews and set their texts, such as:
TextsClass textsClass = new TextsClass(getContext());
textsClass.setTv1Text(getRollNum(i));
//Do it with the other textviews
insertPoint.add(textsClass);

Summary about your code

*

*You are inflating linearLayouts several times (the insertPoint one) inside the for loop and you only need to do that once (before the for loop)

*You are inflating one layout (insertPoint) and trying to bind views from ANOTHER layout into it (tv1, tv2...)

*You are binding views several times inside the loop, which is unnecessary (if not problematic)

*You are trying to use the same textviews to put into the insertPoint layout and you can't do that. You can't use layout.add(child) with repeated children, they all must be different (that's why you must always instance new children in the for loop, in our example, the TextsClass).

Try to follow the link from google to create custom views, that's the way to go and, then, follow the steps I specified here to achieve what you want.
Let me know if my answer helped you, cheers.

A:     Linearlayout  frameLayout = (LinearLayout ) view.findViewById(R.id.frm);
    LayoutInflater inflatr = (LayoutInflater) Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View  menuLayout = inflatr.inflate(R.layout.n_demoview, frameLayout, true);

This Will be work for me
I hope this will work for you!!


text:
Q: Close rx stream basing on amount of passed data by another stream I have an infinite stream:
someIntStream: Observable<Int>
and I'd like to expose a function with following signature:
fun retrieveInts(numberOfIntsToRetrieve: Int): Observable<Int>
, which should emit exactly the same items as someIntStream, but it should emit OnCompleted once it emits numberOfIntsToRetrieve ints. My solution:
fun retrieveInts(numberOfIntsToRetrieve: Int): Observable<Int> {
    val compositeDisposable = CompositeDisposable()
    val ints = mutableListOf<Int>()
    return Observable.create() { emitter ->
        compositeDisposable.add(
            someIntStream().subscribe { someIntItem ->
                ints.add(someIntItem)
                emitter.onNext(someIntItem)
                if (ints.size == numberOfIntsToRetrieve) {
                    emitter.onComplete()
                    compositeDisposable.dispose()
                }
            }
        )
    }
}

But it's nasty: I have to internally subscribe to stream and dispose it.
Any other ideas?


text:
Q: Batch rename files using find in content Long-time listener first-time caller.
I'm trying to use a windows batch script to search for specific strings in files contained in a directory, and classify them with a file name and random value for further processing.
This is what I have put together based on similar posts:
setlocal enabledelayedexpansion

for %%a in (C:\Temp\*.txt) do (

  set t1=string1-%RANDOM%.txt

  set t2=string2-%RANDOM%.txt

  find "string1" %%~fa && ren %%~fa %t1%

  find "string2" %%~fa && ren %%~fa %t2%

)

If I move the set commands outside the for loop it will work, but I need it to generate a random file name within the loop in case there's multiple files found with 'string1'.
Any help much appreciated!
Thanks.

A: In cmd, variables are replaced with it value when the block in which they are placed is readed. In your case, your set variables are replaced once, when the for is readed, and changes are not visible because once that replacement is done, there is no more variable replacement. That is the reason for the enabledelayedexpansion, but a change in code is needed
setlocal enabledelayedexpansion

for %%a in (C:\Temp\*.txt) do (
  set t1=string1-!RANDOM!.txt
  set t2=string2-!RANDOM!.txt
  find "string1" "%%~fa" && ren "%%~fa" !t1!
  find "string2" "%%~fa" && ren "%%~fa" !t2!
)

For delayed expansion of variables, it is necessary to indicate to cmd which of the variables should be replaced in each access. To do it, change % with ! when using the variable. This is not necessary for control variables in for command (your %%a), for which it is assumed.
Be careful, your code does not handle the posibility of duplicate file names. Random means random, not unique. Collisions are possible.


text:
Q: Zend - Fatal error: Uncaught Zend_View_Exception: script '/.phtml' Get the following error message on my app. The app is written with the Zend framework, but not by myself. Can anyone tell me what the error message says.
It is about an extra module after all and a template file is missing. Is that correct so far? Can I just copy it in there myself?
Fatal error: Uncaught Zend_View_Exception: script '/.phtml' not found in path

(/application/modules/default/views/scripts/) in
/library/Zend/View/Abstract.php:987 Stack trace: #0
/library/Zend/View/Abstract.php(883): Zend_View_Abstract->_script('/.phtml')
#1 /library/Zend/Controller/Action/Helper/ViewRenderer.php(910):
Zend_View_Abstract->render('/.phtml') #2
library/Zend/Controller/Action/Helper/ViewRenderer.php(931):
Zend_Controller_Action_Helper_ViewRenderer->renderScript('/.phtml', NULL) #3
library/Zend/Controller/Action/Helper/ViewRenderer.php(970):
Zend_Controller_Action_Helper_ViewRenderer->render() #4
/libr in
library/Zend/Controller/Plugin/Broker.php on line 335

Would be very grateful for any tip.
Greetz Bavra


text:
Q: NODEJS dns.lookup I'm trying to read a site's name from terminal and do a dnslookup to print its IP on screen , but the following code is throwing an error for some reason , here is the code
process.stdout.write('Enter the website name:<www.sitename.com>: ');
process.stdin.resume();
var dns = require('dns');
process.stdin.on('data',function(site) {

var lookup = site.toString('utf-8');
console.log(lookup);
dns.lookup(lookup,function(err,ip) {
    if (err) throw err;
    console.log(ip);
       });

});

The error is
if (err) throw err;
               ^
Error: getaddrinfo ENOENT
    at errnoException (dns.js:31:11)
    at Object.onanswer [as oncomplete] (dns.js:123:16)
Why isnt the code working ?

A: the data on stdin gives you the host with a trailing carriage return. This trailing CR leads to the getaddrinfo ENOENT exception.
modify your code with
var lookup = site.toString('utf-8').trim();


text:
Q: Is document write the preferred way to write html to a third party site for corporate branding? I have an existing header and footer navigation that I would like to apply to third-party applications and sites on various platforms.
Ideally I would like to instruct vendors to add one script tag in HEAD of the document that then uses javascript to do the following:

*

*Add stylesheets to document head

*Add script tags before the closing body tag (jquery and other libraries and a app.js)

*The app.js will then rely on jQuery to load navigation html after the opening body tag and other dom manipulation (adding classes, removing elements, etc.)

I after reviewing this discussion - is document write the best solution in the initial script tag given to a third party?
Thank you.

A: You don't need to document.write(); in order to inject code into the head. If they embed your remote JavaScript file into their page, anywhere, you should be able to just append a script/style elements to the head.
 var myScript = document.createElement('script');
 myScript.setAttribute('src', '...');
 myScript.setAttribute('type', 'text/javascript');
 document.getElementsByTagName('head')[0].appendChild( myScript );

If you look at the Google Analytics embed code, you'll see some similarities. It's short enough that you should be able to figure out what is going on:
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', '...', 'auto');
  ga('send', 'pageview');

</script>

A: I would not use document.write for this because anytime this method is called after the window is loaded, it wipes everything out except for what you just wrote to the document.
Instead, I would use document.createElement() to create the tags, and then use appendChild() to add the js files or elements to the elements and then to the document.
var script1 = document.createElement("script");
var script1File = document.createTextNode(myfilepath.js);
script1.appendChild(script1File);
document.body.appendChild(script1);

This should add the script to the bottom of the body. This way, triggers can be set in the JS files without wiping the document clean every time one is called. Rinse, wash and repeat for other elements.


text:
Q: laravel database where condition Below is my laravel query to selct data...
$mydata = DB::table('History')
    ->where('Start','>=',$Start)
    ->andwhere('Start','<=',$End)
    ->select()->get();

Lets assume in database we have data from 3-10 (start).....user inputs
1)case
    $start = 2;
    $end = 10;
2)case
    $start = 4;
    $end = 10;
using the query I am getting data between 3-10 for 1) case ...
In the first case,I dont want to display any data, in second case i want to display data between 4-10 only...condition should be something like
start=data<=end not start<=data<=end
i also tried ...
$mydata = DB::table('History')
    ->where('Start',$Start)
    ->andwhere('Start','<=',$End)
    ->select()->get();

but still not fixed any ways to fix this laravel?

A: Your question has nothing to do with Laravel per se. In order to achieve your goal you have to probe your data in your query prior to filtering the resultset. Your query in plain SQL can look like this
SELECT h.*
FROM history h JOIN
(
  SELECT a.start, MIN(h.start) min_start, a.end, MAX(h.start) max_end
    FROM history h JOIN (SELECT 2 start, 10 end) a
      ON h.start BETWEEN a.start AND a.end
) q
    ON h.start BETWEEN q.start AND q.end
   AND q.start >= q.min_start AND q.end <= q.max_end

This particular query will return an empty resultset.
If you change (SELECT 2 start, 10 end) a to (SELECT 4 start, 10 end) a you'll get

+-------+
| start |
+-------+
|     4 |
|     5 |
|     6 |
|     7 |
|     8 |
|     9 |
|    10 |
+-------+


text:
Q: How to pick(choose) multiple files at the same time in phonegap I googled and search here i didn't find any opted solution relates to multiple file picker or chooser in phonegap. Currently i am able pick single file at a time in phonegap(for Android) without any plugins Using this to get file. How to pick or choose multiple files at a time in phonegap. Please suggest some solutions.

A: Please try this:
Download this demo..
http://ramkulkarni.com/temp/2012-04-09/FileChooser_PG_3_3.zip
Replce this on index.html
    file_Browser_params = new Object()
    file_Browser_params.on_file_select = function (fileEntry)
    {
        //$("#fileMsgSpan").html("You selected " + fileEntry.fullPath);
        $("#fileMsgSpan").html("You selected " + fileEntry);
        return false;
    }

Replace all filebrowser.html with this code

File Chooser

            New File
            New Dir

            OK
            Cancel


text:
Q: How to get client time in php? I can't get the client's time using PHP. I only get the server time using:
$cur_time = date('d-m-Y h:i:s A');

How can I fix this problem?
Someone said "You can fix it using timezone". But how can I?
I want to solve this problem without using JavaScript.

A: You need some javascript first to get the browsers timezone
Determine a user's timezone
Then use the timezone in your php script to calculate the current time where the browser is.
$tz = new DateTimeZone($browser_tz);
$dt = new DateTime();
$dt->setTimezone($tz);
$cur_time = $dt->format("d-m-Y h:i:s A");

A: If you want to achieve this just using PHP:

*

*Fetch User's IP Address

*Locate User's Location based on their IP Address. This can be done using 3rd Party API or, GEO IP Databases

*Get User's Timezone with the Country Code and with/without Region Code

*Get Time According to the timezone.

MaxMind's Dev: https://dev.maxmind.com/geoip/
Code:
<?php

if(!isset($_COOKIE['timezone'])){

    $ip = $_SERVER['REMOTE_ADDR'];

    //Open GeoIP database and query our IP
    $gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
    $record = geoip_record_by_addr($gi, $ip);

    //If we for some reason didnt find data about the IP, default to a preset location.
    //You can also print an error here.
    if(!isset($record))
    {
        $record = new geoiprecord();
        $record->latitude = 59.2;
        $record->longitude = 17.8167;
        $record->country_code = 'SE';
        $record->region = 26;
    }

    //Calculate the timezone and local time
    try
    {
        //Create timezone
        $user_timezone = new DateTimeZone(get_time_zone($record->country_code, ($record->region!='') ? $record->region : 0));

        setcookie("timezone", $user_timezone, time() + (86400 * 30), "/"); //setting cookie to the browser for reference

        //Create local time
        $user_localtime = new DateTime("now", $user_timezone);
        $user_timezone_offset = $user_localtime->getOffset();
    }
    //Timezone and/or local time detection failed
    catch(Exception $e)
    {
        $user_timezone_offset = 7200;
        $user_localtime = new DateTime("now");
    }

    echo 'User local time: ' . $user_localtime->format('H:i:s') . '
';
    echo 'Timezone GMT offset: ' . $user_timezone_offset . '
';
}
?>

Note: PHP code might not be effective all the time. The javascript code written above will ensure that the PHP-fetched timezone match the timezone with the browser, otherwise it updates the timezone info in cookie and reloads the page.


text:
Q: Using Google Maps API to get Address of Business I have a requirement and I am hoping Google Maps API will have a solution. I have never used Google Maps API - so I am very new to this.
On the website homepage there is a form, when a user comes, I want the following things to happen:
1) The city field should be populated with users city based on IP
2) There is a second field called store name - when the user starts typing the store name - I want to fetch all business listings with that name in that city and show it as a drop down from which the user can select the appropriate branch. There is no need for anything to be shown on the map.
Egs - If a user in houston starts typing McDonalds, the following business listings should start showing up

*
*McDonalds, 12 Pearland Ave, Houston TX

*McDonalds, 2600 Bary Area Blvd, Houston TX

*McDonalds, 262 Clearlake Blvd, Houston TX

Also when we get the address for a business listing from Google API - do we get it as one String and we need to parse it or do we get it different fields Street Name, City, State, Zip code etc
Any information or examples will be really appreciated
Thanks

A: updated: here is an example of using the google clientlocation api and localsearch using jsonp.

    <title></title>

    <form id="form1" runat="server">

        latitude :

        longitude :

        city :

        region :

        country :

        country_code :

    <input type="text" id="txtSearch" /><input type="button" id="btnSearch" value="get results"
        onclick="search();" />

    </form>

// <copyright file="clientLocation.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>

/*
object literal format for google.loader.clientlocation
{
"latitude": 33.324,
"longitude": -111.867,
"address": {
"city": "Chandler",
"region": "AZ",
"country": "USA",
"country_code": "US"
}
}
*/

var ClientLocation = {};

ClientLocation.Address = function() {
    /// <field name="city" type="String" />
    /// <field name="region" type="String" />
    /// <field name="country" type="String" />
    /// <field name="country_code" type="String" />
    /// <returns type="ClientLocation.Address"/>
    if (arguments.length > 0) {
        this.city = arguments[0].city;
        this.region = arguments[0].region;
        this.country = arguments[0].country;
        this.country_code = arguments[0].country_code;
        return;
    }
    else {
        this.city = "";
        this.region = "";
        this.country = "";
        this.country_code = "";
    }

}
ClientLocation.Location = function() {
    /// <field name="latitude" type="Number" />
    /// <field name="longitude" type="Number" />
    /// <field name="address" type="ClientLocation.Address" />
    if (arguments.length > 0) {

        this.latitude = arguments[0].latitude;
        this.longitude = arguments[0].longitude;
        this.address = arguments[0].address;

    }
    else {
        this.latitude = 0;
        this.longitude = 0;
        this.address = undefined;
    }

}

// <copyright file="localSearc.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>
/*
GlocalSearch result

{
"GsearchResultClass": "GlocalSearch",
"viewportmode": "computed",
"listingType": "local",
"lat": "33.389689",
"lng": "-111.853909",
"accuracy": "8",
"title": "Best \u003cb\u003eBuy\u003c/b\u003e",
"titleNoFormatting": "Best Buy",
"ddUrl": "http://www.google.com/maps....",
"ddUrlToHere": "http://www.google.com/maps?....",
"ddUrlFromHere": "http://www.google.com/maps?....",
"streetAddress": "1337 South Alma School Road",
"city": "Mesa",
"region": "AZ",
"country": "United States",
"staticMapUrl": "http://mt.google.com/mapdata?....",
"url": "http://www.google.com/maps/place?source....",
"content": "",
"maxAge": 604800,
"phoneNumbers": [{
"type": "",
"number": "(480) 644-7139"
},
{
"type": "",
"number": "(480) 464-0444"
}],
"addressLines": ["1337 South Alma School Road", "Mesa, AZ"]
}

*/

var LocalSearch = {};

LocalSearch.PhoneNumber = function() {
    /// <field name="type" type="String"/>
    /// <field name="number" type="String"/>
    /// <returns type="LocalSearch.PhoneNumber"/>

    if (arguments.length > 0) {
        this.type = arguments[0].type;
        this.number = arguments[0].number;
    }
    else {
        this.type = "";
        this.number = "";
    }
}

LocalSearch.Result = function() {
    /// <field name="GsearchResultClass" type="String"/>
    /// <field name="viewportmode" type="String"/>
    /// <field name="listingType" type="String"/>
    /// <field name="lat" type="String"/>
    /// <field name="lng" type="String"/>
    /// <field name="accuracy" type="String"/>
    /// <field name="title" type="String"/>
    /// <field name="titleNoFormatting" type="String"/>
    /// <field name="ddUrl" type="String"/>
    /// <field name="ddUrlToHere" type="String"/>
    /// <field name="ddUrlFromHere" type="String"/>
    /// <field name="streetAddress" type="String"/>
    /// <field name="city" type="String"/>
    /// <field name="region" type="String"/>
    /// <field name="country" type="String"/>
    /// <field name="staticMapUrl" type="String"/>
    /// <field name="url" type="String"/>
    /// <field name="content" type="String"/>
    /// <field name="maxAge" type="Number"/>
    /// <field name="phoneNumbers" type="Array"/>
    /// <field name="addressLines" type="Array"/>
    // <returns type="LocalSearch.Result"/>
    if (arguments.length > 0) {
        this.GsearchResultClass = arguments[0].GsearchResultClass;
        this.viewportmode = arguments[0].viewportmode;
        this.listingType = arguments[0].listingType;
        this.lat = arguments[0].lat;
        this.lng = arguments[0].lng;
        this.accuracy = arguments[0].accuracy;
        this.title = arguments[0].title;
        this.titleNoFormatting = arguments[0].titleNoFormatting;
        this.ddUrl = arguments[0].ddUrl;
        this.ddUrlToHere = arguments[0].ddUrlToHere;
        this.ddUrlFromHere = arguments[0].ddUrlFromHere;
        this.streetAddress = arguments[0].streetAddress;
        this.city = arguments[0].city;
        this.region = arguments[0].region;
        this.country = arguments[0].country;
        this.staticMapUrl = arguments[0].staticMapUrl;
        this.url = arguments[0].url;
        this.content = arguments[0].content;
        this.maxAge = arguments[0].maxAge;
        this.phoneNumbers = arguments[0].phoneNumbers;
        this.addressLines = arguments[0].addressLines;

    }
    else {

        this.GsearchResultClass = "";
        this.viewportmode = "";
        this.listingType = "";
        this.lat = "";
        this.lng = "";
        this.accuracy = "";
        this.title = "";
        this.titleNoFormatting = "";
        this.ddUrl = "";
        this.ddUrlToHere = "";
        this.ddUrlFromHere = "";
        this.streetAddress = "";
        this.city = "";
        this.region = "";
        this.country = "";
        this.staticMapUrl = "";
        this.url = "";
        this.content = "";
        this.maxAge = 0;
        this.phoneNumbers = [];
        this.addressLines = [];
    }

}

A: If you're only looking up restaurants, try using Yelp's API. You can search for a business by its name within a search radius. Their API is also simpler and easier to use than google's.
http://www.yelp.com/developers/documentation/search_api

A: I don't think you want Google Maps. First of all the terms of use do not allow any use other than displaying things on a Google Map on a publicly accessible webpage, second, there is another Google API that does exactly what you need: the Client location API: http://code.google.com/apis/ajax/documentation/#ClientLocation
Concerning the "businesses": You're going to have to source that data from somewhere - I do not believe google has a service for that. Perhaps  you could simply use the Google Search API and some logic to find only businesses (http://code.google.com/apis/ajaxsearch/)
EDIT: I for the businesses, perhaps you could take a look at this sample: http://code.google.com/apis/ajaxsearch/samples.html#local-search


text:
Q: Install Laravel Framework on cPanel VPS Laravel seems to be a great framework to take advantage of, but it's raising hell to install properly.
Apparently I followed all the directions properly and it's installed just fine, but when it comes to an autoloader, it won't do anything.

Warning:
require(/home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/bootstrap/../vendor/autoload.php):
failed to open stream: No such file or directory in
/home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/bootstrap/autoload.php
on line 17
Fatal error: require(): Failed opening required
'/home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/bootstrap/../vendor/autoload.php'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/bootstrap/autoload.php
on line 17

This is what I see when I list what's in my laravel directory.
So, is it a directory issue? I'm testing it under a /testing/ directory, is that my issue?

A: You need to execute:
composer install

Or
sudo composer install

Or, if you don't have access to your box via command line (SSH?), you will have to copy the whole vendor folder via FTP or any file copy utility you are able to use with your server.
To check if you have a vendor folder, execute:
ls -la /home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/

You should see something like
drwxrwsr-x  6 mywumbo mywumbo    16 Feb 26 09:37 ./
drwxrwsr-x 12 mywumbo mywumbo    14 Feb 26 09:37 app/
-rw-rw-r--  1 mywumbo mywumbo  2451 Feb 26 09:37 artisan
drwxrwsr-x  2 mywumbo mywumbo     5 Feb 26 09:37 bootstrap/
-rw-rw-r--  1 mywumbo mywumbo   697 Feb 26 09:37 composer.json
-rw-rw-r--  1 mywumbo mywumbo 56230 Feb 26 09:37 composer.lock
-rw-rw-r--  1 mywumbo mywumbo   145 Feb 26 09:37 CONTRIBUTING.md
-rw-rw-r--  1 mywumbo mywumbo    11 Feb 26 09:37 .gitattributes
-rw-rw-r--  1 mywumbo mywumbo   103 Feb 26 09:37 .gitignore
-rw-rw-r--  1 mywumbo mywumbo   566 Feb 26 09:37 phpunit.xml
drwxrwsr-x  3 mywumbo mywumbo     8 Feb 26 09:37 public/
-rw-rw-r--  1 mywumbo mywumbo  1913 Feb 26 09:37 readme.md
-rw-rw-r--  1 mywumbo mywumbo   519 Feb 26 09:37 server.php
drwxrwsr-x 20 mywumbo mywumbo    21 Feb 26 09:37 vendor/

Last one, is your vendor folder, inside it there should have a autoload.php file, which is missing in the error:
Warning: require(/home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /home/mywumbo/public_html/testing/Laravel-and-Angular-Goodness-master/bootstrap/autoload.php on line 17


text:
Q: CodeIgniter uploading files I am strugling to upload files with codeIgniter. Something i am doing wrong, can some one explain to me file premision, and how to change it on windows. Should i set only to folder where i upload files or to also patent folders. My code is in form

    <form id="form" enctype="multipart/form-data" name="form" action="<?php echo site_url('admin/clients/add_client');?>"  method="post" >
         Client Name:
<input type="text" name="name" id="name"/>

         LOgo: <input type="file" name="file" id="file"/>

         <input type="submit"/>
    </form>

and controller
$this->load->library('upload');
$config['upload_path'] = './att/';
$config['allowed_types'] = 'png|jpg|bmp';
$this->upload->initialize($config);
$upload = $this->upload->do_upload();

i dont know what i am doing wrong
Should i ajdust htaccess file?
$config['upload_path'] = './att/';

is it maybe this line wrong att folder child of CodeIgniter folder
should i check file premison. I add for this folder full control.
In controller i get result when i print_r $_FILES['file']['name'], but some how nothing in folder???

A: Try something like this:
$this->upload->do_upload('file'); #The field name of the file you are trying to upload

A: Try something like this:
$this->config =  array(
                  'upload_path'     => dirname($_SERVER["SCRIPT_FILENAME"])."/att/",
                  'upload_url'      => base_url()."att/",
                  'allowed_types'   => "png|jpg|bmp|jpeg"
                );

$this->load->library('upload', $this->config);
if($this->upload->do_upload()){
    echo "file upload success"; }
else{
    echo "file upload failed";
}

A: <input type="file" name="userfile1" class="form-control" />
<input type="file" name="userfile2" class="form-control" />

If you want to use it many times, change the back and so on
$filename1 ="";
$filename2 ="";
        if(isset($_FILES['userfile1']['name'])){
            $rand = rand(111111,999999);
            $target_dir = "files/img/examination/";
            $target_file = $target_dir . basename($rand."-".$_FILES["userfile1"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            // Check if image file is a actual image or fake image
            if(isset($_POST["submit"])) {
                $check = getimagesize($_FILES["userfile1"]["tmp_name"]);
                if($check !== false) {
                    //echo "File is an image - " . $check["mime"] . ".";
                    $uploadOk = 1;
                } else {
                    echo "File is not an image.";
                    $uploadOk = 0;
                }
            }
            // Check if file already exists
            if (file_exists($target_file)) {
            //  echo "Sorry, file already exists.";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["userfile1"]["size"] > 10000000) {
                //echo "Sorry, your file is too large.";
                $uploadOk = 0;
            }
            // Allow certain file formats
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
                //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                $uploadOk = 0;
            }
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                //echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["userfile1"]["tmp_name"], $target_file)) {
                    $filename1 = $rand."-".$_FILES["userfile1"]["name"];
                    //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                } else {
                    //echo "Sorry, there was an error uploading your file.";
                }
            }

          }else{
            $filename1 = "";
        }

        if(isset($_FILES['userfile2']['name'])){
            $rand = rand(111111,999999);
            $target_dir = "files/img/examination/";
            $target_file = $target_dir . basename($rand."-".$_FILES["userfile2"]["name"]);
            $uploadOk = 1;
            $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
            // Check if image file is a actual image or fake image
            if(isset($_POST["submit"])) {
                $check = getimagesize($_FILES["userfile2"]["tmp_name"]);
                if($check !== false) {
                    //echo "File is an image - " . $check["mime"] . ".";
                    $uploadOk = 1;
                } else {
                    echo "File is not an image.";
                    $uploadOk = 0;
                }
            }
            // Check if file already exists
            if (file_exists($target_file)) {
            //  echo "Sorry, file already exists.";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["userfile2"]["size"] > 10000000) {
                //echo "Sorry, your file is too large.";
                $uploadOk = 0;
            }
            // Allow certain file formats
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
            && $imageFileType != "gif" ) {
                //echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                $uploadOk = 0;
            }
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                //echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["userfile2"]["tmp_name"], $target_file)) {
                    $filename1 = $rand."-".$_FILES["userfile2"]["name"];
                    //echo "The file ". basename( $_FILES["userfile2"]["name"]). " has been uploaded.";
                } else {
                    //echo "Sorry, there was an error uploading your file.";
                }
            }

          }else{
            $filename2 = "";
        }


text:
Q: How can I retrieve Unicode characters from IMAP in PHP? I'm trying to parse an email that is partially written in English and partially written in Japanese using PHP. Here's the code I have so far:
if ($mbox = imap_open($mailbox, $username, $password)) {

    $inbox = imap_check($mbox);
    $total = (int) $inbox->Nmsgs;
    $min = max(1, $total - 10);

    // fetch 10 most recent emails
    if ($total > 0 && ($emails = imap_fetch_overview($mbox, "{$min}:{$total}"))) {

        foreach ($emails as $email) {

            $body = imap_body($mbox, $email->uid, FT_UID);

            // for testing purposes
            echo $body;

            // parsing logic here

        }
    }
}

So as you can see I'm just echoing out the plaintext body of the email, just to test things, and here's part of the echoed response I get when I run this script:

Your Japanese word of the day is: ç"·ã®å

However, the following is what I should see in place of that, based on what's actually in the email:

Your Japanese word of the day is: 男の子

So clearly something's being lost in translation (pun intended). I'm using some simple string manipulation to try and parse the Japanese characters, and then insert them into a MySQL database. However, it's currently inserting those gobbledygook characters instead. What am I missing?
Edit: I'm using PHP version 5.4.45

A: So I'm not really sure how to get this working in PHP 5. I decided to try upgrading my server to PHP 7 and suddenly all of the code just started working.


text:
Q: SQLAlchemy IN_ - trouble with leading zeroes In my sqlalchemy ( sqlalchemy = "^1.4.36" ) query I have a clause:
.filter( some_model.some_field[2].in_(['item1', 'item2']) )
where  some_field is jsonb and the value in some_field value in the db formatted like this:
["something","something","123"]
or
["something","something","0123"]
note: some_field[2] is always digits-only double-quoted string, sometimes with leading zeroes and sometimes without them.
The query works fine for cases like this:
.filter( some_model.some_field[2].in_(['123', '345']) )
and fails when the values in the in_ clause have leading zeroes:
e.g. .filter( some_model.some_field[2].in_(['0123', '0345']) ) fails.
The error it gives:
cursor.execute(statement, parameters)\\npsycopg2.errors.InvalidTextRepresentation: invalid input syntax for type json\\nLINE 3: ...d_on) = 2 AND (app_cache.value_metadata -> 2) IN (\\'0123\\'\\n                                                             ^\\nDETAIL:  Token \"0123\" is invalid.
Again, in the case of '123' (or any string of digits without leading zero) instead of '0123' the error is not thrown.
What is wrong with having leading zeroes for the strings in the list of in_ clause? Thanks.
UPDATE: basically, sqlachemy's IN_ assumes int input and fails accordingly. There must be some reasoning behind this behavior, can't tell what it is. I removed that filter fromm the query and  did the filtering of the ouput in python code afterwards.

A: The problem here is that the values in the IN clause are being interpreted by PostgreSQL as JSON representations of integers, and an integer with a leading zero is not valid JSON.
The IN clause has a value of type jsonb on the left hand side. The values on the right hand side are not explicitly typed, so Postgres tries to find the best match that will allow them to be compared with a jsonb value. This type is jsonb, so Postgres attempts to cast the values to jsonb.  This works for values without a leading zero, because digits in single quotes without leading zeroes are valid representations of integers in JSON:
test# select '123'::jsonb;
 jsonb
═══════
 123
(1 row)

but it doesn't work for values with leading zeroes, because they are not valid JSON:
test# select '0123'::jsonb;
ERROR:  invalid input syntax for type json
LINE 1: select '0123'::jsonb;
               ^
DETAIL:  Token "0123" is invalid.
CONTEXT:  JSON data, line 1: 0123

Assuming that you expect some_field[2].in_(['123', '345']) and some_field[2].in_(['0123', '345']) to match ["something","something","123"] and ["something","something","123"] respectively, you can either serialise the values to JSON yourself:
some_field[2].in_([json.dumps(x) for x in ['0123', '345']])

or use the contained_by operator (<@ in PostgreSQL), to test whether some_field[2] is present in the list of values:
some_field[2].contained_by(['0123', '345'])

or cast some_field[2] to text (that is, use the ->> operator) so that the values are compared as text, not JSON.
some_field[2].astext.in_(['0123', '345'])


text:
Q: C# winform Unhandled exception occured after running the application on user login I have developed an C# WinForms application with the setup project in Visual Studio 2010 and am using SqlClient, .NET Entity Framework 4 and Crystal Reports 2011 as well.
I installed my WinForms application on other computer for testing purposes, the installation was successful. I have installed .NET EF 4 on the testing computer as well and when I run the installed application and when I click on login it give unhandled exception... error:

I really could not figure out the actual problem and am stuck. Any help will be highly appreciated.


text:
Q: Why my django project is not visible from domain but working fine when accessed from server ip address? I'm deploying a django project with nginx on digitalocean. When i accessed my project from server ip address, it is working fine but when i visited through domain connected with it, default welcome page of nginx is shown.
After reading previous questions on stackoverflow, i figured it out that it usually happense when your domain is not in allowed host setting of django.But this is not the case this time. Here is my sllowed hosts in django settings:-
ALLOWED_HOSTS=['server-ip-address','www.saporasocial.me','.saporasocial.me','saporasocial.me']

You can visit SaporaSocial
How can i solve this behaviour?
Edit
Here is the nginx config
server {
listen 80;
server_name saporasocial.me www.saporasocial.me server-ip-address;

location = /favicon.ico { access_log off; log_not_found off; }

location /static/ {
        root /home/user/project;
}

location /media/ {
        root /home/user/project/project;
}

location / {
        include proxy_params;
        proxy_pass http://unix:/home/user/project/project.sock;
}

}

Since i can see default nginx page, i do not think that nginx has any problem.

A: First add your domain
saporasocial.me

in the
Networking > Domains > Settings

of DigitalOceans.com cloud. Make sure it is pointing to your droplet IP address.
Next, you will need to change the Nameserver settings for your domain in the Domain name provider's control panel.


text:
Q: Autohotkey: Using a 3 key combination to initiate script? Basically I want to find a solution to make this code work by initiating it with b+down+right key combination.
~b & Left & Down::
{
    BlockInput On
    Click, Left, 1
    sleep, % _ran(150, 250)
    Click, Rel 144, 72 Left, 1
    sleep, % _ran(150, 250)
    Click, Rel 144, 72 Left, 1
    Click, Right
    BlockInput Off
}
return

The code works if I just switch it to ~b & left or ~b & down but the problem is with my brain and I need a 3 key combo.
Basically my monitor is a square (obviously) so the "up" would indicate clicking upwards, down for downwards and so on. But I'm using this scripts within a tilted square and it's hard to differentiate between down left and down right when I just use ~b & down.
The square on the outside is the monitor, the titled square inside is where I'm using the script and need a 3 key combination:

A: I actually figured it out.
        ~Right::
      If GetKeyState("b", "b") && GetKeyState("Up", "b")
      {
            BlockInput On
            Click, Left, 1
            sleep, % _ran(150, 250)
            Click, Rel 144, 72 Left, 1
            sleep, % _ran(150, 250)
            Click, Rel 144, 72 Left, 1
            Click, Right
            BlockInput Off
      }
      return


text:
Q: There was an error completing your request-google-home simulator page issue I have try to test my project in google home simulator. up to yesterday it was working but today it is showing error "There was an error completing your request"
URL: "https://console.actions.google.com/project/tell-you-profile/simulator/"

A: I was just having the same issue starting my simulator.   The problem was:  I was signed into Google Chrome, with my other (personal) email address.  Once I went to cloud.google.com, signed out, and signed back in with the account that matched the needed user for the Cloud Services, the simulator loads fine.
This was my simulator issue (just to confirm):

A: Most times this error is caused by an error in your fulfillment server. Check your code to make sure it compiled or is interpreted correctly and then check your logs for any errors.


text:
Q: cant start webpack / webpack not found i want to start webpack. I type this command
npm run dev

in the command shell where my project is and where the node_modules are.
I get this error in the terminal:
> clear; npm run --silent sound:trash; ./bin/webpack --env development --watch; npm run --silent sound:microwave

[3;J

sh: 1: ./bin/webpack: not found

I have looked in node_modules/bin/ and there is a file named webpack. Can somebody help me? I am new in stackoverflow and new in using webpack.
Package JSON
{
  "name": "xxx",
  "version": "1.1.0",
  "description": "",
  "main": "src/js/init.js",
  "scripts": {
    "sound:plock": "play -q -v 0.2 $(find /usr/share/sounds/ -type f -name *device-added* | head -n 1)",
    "sound:microwave": "play -q -v 0.1 $(find /usr/share/sounds/ -type f -name *complete* | head -n 1)",
    "sound:trash": "play -q -v 0.15 $(find /usr/share/sounds/ -type f -name *trash*  | head -n 1)",
    "clean:js": "rm $(find ./static/ -type f -regex '.*\\.[jt]sx?'); npm run --silent sound:trash",
    "clean:dir": "rm -rf ./static; npm run --silent sound:trash",
    "build": "clear; npm run --silent clean:dir; ./node_modules/.bin/webpack --env production --progress; npm run --silent sound:microwave",
    "build:server": "./node_modules/.bin/webpack --env production --progress",
    "dev": "clear; npm run --silent sound:trash; ./bin/webpack --env development --watch; npm run --silent sound:microwave",
    "test": "clear; npm run --silent build; ./bin/mocha --compilers js:babel-core/register --require jsdom-global/register; npm run --silent sound:plock",
    "test:monitor": "nodemon -x \"rm -rf ./build; babel ./src --out-dir ./build; ./bin/mocha --compilers js:babel-core/register --require jsdom-global/register; npm run --silent sound:plock\"",
    "stats": "./node_modules/.bin/webpack --env production --profile --json > webpack-build-stats.json"
  },
  "repository": {
    "type": "git",
    "url": "git@gitlab.gereon-reus.de:/l3pweb/pipeline"
  },
  "author": "",
  "license": "UNLICENSED",
  "devDependencies": {
    "@types/jquery": "*",
    "awesome-typescript-loader": "*",
    "babel-core": "*",
    "babel-eslint": "*",
    "babel-plugin-transform-object-rest-spread": "*",
    "babel-preset-env": "*",
    "babel-preset-es2015": "*",
    "babel-preset-flow": "*",
    "babel-preset-react": "*",
    "browser-sync": "*",
    "browser-sync-webpack-plugin": "*",
    "copy-webpack-plugin": "*",
    "css-loader": "*",
    "eslint": "*",
    "eslint-loader": "*",
    "eslint-plugin-flowtype": "*",
    "extract-text-webpack-plugin": "*",
    "file-loader": "*",
    "google-fonts-webpack-plugin": "*",
    "html-webpack-plugin": "*",
    "jsdom": "*",
    "jsdom-quokka-plugin": "*",
    "json-loader": "*",
    "less": "*",
    "less-loader": "*",
    "node-sass": "*",
    "nodemon": "*",
    "sass-loader": "*",
    "style-loader": "*",
    "svg-loader": "*",
    "trash-cli": "*",
    "ts-loader": "*",
    "ts-node": "*",
    "tslint": "*",
    "tslint-eslint-rules": "*",
    "typescript": "*",
    "url-loader": "*",
    "webpack": "^3.8.1",
    "webpack-bundle-analyzer": "*",
    "webpack-config": "*",
    "webpack-merge": "*"
  },
  "dependencies": {
    "@cartok/dagre-d3": "^0.4.52",
    "@cartok/hierarchy-select": "^1.0.0",
    "babel-polyfill": "^6.23.0",
    "d3": "^3.5.17",
    "datatables.net": "^1.10.15",
    "datatables.net-bs": "^1.10.15",
    "datatables.net-buttons": "^1.4.0",
    "datatables.net-buttons-bs": "^1.4.0",
    "datatables.net-colreorder": "^1.3.3",
    "datatables.net-colreorder-bs": "^1.3.3",
    "datatables.net-fixedheader": "^3.1.2",
    "datatables.net-fixedheader-bs": "^3.1.2",
    "datatables.net-keytable": "^2.2.1",
    "datatables.net-keytable-bs": "^2.2.1",
    "datatables.net-responsive": "^2.1.1",
    "datatables.net-responsive-bs": "^2.1.1",
    "datatables.net-scroller": "^1.4.2",
    "datatables.net-scroller-bs": "^1.4.2",
    "datatables.net-select": "^1.2.2",
    "datatables.net-select-bs": "^1.2.2",
    "dom-node-template": "^1.0.1",
    "jquery": "^3.2.1",
    "l3p-core": "^2.5.2",
    "list.js": "^1.5.0",
    "literal-observer": "^0.5.1",
    "lodash-es": "^4.17.4"
  },
  "quokka": {
    "babel": {
      "presets": [
        "env",
        "flow"
      ],
      "polyfill": true
    },
    "plugins": [
      "jsdom-quokka-plugin"
    ],
    "ts": true
  }
}

A: The correct path for webpack in a node project would be ./node_modules/.bin/wepback
And in a npm script you get access to all node modules as if they were on the PATH so you would want this:
"dev":"clear; npm run --silent sound:trash; webpack --env development --watch; npm run --silent sound:microwave"
Note that webpack doesn't need the folder scoping within the package.json
EDIT:
Or to keep it consistent with your build script:
"dev":"clear; npm run --silent sound:trash; ./node_modules/.bin/webpack --env development --watch; npm run --silent sound:microwave"

A: When running an NPM script defined in package.json, you do not need to specify relative paths to executables inside of the .\node_modules\.bin folder. In your case, that means replacing all occurrences of either:
./node_modules/.bin/webpack
./.bin/webpack

With just:
webpack

This will ensure that your NPM scripts are able to resolve the executables correctly.


text:
Q: ITunes Connect Localization - German, French I'm trying to add a German and French localization to the iTunes Connect Meta data. The app is in an editable state and I can choose from some given languages.

Also the docs mention French at the beginning of the article, but then there are the same language choices.
The App is localized and has the "Localization" key in the info.plist.
I'm not seeing anything I can do about that (already tried to change my system language as well)

A: If you scroll over that language page, can see French is waiting for you. That language pop-up is scrollable.


text:
Q: ¿Como convierto un array de bytes a una PublicKey? Quiero convertir un array de bytes a una PublicKey. El problema es que el array de bytes viene (o debería venir) codificado con ECDH y al ser clave pública X509. Se trata de la clave pública del DNIe. He estado probando con este código pero me devuelve:

Detect premature EOF

justo en la línea en la que convierto:
Data(en hex) = 0bbe0c8f66d755020f6a2a656c1111664c745836ac7dafbde0af484bd66b1d31a0ba7da687acd0ee1b695b54ea274d495cb613e90d3277159827f54f316e5833

 public static PublicKey loadPublicKey (byte[] data) throws Exception{
    PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(data));}

A: Intenta convertir el String Hexadecimal un Byte Array y cambiar el parametro de entrada a String.
public static byte[] HexToByteArr(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

public static PublicKey loadPublicKey(String myhex) throws Exception{
    PublicKey  publicKey;
    byte[] data = HexToByteArr(myhex);
    try {
        publicKey = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(data));
        return publicKey;
    } catch(InvalidKeySpecException e) {};

    throw new InvalidKeySpecException("EC DSA or RSA no compatibles");
}


text:
Q: creating a JTree from a heap Setup

I have a heap with intLevels levels and e elements (both ints) stored in a 2D array of Objects, heapArray, which is intLevels tall and Math.pow(2, intLevels) wide. For hypothetical purposes, let's say I input 1, 2, 3, 4, 5, 6, 7, 8, and 9. The heap will look something like this:
       9
   8       6
 7   3   2   5
1 4

and if you were to print it with a series of java.util.Arrays.toString(Object[] a)s, it would look like this:
[9, null, null, null, null, null, null, null]
[8, 6, null, null, null, null, null, null]
[7, 3, 2, 5, null, null, null, null]
[1, 4, null, null, null, null, null, null]

does anyone have any idea how to take this information and create a JTree out of it? For anyone who doesn't know, a JTree works much like a linked list. You have a root node which you add more nodes to, and you can add additional nodes on those. I know for a fact that if the only heap I was dealing with was this one, I would be able to make the tree this way:
jTree = new javax.swing.JTree();

treeNode1 = new javax.swing.tree.DefaultMutableTreeNode(9);
treeNode2 = new javax.swing.tree.DefaultMutableTreeNode(8);
treeNode3 = new javax.swing.tree.DefaultMutableTreeNode(7);
treeNode4 = new javax.swing.tree.DefaultMutableTreeNode(1);
treeNode3.add(treeNode4);
treeNode4 = new javax.swing.tree.DefaultMutableTreeNode(4);
treeNode3.add(treeNode4);
treeNode2.add(treeNode3);
treeNode3 = new javax.swing.tree.DefaultMutableTreeNode(3);
treeNode2.add(treeNode3);
treeNode1.add(treeNode2);
treeNode2 = new javax.swing.tree.DefaultMutableTreeNode(6);
treeNode3 = new javax.swing.tree.DefaultMutableTreeNode(2);
treeNode2.add(treeNode3);
treeNode3 = new javax.swing.tree.DefaultMutableTreeNode(5);
treeNode2.add(treeNode3);
treeNode1.add(treeNode2);
jTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));

which results in a tree looking like:
9
├8
│├7
││├1
││└4
│└3
└6
 ├2
 └5

Edit

I found implemented the answer's buildTree(List<Object[]>) method:
java.util.List<Object[]> objectArrays = new java.util.ArrayList<Object[]>();
objectArrays.addAll(Arrays.asList(heapArray));
jTree1 = buildTree(objectArrays);

it still doesn't seem to work; the tree remains empty.
Question

Does anyone know a relatively easy yet flexible way to make this 2D array into a JTree with the given information? If implemented correctly, inputting 1, 2, 3, 4, 5, 6, 7, 8, and 9 to this tree/heap/array should end up with the same result as the concrete way I showed above.

A: This class should do the trick. I've used recursion to allow any number of child levels (assuming there are enough object arrays and objects to support the tree).
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class TreeBuilder {

    public static void main(final String[] args) {

        // build the list of object arrays
        List<Object[]> objectArrays = new ArrayList<Object[]>();
        Object[] array1 = {9, null, null, null, null, null, null, null};
        Object[] array2 = {8, 6, null, null, null, null, null, null};
        Object[] array3 = {7, 3, 2, 5, null, null, null, null};
        Object[] array4 = {1, 2, null, null, null, null, null, null};
        objectArrays.add(array1);
        objectArrays.add(array2);
        objectArrays.add(array3);
        objectArrays.add(array4);

        // call the method under test
        JTree result = buildTree(objectArrays);

        // print the results
        if(result == null) {
            System.out.println("FAIL: returned null.");
        } else {
            recursePrintTree((DefaultMutableTreeNode)result.getModel().getRoot(), 0);
        }
    }

    public static void recursePrintTree(
            final DefaultMutableTreeNode treeNode,
            final int indentation) {

        // print the indentation spaces
        for(int index = 0; index < indentation; index++) {
            System.out.print("    ");
        }
        // print the value of the node
        System.out.println(treeNode.getUserObject());

        // enumerate the children of the node
        Enumeration enumeration = treeNode.children();
        while(enumeration.hasMoreElements()) {
            DefaultMutableTreeNode child =
                (DefaultMutableTreeNode)enumeration.nextElement();
            recursePrintTree(child, indentation + 1);
        }
    }

    public static JTree buildTree(final List<Object[]> objectArrays) {
        JTree jTree = new JTree();

        DefaultMutableTreeNode node = recurseBuildTree(objectArrays, 0, 0);
        if(node != null) {
            jTree.setModel(new DefaultTreeModel(node));
        }

        return jTree;
    }

    private static DefaultMutableTreeNode recurseBuildTree(
            final List<Object[]> objectArrays,
            final int objectArrayIndex,
            final int itemIndex) {

        DefaultMutableTreeNode node = null;

        if(objectArrayIndex < objectArrays.size()) {
            Object[] objectArray = objectArrays.get(objectArrayIndex);
            if(itemIndex < objectArray.length) {
                Object obj = objectArray[itemIndex];
                if(obj != null) {
                    node = new DefaultMutableTreeNode(obj);

                    DefaultMutableTreeNode childNode = recurseBuildTree(
                        objectArrays, objectArrayIndex + 1, itemIndex * 2);

                    if(childNode != null) {
                        node.add(childNode);
                    }

                    childNode = recurseBuildTree(
                        objectArrays, objectArrayIndex + 1, (itemIndex * 2) + 1);

                    if(childNode != null) {
                        node.add(childNode);
                    }
                }
            }
        }

        return node;
    }

}

The results are:
9
    8
        7
            1
            2
        3
    6
        2
        5


text:
Q: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "card" I have a site with cards and when you click on some card you need to see the same card but with another details. But everytime I click on some card I get this massgae in the terminal:
Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "card"
Here What I wrote:
**
CardDatails.jsx**
import React, { Component } from "react";
import PageHeader from "../common/pageHeader";
import { getCard } from "../../services/cardService";

class CardDetails extends Component {
  state = {
    card: {
      adress: "",
      bizNumber: "",
      createdAt: "",
      description: "",
      image: { url: "", alt: "" },
      likes: [],
      phone: "",
      title: "",
    },
    errors: {},
    isMounted: false,
  };

  async componentDidMount() {
    try {
      const { data } = await getCard(this.props.id);
      this.setState({ card: { card: data, isMounted: true } });
    } catch (error) {
      this.setState({ errors: error.massage });
    }
  }

  render() {
    const { card } = this.state;
    const {
      title,
      description,
      image: { url, alt },
      address,
      phone,
      bizNumber,
      createdAt,
      likes,
    } = card;

    return (
      <React.Fragment>
        <PageHeader
          title={`Business Card of: ${title}`}
          subTitle={`Businness Description: ${description}`}
        />

            Tel:
            {phone}

            Address:
            {address}

            Card Number:
            {bizNumber}

            Created At:
            {createdAt}

            likes:
            {likes}

      </React.Fragment>
    );
  }
}

export default CardDetails;

App.js:
import { useParams } from "react-router-dom";
import CardDetails from "./CardDetails";

const CardDetailsConvertor = () => {
  const { id } = useParams();
  return <CardDetails id={id} />;
};

export default CardDetailsConvertor;

import HomePage from "./layout/main/Home";
import About from "./layout/main/About.jsx";
import { Routes, Route } from "react-router-dom";
import Error404 from "./layout/main/Error404";
import Header from "./layout/header/Header.jsx";
import Footer from "./layout/footer/footer.jsx";
import BizSignup from "./layout/main/BizSignup";
import Logout from "./layout/main/Logout";
import MyCards from "./layout/main/MyCards";
import MyFavoriteCards from "./layout/main/MyFavoriteCards";
import Login from "./layout/main/Login";
import Signup from "./layout/main/Signup";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { getCurrentUser } from "./services/userService";
import CreateCard from "./layout/main/CreateCard";
import EditCardConvertor from "./layout/main/editCardConvertor";
import CardDetails from "./layout/main/CardDetails";
import CardDetailsConvertor from "./layout/main/CardDetailsConvertor";

function App() {
  const user = getCurrentUser();
  return (

      <ToastContainer />

        <Routes>
          <Route path="/about" element={<About />} />
          <Route path="/biz-signup" element={<BizSignup />} />
          <Route path="/logout" element={<Logout />} />
          <Route path="/my-cards" element={<MyCards user={user} />} />
          <Route path="/create-card" element={<CreateCard user={user} />} />
          <Route
            path="/card-details-converotr"
            element={<CardDetailsConvertor user={user} />}
          />
          <Route
            path="/edit-card/:id"
            element={<EditCardConvertor user={user} />}
          />
          <Route path="/card-details/:id" element={<CardDetails />} />
          <Route
            path="/my-fav-cards"
            element={<MyFavoriteCards user={user} />}
          />
          <Route path="/login" element={<Login />} />
          <Route path="/signup" element={<Signup />} />
          <Route path="/" element={<HomePage />} />
          <Route path="*" element={<Error404 />} />
        </Routes>

  );
}

export default App;

**CardDetailsConverotr.jsx:**
import { useParams } from "react-router-dom";
import CardDetails from "./CardDetails";

const CardDetailsConvertor = () => {
  const { id } = useParams();
  return <CardDetails id={id} />;
};

export default CardDetailsConvertor;

So if you can help I will be happy
Thank you!

A: CardDetails component isn't passed any props, so this.props.id is undefined.
<Route
  path="/card-details/:id"
  element={<CardDetails />} // <-- no props are passed here
/>

You can either convert CardDetails to a functional component so it can use the useParams hook to access the id route param, or you can create a custom withRouter Higher Order Component to do this and inject the params as a prop to be accessed in component.
I won't cover conversion, but the following is a simple withRouter HOC:
import { useParams } from 'react-router-dom';

const withRouter = Component => props => {
  const params = useParams();
  return <Component {...props} params={params} />;
};

...
import React, { Component } from "react";
import PageHeader from "../common/pageHeader";
import { getCard } from "../../services/cardService";
import { withRouter } from "../path/to/withRouter";

class CardDetails extends Component {
  state = {
    ...
  };

  async componentDidMount() {
    try {
      const { data } = await getCard(this.props.params.id);
      this.setState({ card: { card: data, isMounted: true } });
    } catch (error) {
      this.setState({ errors: error.massage });
    }
  }

  render() {
    const { card } = this.state;
    const {
      title,
      description,
      image: { url, alt },
      address,
      phone,
      bizNumber,
      createdAt,
      likes,
    } = card;

    return (
      ...
    );
  }
}

export default withRouter(CardDetails);


text:
Q: DataGridTableStyle VB.Net I am using the following code to try and apply a style to my datagrid but nothing is happening, no columns are created at all, I just get a blank DataGrid:
Can someone please advise what I am doing wrong?
    adapter.Fill(ds, "dttest")

    DataGrid1.DataSource = ds.Tables("dttest")

    Dim ts As New DataGridTableStyle()
    ts.MappingName = "dttest"

    Dim column1 As New DataGridTextBoxColumn()
    column1.MappingName = "serv"
    column1.Width = 25
    column1.HeaderText = "Serv"
    ts.GridColumnStyles.Add(column1)

    Dim column2 As New DataGridTextBoxColumn()
    column2.MappingName = "op"
    column2.Width = 50
    ts.GridColumnStyles.Add(column2)

    Dim column3 As New DataGridTextBoxColumn()
    column3.MappingName = "deptime"
    column3.Width = 50
    ts.GridColumnStyles.Add(column3)

    Me.DataGrid1.TableStyles.Add(ts)

A: Doesn't look like you have called DataGrid1.DataBind().


text:
Q: Trade offs between FetchType.LAZY and FetchType.EAGER? My current understanding is FetchType.EAGER is preferred only if:

*

*the fetch strategy for the association is @Fetch(FetchMode.JOIN) or @Fetch(FetchMode.SUBSELECT), so Hibernate will make a batch query when loading the root entity.

*we want to ensure the root entity and the associated entity are loaded within the same transaction, but this can also be enforce through other mechanisms(e.g. using @Transactional).

In other cases, FetchType.LAZY always help decrease number of db requests. Is this correct?

A: *

*As for the relation between @Fetch(FetchMode.JOIN) and FetchType.LAZY, you can find in the documentation the following:

... FetchMode.JOIN is useful for when entities are fetched directly, via their identifier or natural-id.
Also, the FetchMode.JOIN acts as a FetchType.EAGER strategy. Even if we mark the association as FetchType.LAZY, the FetchMode.JOIN will load the association eagerly.

*You can find the following recommendation in this section of the documentation:

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness.
This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default.
Hibernate, as a JPA provider, honors that default.


text:
Q: jQuery UI Sortable php/mysql I have been working on a sortable list. I want to implement a sortable list like this: http://jqueryui.com/demos/sortable/#connect-lists-through-tabs
It is the ajax communication, that I'm really stuck with.
I have set up a jsfiddle, http://jsfiddle.net/pnrAx/, showing my current code. (Note, it is copy and paste with loads of junk, cleanup needed)
The fields, updating the information on each row are working fine, no problems there. The sorting also works on the screen, I can drag-n-drop items nicely.
To boil the problem down, how can I get the sorted elements from the page, with ajax (json?), into an array on a php page?
From there, it should be pretty easy to update the table.

A: what i would do is when you output then html put them into arrays like this
<input type="hidden" name="block[369][id]" value="369"/>
<input type="hidden" name="block[369][menuBolk_id]" value="55"/>
<input type="hidden" name="block[369][matstovuID]" value="39"/>
<input type="text" name="block[369][Heiti]" value="Big Burgara Matskrá" style="width: 60%; font-weight: bold; padding: 4px; line-height: 150%; font-size: 12pt; background-color: #ccc;"/>
<textarea style="width: 60%; background-color: #ccc;" name="Vorulysing"></textarea>
<div style="margin-top: -70px; padding-bottom: 70px;">
    <input type="text" name="block[369][Pris][]" value="Kr 83,-" class="price priceR" style="width: 10%;"/>
    <input type="text" name="block[369][Pris][]" value="" class="price priceC" style="width: 10%;"/>
    <input type="text" name="block[369][Pris][]" value="" class="price priceL" style="width: 10%;"/>
</div>

then when you poste you will have a post of "block" which will be a multi dimensional array
so in this instance what you want is to submit them all at once and process them in the order they are revived so the user would sort then hit a submit button and the form would submit all post data in the the order in which they have sorted them. Does that make sense ?

A: On the drop function I would call, via $.ajax, a php page and send the ID, new position, and tab/category ID of that item just dropped in the query string. Then on the new page, get the old sort position from the database and loop through all items that are between the new position and old position of the item dropped either incrementing or decrementing the position of each item.


text:
Q: Android Live wallpaper like screen wash I need your help. I need to create live wallpaper like this : Bikini girl!
If you can point me in the right direction it will be wonderful. Also, I want to know is this a video file or is it an animated gif or something else. I saw a simple tutorial for live wallpaper, but didn't find anywhere something like this. If you can give me some direction, like what I need to do first, what to use or some code it will be great.
Thanks again!!!

A: You have to work with SurfaceView and Canvas. I also suggest you to read the article on Android Developer, that is really clear to understand how to develop LiveWallpapers.
I've never worked with LiveWallpapers directly, but GIFs are only 256 colors, so it's really hard to believe that a LiveWallpaper like the one you need to create is made on a poor quality image like GIF.


text:
Q: How to use non-square roots on the Default Calculator in advanced mode without exponents? I can't seem to figure out how to input a root that isn't square in Ubuntu's default calculator. I know I can input 4^(1 / 3) but I'd prefer to input them in a more.. "natural" way.  (I can't think of a good way to put it.)
Is there a  way to work with non-square roots in the advanced mode of the calculator without using exponents?


text:
Q: php simplexml load file i have a problem of this error or how do i fix it, any help.

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0" encoding="UTF-8" ?><response><psid /><date><![CDATA[2013-06-04]]></date><name /><email /><status><![CDATA[declined]]></status><message><![CDATA[This company has not yet been approved.]]></message><price>0</price></response>"

i am using this line
$xml = simplexml_load_file($json);

A: $json should contain a file name/path. Not XML.
Use simplexml_load_string() to load an XML string.
So try this in stead:
$xml = simplexml_load_string($json);

Also naming the variable json is weird as it suggests it will contain something to do with JSON. But JSON and XML are totally different things.