text:
Q: How to connect reactJS with mysql on node.js I am trying to insert form data from reactJS to mysql database on Node.js. I am beginner in reactJS so please help me.
import React from 'react';
import Layout from './App.jsx';

class Header extends React.Component{

constructor(props) {
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
 var fname=this.refs.fname.value; //This variable holds firstname
}
render() {
  return (

      <form onSubmit={this.handleSubmit}>

Registration Form:

       First Name:
       <input type="text" ref="fname" value={this.state.fname}  />

       Last Name:
       <input type="text" ref="lname" value={this.state.lname}  />

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

);
 }
}
export default Header;

Above code is Header.jsx which renders form
The variable fname contains value which I want to insert into mysql database.

A: Well, the answer of your question may go deep into flux (or redux) architecture and talking about services, dispatching actions and so on. If you want to do it properly then you'll probably need to learn about this stuff. If you want to do it quickly then you may pass whatever you want to the component via props. For example:
var storeToDatabase = function(username) {
  // here you call a backend endpoint with some library like superagent
}

// and then in your Header.jsx component
handleSubmit(event) {
 var fname = this.refs.fname.value;

 this.props.store({ fname });
}

So, React is only about rendering views. All the other stuff should be handle outside of it.

A: It seems you are a little confused. First of all, what you want to do is to send a request to a Node.js server, which will handle the request and save it to the database. You don't connect React to MySQL.
To do this you could install a library to make the request, e.g. superagent. You import it: import request from 'superagent'. Then you should do something like this:
handleSubmit(event) {
  var fname=this.refs.fname.value; //This variable holds firstname
  request.post('/api/name').send({ name: fname }).end(callback);
}

Where callback is a function which will receive the server response and you can do whatever you want with it.
In the server, if you are for exampling using Express, you should do something like this:
app.post('/api/name', function(req, res) {
  // code for saving the name in the database
})

By the way, you don't need Redux store (which Krasimir said). This has nothing to do with Redux and application state.


text:
Q: Another failure at deserializing data with discriminated unions, in F# Following a question where the answer provided a working solution to serialize / deserialize discriminated unions (IgnoreMissingMember setting doesn't seem to work with FSharpLu.Json deserializer)
I have now a practical case where this fails (although it works in simpler cases).
here is the test code:
open System.Collections.Generic
open Microsoft.FSharpLu.Json
open Newtonsoft.Json
open Newtonsoft.Json.Serialization

// set up the serialization / deserialization based on answer from:
// https://stackoverflow.com/questions/62364229/ignoremissingmember-setting-doesnt-seem-to-work-with-fsharplu-json-deserializer/62364913#62364913

let settings =
    JsonSerializerSettings(
        NullValueHandling = NullValueHandling.Ignore,
        Converters = [| CompactUnionJsonConverter(true, true) |]
    )

let serialize object =
    JsonConvert.SerializeObject(object, settings)

let deserialize<'a> object =
    JsonConvert.DeserializeObject<'a>(object, settings)

// define the type used
type BookSide =
    | Bid
    | Ask

type BookEntry =
    {
        S : float
        P : float
    }

type BookSideData =
    Dictionary<int, BookEntry>

type BookData =
    {
        Data: Dictionary<BookSide, BookSideData>
    }

    static member empty =
        {
            Data = Dictionary<BookSide, BookSideData>(dict [ (BookSide.Bid, BookSideData()); (BookSide.Ask, BookSideData()) ])
        }

// make some sample data
let bookEntry = { S=3.; P=5. }
let bookData = BookData.empty
bookData.Data.[BookSide.Bid].Add(1, bookEntry)

// serialize. This part works
let s = serialize bookData

// deserialize. This part fails
deserialize<BookData> s

the serialized test data will look like this:

{"Data":{"Bid":{"1":{"S":3.0,"P":5.0}},"Ask":{}}}

but deserializing will crash like this:

Could not convert string 'Bid' to dictionary key type 'FSI_0023+BookSide'. Create a TypeConverter to convert from the string to the key type object.

although the serialization / deserialization of the DU through FSharpLu which has a DU converter.
The reason I am trying to find some automated solution, vs writing a custom TypeConverter (besides the fact I've never done it) is that I have a lot of types I do not control to go through.
Here is a fiddle:
https://dotnetfiddle.net/Sx0k4x

A: Your basic problem is that you are using BookSide as a dictionary key -- but this is an f# union which makes it a complex key -- one not immediately convertible to and from a string.  Unfortunately Json.NET does not support complex dictionary keys out of the box as is stated in its Serialization Guide:

When serializing a dictionary, the keys of the dictionary are converted to strings and used as the JSON object property names. The string written for a key can be customized by either overriding ToString() for the key type or by implementing a TypeConverter. A TypeConverter will also support converting a custom string back again when deserializing a dictionary.

There are two basic approaches to handling this issue:

*

*Implement a TypeConverter as is shown in, e.g., Not ableTo Serialize Dictionary with Complex key using Json.net.

*Serialize the dictionary as an array of key/value pair objects e.g. as is shown in Serialize dictionary as array (of key value pairs).
Since your data model includes dictionaries with a variety of keys (DU, strings and ints) the second solution would appear to be the only possibility.  The following DictionaryConverter should have the necessary logic:
let inline isNull (x:^T when ^T : not struct) = obj.ReferenceEquals (x, null)

type Type with
    member t.BaseTypesAndSelf() =
        t |> Seq.unfold (fun state -> if isNull state then None else Some(state, state.BaseType))
    member t.DictionaryKeyValueTypes() =
        t.BaseTypesAndSelf()
            |> Seq.filter (fun i -> i.IsGenericType && i.GetGenericTypeDefinition() = typedefof<Dictionary<_,_>>)
            |> Seq.map (fun i -> i.GetGenericArguments())

type JsonReader with
    member r.ReadAndAssert() =
        if not (r.Read()) then raise (JsonReaderException("Unexpected end of JSON stream."))
        r
    member r.MoveToContentAndAssert() =
        if r.TokenType = JsonToken.None then r.ReadAndAssert() |> ignore
        while r.TokenType = JsonToken.Comment do r.ReadAndAssert() |> ignore
        r

type internal DictionaryReadOnlySurrogate<'TKey, 'TValue>(i : IDictionary<'TKey, 'TValue>) =
    interface IReadOnlyDictionary<'TKey, 'TValue> with
        member this.ContainsKey(key) = i.ContainsKey(key)
        member this.TryGetValue(key, value) = i.TryGetValue(key, &value)
        member this.Item with get(index) = i.[index]
        member this.Keys = i.Keys :> IEnumerable<'TKey>
        member this.Values = i.Values :> IEnumerable<'TValue>
        member this.Count = i.Count
        member this.GetEnumerator() = i.GetEnumerator()
        member this.GetEnumerator() = i.GetEnumerator() :> IEnumerator

type DictionaryConverter () =
    // ReadJson adapted from this answer https://stackoverflow.com/a/28633769/3744182
    // To https://stackoverflow.com/questions/28451990/newtonsoft-json-deserialize-dictionary-as-key-value-list-from-datacontractjsonse
    // By https://stackoverflow.com/users/3744182/dbc
    inherit JsonConverter()

    override this.CanConvert(t) = (t.DictionaryKeyValueTypes().Count() = 1) // If ever implemented for IReadOnlyDictionary<'TKey, 'TValue> then reject DictionaryReadOnlySurrogate<'TKey, 'TValue>

    member private this.ReadJsonGeneric<'TKey, 'TValue> (reader : JsonReader, t : Type, existingValue : obj, serializer : JsonSerializer) : obj =
        let contract = serializer.ContractResolver.ResolveContract(t)
        let dict = if (existingValue :? IDictionary<'TKey, 'TValue>) then existingValue :?> IDictionary<'TKey, 'TValue> else contract.DefaultCreator.Invoke() :?> IDictionary<'TKey, 'TValue>
        match reader.MoveToContentAndAssert().TokenType with
        | JsonToken.StartArray ->
            let l = serializer.Deserialize<List<KeyValuePair<'TKey, 'TValue>>>(reader)
            for p in l do dict.Add(p)
            dict :> obj
        | JsonToken.StartObject ->
            serializer.Populate(reader, dict)
            dict :> obj
        | JsonToken.Null -> null // Or throw an exception if you prefer
        | _ -> raise (JsonSerializationException(String.Format("Unexpected token {0}", reader.TokenType)))

    override this.ReadJson(reader, t, existingValue, serializer) =
        let keyValueTypes = t.DictionaryKeyValueTypes().Single(); // Throws an exception if not exactly one.
        let m = typeof<DictionaryConverter>.GetMethod("ReadJsonGeneric", BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Public);
        m.MakeGenericMethod(keyValueTypes).Invoke(this, [| reader; t; existingValue; serializer |])

    member private this.WriteJsonGeneric<'TKey, 'TValue> (writer : JsonWriter, value : obj, serializer : JsonSerializer) =
        let dict = value :?> IDictionary<'TKey, 'TValue>
        let keyContract = serializer.ContractResolver.ResolveContract(typeof<'Key>)
        // Wrap the value in an enumerator or read-only surrogate to prevent infinite recursion.
        match keyContract with
        | :? JsonPrimitiveContract -> serializer.Serialize(writer, new DictionaryReadOnlySurrogate<'TKey, 'TValue>(dict))
        | _ -> serializer.Serialize(writer, seq { yield! dict })
        ()

    override this.WriteJson(writer, value, serializer) =
        let keyValueTypes = value.GetType().DictionaryKeyValueTypes().Single(); // Throws an exception if not exactly one.
        let m = typeof<DictionaryConverter>.GetMethod("WriteJsonGeneric", BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Public);
        m.MakeGenericMethod(keyValueTypes).Invoke(this, [| writer; value; serializer |])
        ()

Which you would add to settings as follows:
let settings =
    JsonSerializerSettings(
        NullValueHandling = NullValueHandling.Ignore,
        Converters = [| CompactUnionJsonConverter(true, true); DictionaryConverter() |]
    )

And generates the following JSON for your bookData:
{
  "Data": [
    {
      "Key": "Bid",
      "Value": [
        {
          "Key": 1,
          "Value": {
            "S": 3.0,
            "P": 5.0
          }
        }
      ]
    },
    {
      "Key": "Ask",
      "Value": []
    }
  ]
}

Notes:

*

*The converter works for all Dictionary<TKey, TValue> types (and subtypes).

*The converter detects whether the dictionary keys will be serialized using a primitive contract, and if so, serializes the dictionary compactly as a JSON object.  If not the dictionary is serialized as an array.  You can observe this in the JSON shown above: the Dictionary<BookSide, BookSideData> dictionary is serialized as a JSON array, and the Dictionary<int, BookEntry> dictionary is serialized as a JSON object.
During deserialization the converter detects whether the incoming JSON value is an array or object, and adapts as required.

*The converter is only implemented for the mutable .Net Dictionary<TKey, TValue> type.  The logic would require some slight modification to deserialize the immutable Map<'Key,'Value> type.
Demo fiddle here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play Framework return result from Twitter Future I have a next code, this return true, when number is 0, otherwise exception
  import com.twitter.util.Future

  def compute(x: Int): Future[Boolean] = {
     if (x == 0) {
       Future.value(true)
     } else {
       Future.value(new Exception("Invalid number"))
     }
  }

And my controller for work with this code:
 object MyController extends Controller {

   def get(x: Int) = Actrion {
     compute(x).flatMap {
       case x: Boolean => Ok(views.html.ok("ok"))
       case _ => NotFound
     }
   }
 }

but when i run this code, i get type mismatch;
 found   : play.api.mvc.Result
 required: com.twitter.util.Future[?]
How to extract value from Future and pass as result to response?

A: Play uses Scala futures, not Twitter futures. If you have to use the Twitter future, you have to convert it. The following code is taken from an Akka feature request:
import scala.concurrent.{Future, Promise}
import com.twitter.util.{Future => TwitterFuture, Throw, Return}

def fromTwitter[A](twitterFuture: TwitterFuture[A]): Future[A] = {
  val promise = Promise[A]()
  twitterFuture respond {
    case Return(a) => promise success a
    case Throw(e) => promise failure e
  }
  promise.future
}

Then use it in your controller:
object MyController extends Controller {true
  def get(x: Int) = Action.async {
    fromTwitter(compute(x)).map { _ =>
      Ok(views.html.ok("ok"))
    }.recover { case e =>
      NotFound
    }
  }
}

Your case statement also doesn't make sense, a Future typed to Boolean will always result in Boolean. If the future fails, you can use recover, recoverWith, or fallbackTo.

A: According to Future doc error is caused simply because of flatMap definition. I would rather use map or poll method.
Moreover, I suggest using scala.concurrent.Future with Action.async like this:
def index = Action.async {
  val futureInt = scala.concurrent.Future { intensiveComputation() }
  futureInt.map(i => Ok("Got result: " + i))
}

More info can be found here


text:
Q: How to change css class for multiple DOM elements with jQuery? I am trying to change class property of an DOM element (specifically, for label tag) using jQuery 1.10.2.
Here is my code:

var MyNameSpace = MyNameSpace || {};
MyNameSpace.enableDisableLabels = (function() {
  var m_labelIds = {
    "bookId": "book",
    "customerId": "customer"
  };

  var mf_getjQueryDOMObjectReperesentation = function(arrayObjIds) {
    var result = {};
    $.each(arrayObjIds, function(id, value) {
      result[id] = $("#" + value);
    });
    return result;
  };

  var mf_unBoldLabels = function(arrayjQueryObjLabels) {
    $.each(arrayjQueryObjLabels, function(id, value) {
      value.atrr("class", "outputLabelOpt"); // PROBLEM: TypeError: value.atrr is not a function
    });
  };

  var arrayjQueryObjLabels = mf_getjQueryDOMObjectReperesentation(m_labelIds);
  mf_unBoldLabels(arrayjQueryObjLabels);

}());
.outputLabelOpt {
  color: #0B63CA;
}

  book
  customer

But I get an error:
TypeError: value.atrr is not a function
Can you please advise what am I doing wrong and how to do it correctly.
Any kind of help is very much appreciated.
Thank you in advance,
mismas

A: Just a typo : it is not atrr, but attr ;-)

A: This is value.attr not .atrr.
For class attribute manipulation, you also have .addClass("classname") and .removeClass("classname").


text:
Q: No response from sending a POST request via jQuery? I'm experimenting a bit with jQuery
<html>
<head>
<title>post test</title>

<script src="jquery-3.2.1.min.js"></script>

<script>

$.post('http://lab.anta40.net/dummy/login.php',
      {
        'username': 'John Doe',
        'password': 'hello123'
      },

      function (response, status) {
        alert(response.status);
      }
    );

</script>
</head>

<body>
test...
</body>
</html>

My intention is the page will display an alert box which contains the response of the POST request. Running the code on Chrome 61 doesn't yield anything. No alert box at all. What is wrong here?


text:
Q: Elegant Numpy ways to implement this matrix operation I'm looking to vectorize the following equation:

Where x represents an N x T list of observations, and gamma is an N x K matrix. The intended output, theta, is a K x T matrix. Of course, I have a naive implementation that works by just looping through the elements and setting the array manually, but I just know there's a much cleaner solution lurking out here somewhere.
Below is my naive implementation, however it is much too slow for my purposes.
    theta = np.zeros((K, T))
    for k in range(K):
        numerator = np.zeros((T,))
        denominator = 0
        for i in range(N):
            gamma_ik = r[i,k]
            numerator = numerator + gamma_ik * x[i]
            denominator = denominator + gamma_ik
        theta[k] = numerator / denominator

A: Slightly more explicit answer that may be easier to follow. Again, the key function call is numpy.matmul.
import numpy as np

# dimensions N, T, K
N = 2
T = 3
K = 4

x = np.cumsum(np.ones([N,T]), axis = 0)
#[[1. 1. 1.]
#[2. 2. 2.]]

gamma = np.cumsum(np.ones([K,N]), axis = 0)
#[[1. 1.]
# [2. 2.]
# [3. 3.]
# [4. 4.]]

y = np.matmul(gamma, x) # numerator
#[[ 3.  3.  3.]
# [ 6.  6.  6.]
# [ 9.  9.  9.]
# [12. 12. 12.]]

# denominator
sumgamma = np.matmul(gamma, np.ones(N))
#[2. 4. 6. 8.]

theta = y / sumgamma[:,None]
#[[1.5 1.5 1.5]
# [1.5 1.5 1.5]
# [1.5 1.5 1.5]
# [1.5 1.5 1.5]]

A: The other answers are both correct. I just wanted to add that we could also sum on axis and keepdims to keep the sum as a column vector.
Reusing @ramzeek's input (note that gamma is already transposed from construction in their example; here I use the original dimension):
N = 2
T = 3
K = 4

X = np.cumsum(np.ones((N,T)), axis = 0)
gamma = np.cumsum(np.ones((N,K)), axis = 0)

where X is an NxT matrix and gamma is an NxK matrix. Then np.matmul(gamma.T, X) creates the numerator (of dimension (NxK)' x (NxT) = KxT ) and gamma.T.sum(axis=1, keepdims=True) creates the denominator (of dimension sum^N(NxK)' = Kx1 ).
You can also use np.divide to element-wise divide as well:
theta = np.divide(np.matmul(gamma.T, X), gamma.T.sum(axis=1, keepdims=True))

then theta's dimension: (KxT / Kx1 = KxT)
Output:
array([[1.66666667, 1.66666667, 1.66666667],
       [1.66666667, 1.66666667, 1.66666667],
       [1.66666667, 1.66666667, 1.66666667],
       [1.66666667, 1.66666667, 1.66666667]])


text:
Q: How to run flutter app for development on ios device without a paid developer account? Following flutter's setup instructions, I tried to run the app on my iphone. I got into signing problems. In the project settings, under general/signing, I have this error message:

Failed to create provisioning profile. There are no devices registered
  in your account on the developer profile. Plug in and select a device
  to have Xcode register it.

I couldn't do anything in my developer profile, as there was only a message saying my account is expired. I only want to test my app for development, which I should be able to do without renewing the expensive apple developer program.

A: This is the solution that worked for me:

*

*Contact apple and have them removed from the expired team

*Create a personal team for your apple id. But it might not work to trust the computer yet! (as in olexa.le's comment https://www.oodlestechnologies.com/blogs/Deploying-Apps-to-Devices-without-an-Apple-Developer-Account)

*Plug in the iOS device and make sure it's detected on the Mac computer (for me it opened itunes and the device name was visible in xcode)

*Under signing, where the error message (Failed to create provisioning profile. There are no devices...) was: click try again

*Instead of the error message there was a message saying the device is signed.

*Now you can trust the computer from the device General/Profiles and device managment (again as in https://www.oodlestechnologies.com/blogs/Deploying-Apps-to-Devices-without-an-Apple-Developer-Account)

*It didn't work to use "flutter run" as the flutter documentation says. It worked however to open the project in xcode, and then from xcode's menu project/run.

*Make sure the screen is not locked after the build is complete (it took me more than 5 minutes to build this project when no changes had been made since last build)


text:
Q: playwright javascript wait for link to be bold Im currently facing a problem using playwright where I need to click a link, and then wait for it to turn bold. I can find the element itself and click it using:
await page.click("a[id$='clickablelink_0']")

and I am currently waiting for to change when I see a class (which adds bold) added to the element:
await page.waitForSelector("a[id$='clickablelink_0'][class~=xmp]")

However this class name is changing every so often. Is there a way instead of using the class, look directly for the value of "font-weight"? ideally as a ">=" to a value?
Just some notes:

*

*I cant change any code generating this page

*I have looked for other ways to determine this was clicked, but the other ways are less deterministic

*its a private page and unfortantly can not sure it out

Thanks!

A: In case of asserting a css property you can use the expect toHaveCSS() assertion for this. You can play around with the timeout as well, by default expect assertions have a 5 second timeout. Now you can increase the timeout for specific assertions as shown below or globally as well.
await expect(page.locator("a[id$='clickablelink_0'][class~=xmp]")).toHaveCSS(
  'font-weight',
  '30px',
  {timeout: 7000}
)

Or, if you want to extract the value of font-weight and then apply an assertion for greater than, you can do like this:
const element = await page.waitForSelector(
  "a[id$='clickablelink_0'][class~=xmp]"
)
const fontWeight = await element.evaluate((el) => {
  return window.getComputedStyle(el).getPropertyValue('font-weight')
})
//extracting and converting number
expect(+fontWeight.replace(/\D/g, '')).toBeGreaterThan(30)


text:
Q: Code to generate excel sheet hanging when run (using PHPEXCEL) I have the following code that is supposed to generate an excel sheet for me using PHPExcel but the problem is that it takes forever to run. I also have some Doctrine PHP code. The Doctrine code connects to the db and picks the data that I want to use to populate the Excel File. Below is the code. Please could someone tell me what is wrong

/** Error reporting */
error_reporting(E_ALL);

if (!isset($_SESSION)) {
 // session_name("mediapp123456");
  session_start();
}

require_once ('bootstrap.php');
$conn = Doctrine_Manager::connection ( DSN );

$q = Doctrine_Query::create()
    ->select('u.*')
    ->from('UserQuestionnaire u')
    ->orderBy('u.id DESC');
$row = $q->execute();

date_default_timezone_set('Europe/London');

/** PHPExcel */
require_once 'excelreports/Classes/PHPExcel.php';

// Create new PHPExcel object
echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();

// Set properties
echo date('H:i:s') . " Set properties\n";
$objPHPExcel->getProperties()->setCreator("Ifeanyi Agu")
                             ->setLastModifiedBy("Ifeanyi Agu")
                             ->setTitle("QUSER")
                             ->setSubject("QUSER")
                             ->setDescription("QUser Generated Document")
                             ->setKeywords("xml")
                             ->setCategory("Test result file");

// Add some data
echo date('H:i:s') . " Add some data\n";

$objPHPExcel->getActiveSheet()->mergeCells('B2:F2')
                                ->mergeCells('G2:K2')
                            ->setCellValue('I2', 'FEATURES')
                                ->mergeCells('L2:AI2')
                                ->setCellValue('W2', 'EXPECTATION')
                                ->mergeCells('AJ2:BG2')
                                ->setCellValue('AU2', 'PERCEPTION')
                                ->mergeCells('L3:03')
                                ->setCellValue('M', 'Tangible');

$objPHPExcel->getActiveSheet()->setCellValue('A4', 'No')
->setCellValue('B4', 'School')
->setCellValue('C4', 'Dept')
->setCellValue('D4', 'Status')
->setCellValue('E4', 'Browse')
->setCellValue('F4', 'How Long')
->setCellValue('G4', 'Tangibility')
->setCellValue('H4', 'Reliability')
->setCellValue('I4', 'Assurance')
->setCellValue('J4', 'Responsive')
->setCellValue('K4', 'Empathy')
->setCellValue('L4', 'E1')
->setCellValue('M4', 'E2')
->setCellValue('N4', 'E3')
->setCellValue('O4', 'E4')
->setCellValue('P4', 'E5')
->setCellValue('Q4', 'E6')
->setCellValue('R4', 'E7')
->setCellValue('S4', 'E8');

$i=4;
foreach($row as $rows)
{
$i++;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, ($i-4))
                                ->setCellValue('B'.$i, $rows->schoolname)
                                ->setCellValue('C'.$i, $rows->department)
                                ->setCellValue('D'.$i, $rows->status)
                                ->setCellValue('E'.$i, $rows->doyoubrowse)
                                ->setCellValue('F'.$i, $rows->browselength);

}

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', FILE));

// Echo memory peak usage
echo date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";

// Echo done
echo date('H:i:s') . " Done writing file.\r\n";

?>

A: Obvious possibilities:
->mergeCells('L3:03')

suspect this should be O3 (column letter O, row three) rather than 03 (numeric zero three)
->setCellValue('M', 'Tangible');

may be the cause of some problems 'M' is a column reference rather than a cell reference
When merging and then setting a value for the merged cells, it's better to set the top-left cell of the merge range rather than a cell for the middle of the range. e.g.
->mergeCells('G2:K2')
->setCellValue('G2', 'FEATURES')

rather than
->mergeCells('G2:K2')
->setCellValue('I2', 'FEATURES')


text:
Q: DoubleList with template C++ I'm trying to code my DoubleList with head and tail, but during the compilation the compiler shows error:

error C2664: 'doubleList::addFirst' : cannot convert parameter 1
  from 'const char [4]' to 'std::string &'

Can someone help me?
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;

template<typename T>
class node{
private:
    T field;
    node* previous;
    node* next;
public:
    node(){
        previous = NULL;
        next = NULL;
    }

    node(T& name){
        field = name;
        previous = NULL;
        next = NULL;
    }
};

template<typename T>
class doubleList{
private:
    node<T>* head;
    node<T>* tail;
public:
    doubleList(){
        head = new node<T>;
        tail = new node<T>;
    }
    void addFirst(T& name){
        node<T> *newNode = new node<T>(name);
        if (head->next != NULL){
            nowy->next = head->next;
            (nowy -> next) -> previous = nowy;
        }
        head -> next = nowy;
        nowy->previous = head;
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    doubleList <string> *train = new doubleList<string>;
    train->addFirst("Ala");

    system("pause");
    return 0;
}

A: The constructor, and also addFirst, take their argument by non-const lvalue reference, which means that it can only be called with an lvalue of the correct type - string in this case. You're trying to call it with a temporary rvalue constructed from a different type.
Change them to take their argument by value, const, or forwarding reference, and passing a temporary will be allowed:
node(T name)          // value
node(T const & name)  // const reference
node(T && name)       // forwarding reference

A: You're attempting to pass a const char* to a method that takes a reference to a std::string. The compiler is not performing an implicit type cast and therefore complains about a type mismatch.
Overload the addFirst method with another one that takes a const char*, explicitly casts the const char* to a std::string, and then passes it to your existing addFirst method.
Edit: Mike Seymour's answer is better than mine. This const reference example seems like it would be the best option in your case.


text:
Q: Why cannot superset connect to Athena using PyAthena and rest scheme and throws HTTP 422 "unexpected error"? Installing Superset with docker-compose. App is up and running. When adding a new database using PyAthena connector, error Unexpected error occurred, please check your logs for details happens with no details in the logs.

A: First, if you are using docker-compose, check whether you have added driver to the build environment.
echo "PyAthena>1.2.0" >> ./docker/requirements-local.txt

If you don't you will get Driver not found error.
Second, check your URI scheme. It must be of the following form:
awsathena+rest://AKIAXXXX:XXXXXX@athena.{region}.amazonaws.com/{database_name}?s3_staging_dir=s3://{bucket_name_for_results}

If you are missing the query string part you may get mysterious error without a detail reason.
Also note that PyAthena does not check you AK/SK against the staging bucket.


text:
Q: Is half the log loss, twice as good? Lets say I have two different models based on the same dataset.

*

*Model A has a log loss of 0.30 on this dataset.

*Model B has a log loss of 0.60 on this dataset.

If our scoring metric is log loss, is it correct to say that Model A is twice as good as Model B? I guess I'm just not sure what scale log loss is based on (linear, logarithmic, something more exotic, etc.).


text:
Q: Can not restore my site collection .No content databases in the web application were available to store your site collection. I want to change the URL of my team site collection, to do so i have back-up the site collection from inside the old URL,  and i want to restore it to the new URL. so i did the following:-
-i create a new site collection on the root of my web application . http://gvsps01:80
-i back-up my current team site from the old URL.
-when i tried to restore the site collection to the new URL i got the following error:-
Restore-spsite : The operation that you are attempting to perform cannot be
completed successfully.  No content databases in the web application were
available to store your site collection.  The existing content databases may
have reached the maximum number of site collections, or be set to read-only,
or be offline, or may already contain a copy of this site collection.  Create
another content database for the Web application and then try the operation
again.
At line:1 char:1
+ Restore-spsite -identity http://gvsps01:80   -path c:\root\i -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (Microsoft.Share...dletRestoreSite:
   SPCmdletRestoreSite) [Restore-SPSite], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletRestoreS
   ite

so can anyone advice please, as all the articles which is talking about this error, is related to if someone delete a site collection from the same URL and try to restore it, while in my case there was not any previouse site collection on the http://gvsps01:80?

A: after all, what i did is; 1)back-up the old site collection, 2)delete the old site collection using CA UI, 3)use the following Remove-SPDeletedSite –Identity ... to remove the site collection permanently 4) run the delete job 5) wait for a while . restore agian and it worked !!!!!


text:
Q: Optimize Angular vendor output In trying to optimize the vendor bundle when building with webpack, I'm using the NgcWebpackPlugin.
This is the vendor bundle visually presented:

What surprises me is the presence of the angular compiler module even tho we are utilizing AOT.
Do I need to somehow explicitly declare that I don't need the compiler in the bundle? Or am I missing something else?

Here's the vendor.ts:
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';
import '@angular/forms'
import '@angular/animations'
import 'rxjs';
import '@ngrx/core';
import '@ngrx/store';
import 'platform';
import 'underscore';
import 'typed-immutable-record';
import 'toastr';
import 'socket.io-client';
import 'moment';
import 'moment-timezone';
import 'jquery';
import 'immutable';
import 'humanize-duration';
import 'fuzzy';
import 'bricklayer';
import 'ngx-bootstrap';

Here's the boot-aot.ts:
/**
 * Angular bootstrapping
 */
import { platformBrowser } from '@angular/platform-browser';
import { decorateModuleRef } from './environment';
/**
 * App Module
 * our top level module that holds all of our components.
 */
import { AppModuleNgFactory } from '../../compiled/app/src/app.module.ngfactory';
/**
 * Bootstrap our Angular app with a top level NgModule.
 */
export function main(): Promise<any> {
  return platformBrowser()
    .bootstrapModuleFactory(AppModuleNgFactory)
    .then(decorateModuleRef)
    .catch((err) => console.error(err));
}

export function bootstrapDomReady() {
  document.addEventListener('DOMContentLoaded', main);
}

bootstrapDomReady();

A: In vendor.ts remove import 'platform-browser-dynamic' and in your webpack config manually remove unneeded modules.
Sample webpack config:
var empty = {
    NgProbeToken: {},
    HmrState: function() {},
    _createConditionalRootRenderer: function(rootRenderer, extraTokens,
coreTokens) {
      return rootRenderer;
    },
    __platform_browser_private__: {}
  };

return {
    module: {
      rules: [
        ({
          test: /\.ts$/,
          use: removeEmpty([
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: isDev,
                prod: isProd
              }
            },
            {
              /**
               *  MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION
OUTPUT.
               */
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: isProd
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json',
                useCache: !isProd
              }
            },
            ifProd(WebpackStrip.loader('console.log', 'console.info',
'console.error')),
            {
              loader: 'angular2-template-loader'
            }
          ]),
          exclude: [/\.(spec|e2e)\.ts$/]
        })
      ]
    },
    plugins: [
    new ngcWebpack.NgcWebpackPlugin({
      disabled: !isProd,
      tsConfig: resolve('tsconfig.webpack.json')
    }),

    new NormalModuleReplacementPlugin(
      /zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
      empty
    ),

    new HashedModuleIdsPlugin(),

     new NormalModuleReplacementPlugin(
       /@angular(\\|\/)upgrade/,
       empty
     ),
     new NormalModuleReplacementPlugin(
       /@angular(\\|\/)compiler/,
       empty
     ),
     new NormalModuleReplacementPlugin(
       /@angular(\\|\/)platform-browser-dynamic/,
       empty
     ),
     new NormalModuleReplacementPlugin(
       /dom(\\|\/)debug(\\|\/)ng_probe/,
       empty
     ),
     new NormalModuleReplacementPlugin(
       /dom(\\|\/)debug(\\|\/)by/,
       empty
     ),
     new NormalModuleReplacementPlugin(
       /src(\\|\/)debug(\\|\/)debug_node/,
       empty
     ),
     new NormalModuleReplacementPlugin(
       /src(\\|\/)debug(\\|\/)debug_renderer/,
       empty
     )
  ]
};


text:
Q: Load textfiles to android app - Out of memory despite not heavy files I cannot, by now, understand why I got an out-of-memory exception when I load 9 different textfiles into my android app. The total size of the textfiles is about 10 MB. And I hade to change to large-heapsize in the manifest file to be able to load these files. Its not a good solution, so I wonder if someone could help me to understand what causes the heapsize to rize over 100 MB.
Another thing, could be a clue of something??, is that when heapsize has climed a bit over 100 MB and allocated memory is sligtly below - all loading is done, something happends:
The garbagecollector makes something immediately when loading is finished - the allocated space falls dramatically from 100 MB to 35 MB.
SO I wonder - what is happening? Why is the loading so memory consuming?
I can say that I have a class called FileManager where all loading taking place.
And because FileManager do not extend Activity, I have to pass a context to this class.
Could it be the context that is memory consuming? I think It may be and I have to move the loading when the app starts app at first.
Here is the FileManager-class
 public class FileManager {

private String[][] solarObj,, celestObj, stars, sun, moon, venus, march, jupiter, saturn;
private ArrayList <String[][]> stringObjects = new ArrayList <String[][]> () ;
private String[] textFile;
private Context context;
private AssetManager assetManager;

public FileManager(Context context) {

    this.context = context;
    assetManager = context.getResources().getAssets();
    instanciateStrings();

    putStringsToList();

    initializeTextFile();

    for (int array_index = 0; array_index < 9; array_index++) {

        read(this.textFile[array_index], this.stringObjects.get(array_index).length, array_index);
        //printString(array_index);
    }
}

    private void instanciateStrings() {

    this.solarObj = new String[98][4];
    this.celestObj = new String[7][3];
    this.stars = new String[92][7];
    this.sun = new String[14246][15];
    this.moon = new String[14246][15];
    this.venus = new String[14246][15];
    this.march = new String[14246][15];
    this.jupiter = new String[14246][15];
    this.saturn = new String[14246][15];
}

/**
 * Lägger in de tvådimensionella strängvektorerna i en arraylist.
 */
private void putStringsToList() {

    this.stringObjects.add(this.celestObj);
    this.stringObjects.add(this.solarObj);
    this.stringObjects.add(this.stars);
    this.stringObjects.add(this.sun);
    this.stringObjects.add(this.moon);
    this.stringObjects.add(this.venus);
    this.stringObjects.add(this.march);
    this.stringObjects.add(this.jupiter);
    this.stringObjects.add(this.saturn);
}

/**
 * Filnamnen läses in i en strängvektor
 */
private void initializeTextFile() {

    this.textFile = new String[9];

    this.textFile[0] = "celestobj_txt.txt";
    this.textFile[1] = "solarObj_txt.txt";
    this.textFile[2] = "stars_txt.txt";
    this.textFile[3] = "sun_txt.txt";
    this.textFile[4] = "moon_txt.txt";
    this.textFile[5] = "venus_txt.txt";
    this.textFile[6] = "march_txt.txt";
    this.textFile[7] = "jupiter_txt.txt";
    this.textFile[8] = "saturn_txt.txt";
}

    private void read(String text_file, int len, int index) {

    String[] stringBuffer = new String[len]; // temporär textsträng som read-objektet returnerar textraden till.

    BufferedReader br;

    try {
        InputStream input = assetManager.open(text_file);
        br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        //bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(text_file)));
        String line;
        int i = 0;
        while ( (line = br.readLine()) != null) {
            stringBuffer[i] = line; // läs in rader från textfilen
            i++;
        }
        br.close();

    } catch (FileNotFoundException fnde) {
        //fnde.printStackTrace();
        System.out.println("filerna kunde inte hittas");
    } catch (Exception e) {
        e.printStackTrace();
    }

    splitString(stringBuffer, index);
}

private void splitString(String[] str, int index) {

    int nCols = this.stringObjects.get(index)[0].length; // antal kolumner
    for (int i = 0; i < str.length; i++) {

        StringTokenizer st = new StringTokenizer(str[i]);

        for (int j = 0; j < nCols; j++) {

            this.stringObjects.get(index)[i][j] = st.nextToken();
        }
    }
}

since its 9 files that is to be loaded this read-method are called 9 times. Could this be the source to te memory leak?
Greatful for answer
EDIT: I choosed to show the whole class. Thanks again!!!

A: I think it's because of the String[] you are using to store read lines. Can you try it with a StringBuilder instead of String[] ?
// stringBuffer[i] = line;
stringBuilder.append(line);


text:
Q: jQuery : select all element with custom attribute
Possible Duplicate:
jQuery, Select by attribute value, adding new attribute
jQuery - How to select by attribute

please consider this code:

11111111111111

2222222222

33333333333

>4444444444

how I can select All p tag with attribute MyTag?
thanks

A: Use the "has attribute" selector:
$('p[MyTag]')

Or to select one where that attribute has a specific value:
$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

A: As described by the link I've given in comment, this
$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "
");});

works (playable example).


text:
Q: R: Reorganise 2D list of dataframes into one dataframe This is possibly a simple question, but most of my R experience is with dataframes and dplyr. I have list of lists, where the inner list contains one 'information' dataframe and one 'results' dataframe (see example below).
# Sample code for my data structure
data <- list(
  list(data.frame(subject = "A", year = 2016),
       data.frame(results = c(1, 2, 3), time = c(4, 5, 6))
  ),
  list(data.frame(subject = "B", year = 2017),
       data.frame(results = c(7, 8, 9), time = c(10, 11, 12))
  )
)

While this has been great for analysing data in inner lists, I've struggled  to do 'cross-list' analysis. What I'm trying to do is reshape my data as shown below.
# Dataframes in lists in lists (current)
    [[1]]
    [[1]][[1]]
      subject year
    1       A 2016
    [[1]][[2]]
      results time
    1       1    4
    2       2    5
    3       3    6
    [[2]]
    [[2]][[1]]
      subject year
    1       B 2017
    [[2]][[2]]

# Single dataframe (goal)
      subject year results time
    1       A 2016       1    4
    2       A 2016       2    5
    3       A 2016       3    6
    4       B 2017       7   10
    5       B 2017       8   11
    6       B 2017       9   12

I've searched online already, but most of the solutions are of a single list of dataframes not lists of lists.
My best effort so far is using for loops (see below), but as my actual data is much larger (both rows and columns) I'm trying to work out a more efficient solution.
df = data.frame()
for (i in (1:length(data))) {
  df = rbind(df,
             cbind(data[[i]][[1]], data[[i]][[2]]))
}

Cheers!

A: Since you are familiar with dplyr, try this:
bind_rows(lapply(data,function(i)do.call(cbind,i)))

PS. I found bind_cols does not work well. Maybe it is a little bug?

A: Might be:
do.call(rbind, lapply(1:length(data),
                      function(i) do.call(cbind, data[[i]])
                      )
        )

A: package:data.table does this well with rbindlist(..., fill = TRUE). Just convert back to data.frame when you're done.


text:
Q: Selenium error on Win7 I'm starting Selenium server with the following on a command line:
java -jar selenium-server.jar

Here is the code:
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;

import org.openqa.selenium.server.SeleniumServer;

import junit.framework.*;

public class orkut extends SeleneseTestCase {
    public void setUp() throws Exception {
        //SeleniumServer server = new SeleniumServer();
        //server.start();

        setUp("https://www.google.com/", "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
    }

    public void testOrkut() throws Exception {
        selenium.setTimeout("10000");
        selenium.open("/accounts/ServiceLogin?service=orkut&hl=en-US&rm=false&continue=http%3A%2F%2Fwww.orkut.com%2FRedirLogin%3Fmsg%3D0&cd=IN&skipvpage=true&sendvemail=false");
        selenium.type("Email", "username");
        selenium.type("Passwd", "password");
        selenium.click("signIn");
        selenium.selectFrame("orkutFrame");
        selenium.click("link=Communities");
        selenium.waitForPageToLoad("10000");
        }

    public static Test suite() {
        return new TestSuite(orkut.class);
        }

    public void tearDown(){
        selenium.stop();
    }

    public static void main(String args[]) {
        junit.textui.TestRunner.run(suite());
    }
}

Here is the error:
.E
Time: 33.386
There was 1 error:
1) testOrkut(orkut)java.lang.RuntimeException: Could not start Selenium session:     Failed to start new browser session: Unable to delete file     C:\Users\user\AppData\Local\Temp\customProfileDir78cf02e3efca4772a71525c4a7523cac\parent.lock
at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:89)
at com.thoughtworks.selenium.SeleneseTestBase.setUp(SeleneseTestBase.java:123)
at com.thoughtworks.selenium.SeleneseTestBase.setUp(SeleneseTestBase.java:104)
at com.thoughtworks.selenium.SeleneseTestCase.setUp(SeleneseTestCase.java:78)
at orkut.setUp(orkut.java:14)
at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
at orkut.main(orkut.java:37)
Caused by: com.thoughtworks.selenium.SeleniumException: Failed to start new browser session: Unable to delete file C:\Users\M022534\AppData\Local\Temp\customProfileDir78cf02e3efca4772a71525c4a7523cac\parent.lock
at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:262)
at com.thoughtworks.selenium.HttpCommandProcessor.start(HttpCommandProcessor.java:223)
at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:81)
... 16 more

FAILURES!!!
Tests run: 1,  Failures: 0,  Errors: 1

On the advise of answerers - I've modified the code to this:
package file;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.server.SeleniumServer;
public class Reset extends SeleneseTestCase {
private SeleniumServer seleniumServer;

private Selenium selenium = new DefaultSelenium("localhost", 4444,
        "*chrome", "http://");

public void setUp() throws Exception {
    seleniumServer = new SeleniumServer();
    seleniumServer.start();
    selenium.start();
}

// Test methods shd go here
public void tearDown() throws Exception {
    selenium.stop();
    seleniumServer.stop();
}

public void testOrkut() throws Exception {
    selenium.setTimeout("10000");
    selenium.open("/accounts/ServiceLogin?service=orkut&hl=en-US&rm=false&continue=http%3A%2F%2Fwww.orkut.com%2FRedirLogin%3Fmsg%3D0&cd=IN&skipvpage=true&sendvemail=false");
    selenium.type("Email", "username");
    selenium.type("Passwd", "password");
    selenium.click("signIn");
    selenium.selectFrame("orkutFrame");
    selenium.click("link=Communities");
    selenium.waitForPageToLoad("10000");
    }

}
This now hangs with the output:
11:22:15.571 INFO - Java: Sun Microsystems Inc. 16.3-b01
11:22:15.571 INFO - OS: Windows 7 6.1 x86
11:22:15.586 INFO - v1.0.1 [2696], with Core v@VERSION@ [@REVISION@]
11:22:15.686 INFO - Version Jetty/5.1.x
11:22:15.686 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
11:22:15.686 INFO - Started HttpContext[/selenium-server,/selenium-server]
11:22:15.686 INFO - Started HttpContext[/,/]
11:22:15.686 INFO - Started SocketListener on 0.0.0.0:4444
11:22:15.686 INFO - Started org.mortbay.jetty.Server@1f630dc
11:22:15.748 INFO - Checking Resource aliases
11:22:15.748 INFO - Command request: getNewBrowserSession[*chrome, http://, ] on session null
11:22:15.764 INFO - creating new remote session
11:22:16.435 INFO - Allocated session dc869f4254414d05b7f1d028dcf33123 for http://, launching...
11:22:16.559 INFO - Preparing Firefox profile...

There do appear to be two firefox processes running - but no screens appearing.
This occurs whether I run eclipse in Administrator mode or not.
If I kill one firefox process, then a Firefox window appears, but doesn't open anything.
What's wrong with Selenium in Win7?

A: It looks like you need to initialize selenium in your setup (Point to the correct selenium server, port, browser, etc).  Put the following code in the setup and see if this works better.  Also, try out using the *chrome command for firefox instead of *firefox.  It seems to work better.
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.com/");
selenium.start()


text:
Q: Method not working properly This is a method that i made for my comp sci class:
public Time (int y, int x)
{
minute = x;
hour = y;
if (minute>59 || minute<0)
{
 minute = 0;
}
if (hour>=24 || hour<0)
{
 hour=0;
}
}

void addOne()
{//Adds one to the minute.  Still in military time
minute++;
 if (minute == 60) //Makes minute never exceeds 59 minutes. Hour is added 1 and minute is set to 0
 {
minute = 0;
hour++;
 if (hour==24)
 {
  hour=0;
 }
 }
 }

 public String convert()
 {//Converts to standard time with am and pm
String timer = null;
int counter = 0;

if (hour<12)
{
 if (hour<9)
   {
   if (minute>9)
   {
   timer = "0"+hour+":"+minute+" A.M.";
   }
   if (minute<10)
   {
     timer = "0"+hour+":0"+minute+" A.M";
   }
   }

 if (hour>9)
 {
   if (minute>9)
   {
   timer = ""+hour+":"+minute+" A.M.";
   }
   if (minute<10)
    {
     timer = ""+hour+":0"+minute+" A.M";
    }
  }
}

 if (hour ==12)
   {
   if (minute>9)
   {
   timer = ""+hour+":"+minute+" P.M.";
   }
   if (minute<10)
   {
     timer = ""+hour+":0"+minute+" P.M";
   }
 }

 if (hour>12)
 {
   hour-=12;
   if (hour ==12)
   {
   if (minute>9)
   {
   timer = ""+hour+":"+minute+" A.M.";
   }
   if (minute<10)
   {
     timer = ""+hour+":0"+minute+" A.M";
   }
 }

   if (hour<9)
   {
   if (minute>9)
   {
   timer = "0"+hour+":"+minute+" P.M.";
   }
   if (minute<10)
   {
     timer = "0"+hour+":0"+minute+" P.M";
   }
   }

 if (hour>9)
 {
   if (minute>9)
   {
   timer = ""+hour+":"+minute+" P.M.";
   }
   if (minute<10)
   {
     timer = ""+hour+":0"+minute+" P.M";
   }
 }

 }

return timer;
 }

And this is the code that is suppose to run:
 Time time7 = new Time(23,59);
 System.out.println("\ntime7: " + time7);
 System.out.println("convert time7: " + time7.convert());
 time7.addOne();
 System.out.println("increment time7: " + time7);
 System.out.println("convert time7: " + time7.convert());

I get the output as:

time7: 2359
convert time7: 11:59 P.M.
increment time7: 1200
convert time7: 12:00 P.M

But I need the output to be:

time7: 2359
convert time7: 11:59 P.M.
increment time7: 0000
convert time7: 12:00 A.M

All other parts to the program works just fine, until i get to time7.

A: Starting with hour set to 23, then after this code:
if (hour>12)
{
    hour-=12;
    ...

what is the value of hour?
I'm afraid your code is needlessly complex, even if you fix the bug.  Look at the String.format() method for a much better way of formatting numbers for output that does not require you to handle all those "special cases" separately.

A: After you increment and before you convert, you could add:
hour %= 24;

If hour is 24, it would then become 0.


text:
Q: updating object using saveOrUpdate in Hibernate I am familiar with Hibernate.I have a question.
Lets say I do session.saveOrUpdate(object). If object contains some 'id'(object identifier), then it means update query will be fired if the object is modified.
I want to know how does Hibernate do that i.e. there could be 'n' number of fields in the object.Does Hibernate check each and every field to know if any field is modified(in this case update query to be fired)?

A: While using  use .saveOrUpdate() it will check if the object  has no identifier property and if so it will make it persistent by generating it the identifier and assigning it to session.

if the object is already persistent in this session, do nothing if
  another object associated with the session has the same identifier,
  throw an exception if the object has no identifier property, save() it
  if the object's identifier has the value assigned to a newly
  instantiated object, save() it if the object is versioned by a
   or , and the version property value is the same
  value assigned to a newly instantiated object, save() it otherwise
  update() the object

From Hibernate Docs

A: It checks the field(s) mapped as the identifier for the given object, if the object doesn't have an identifier it calls Save() which INSERTS the object,  if it does it calls Update() which UPDATES it

A: Basically in hibernate if you set object with unique identifier any how it is going to update the whole row by calling
session.saveOrUpdate();
or if unique identifier not found it insert the data.


text:
Q: How to set the field values in a form For Magento (1.9) how to set the value to the Magento form.
  $fieldset->addField('country_code', 'text', array(
          'label'     => Mage::helper('catalog')->__('Title3'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'country_code',
          'style'   => "border:10px",
          'value'  => 'hello !!',
          'disabled' => false,
          'readonly' => true,
        ));

I set the value is hello !! but it is not working.

A: Your problem is that values you set with addField() method are then overwritten with addValues() method which tries to set up a form fields values when form is used for editing existing entities or error occurred during submission.
Here is a workaround. Most likely you are getting values with a protected method like this:
protected function _getFormData()
{
    $data = Mage::getSingleton('adminhtml/session')->getFormData();

    if (!$data && Mage::registry('current_osmm_project')->getData()) {
        $data = Mage::registry('current_osmm_project')->getData();
    }

    return (array) $data;
}

So inside of your _prepareForm() method you replace:
$form->addValues($this->_getFormData());

with:
$_data = $this->__getFormData();
if (!empty($_data)) {
    $form->addValues($_data);
}


text:
Q: Batch: Returning a value from a SETLOCAL EnableDelayedExpansion I wonder why this code does not work as expected:
@ECHO off
SET S1=HELLO

SETLOCAL EnableDelayedExpansion
SET S2=!S1! WORLD^^!
ECHO !S2!
ENDLOCAL & SET S1=!S2!

ECHO %S1%
PAUSE

Output:
HELLO WORLD!
!S2!

Expected output:
HELLO WORLD!
HELLO WORLD!

Thanks.

A: It works as expected.
The delayed expansion will expand variables at execution time, not parse time, so it interpret your line ENDLOCAL & SET S1=!S2! as
endlocal
But at the part of SET S1=!S2! the delayed expansion is off so it can't be expanded anymore.
In your case you could use
ENDLOCAL & SET S1=%S2%
As the exclamation mark is S2 is "safe", as the delayed exp. is off at the moment of execution.
But an always secure returning is a bit more complicated.
We discussed it at Dostips: Return ANY string across ENDLOCAL boundry


text:
Q: JDBC Query vs JPA Query Performance I am having some issues related with performance while reading thousands of records from the database. I noticed that a pure JDBC query is much more faster that a JPA Native query.
Here is the query
select ID, COL_A, COL_B, COL_C, COL_D, COL_E, COL_F from MY_SUPER_VIEW_V v
where 1=1
and v.ID in (:idList)
and v.DATE_FROM <= :date
and v.DATE_TILL >= :date;

This query returns around 38.000 records.
The in idList has more than 1000 records and because I am using an Oracle DB it needs to be split in n queries.
Further i have a method that converts the Object[] result to my List<Entity>.
In order to understand the performance issue i created a pure JDBC query and a JPA Native query respectively to compare the results.
Here are the timings.
################ getScoresPureJDBCWithListIds ################
List of Ids retrieved. It took: 00:00:00.096 to execute query on DB using JDBC
It took: 00:00:01.180 to execute query on DB using JDBC query
Creating 24206 Scores records from DB result It took: 00:00:04.440
It took: 00:00:01.038 to execute query on DB using JDBC query
Creating 14445 Scores records from DB result It took: 00:00:04.307
################ getScoresJPANativeQueryWithListIds ################
It took: 00:06:09.450 to execute query on DB using JPA Native query
Creating 24206 Scores records from DB result It took: 00:00:00.009
It took: 00:04:04.879 to execute query on DB using JPA Native query
Creating 14445 Scores records from DB result It took: 00:00:00.007

With Hibernate analytics
################ USING FETCH_SIZE: 2000 ################
################ getScoresPureJDBCWithListIds ################
List of <elements> retrieved. It took: 00:00:00.296 to execute query on DB using JDBC
It took: 00:00:11.940 to execute query on DB using JDBC query
Creating 24206 records from DB result It took: 00:00:02.670
It took: 00:00:13.570 to execute query on DB using JDBC query
Creating 14445 records from DB result It took: 00:00:02.553

################ getScoresJDBCTemplateWithListIds ################
    List of <elements> retrieved. It took: 00:00:00.087 to execute query on DB using JDBC
    Creating 24206 records from DB result It took: 00:00:04.063
    Creating 14445 records from DB result It took: 00:00:04.064
    ################ getScoresJPANativeQueryAsApplication with hint fetch size 2000 ################
    2020-04-22 09:36:30.830  INFO 13262 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
        1232369 nanoseconds spent acquiring 1 JDBC connections;
        0 nanoseconds spent releasing 0 JDBC connections;
        1448702 nanoseconds spent preparing 1 JDBC statements;
        3992364 nanoseconds spent executing 1 JDBC statements;
        0 nanoseconds spent executing 0 JDBC batches;
        0 nanoseconds spent performing 0 L2C puts;
        0 nanoseconds spent performing 0 L2C hits;
        0 nanoseconds spent performing 0 L2C misses;
        0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
        0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
    }
    List of <ids> retrieved. It took: 00:00:00.261 to execute query on DB using JDBC
    2020-04-22 09:47:23.739  INFO 13262 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
        73670 nanoseconds spent acquiring 1 JDBC connections;
        0 nanoseconds spent releasing 0 JDBC connections;
        805772 nanoseconds spent preparing 1 JDBC statements;
        651947762290 nanoseconds spent executing 1 JDBC statements; ==> 10 minutes
        0 nanoseconds spent executing 0 JDBC batches;
        0 nanoseconds spent performing 0 L2C puts;
        0 nanoseconds spent performing 0 L2C hits;
        0 nanoseconds spent performing 0 L2C misses;
        0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
        0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
    }
    It took: 00:10:52.898 to execute query on DB using JPA Native query
    Creating 24206 records from DB result It took: 00:00:00.018
    2020-04-22 09:56:00.792  INFO 13262 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
        2758010 nanoseconds spent acquiring 1 JDBC connections;
        0 nanoseconds spent releasing 0 JDBC connections;
        3096653 nanoseconds spent preparing 1 JDBC statements;
        516148003151 nanoseconds spent executing 1 JDBC statements;
        0 nanoseconds spent executing 0 JDBC batches;
        0 nanoseconds spent performing 0 L2C puts;
        0 nanoseconds spent performing 0 L2C hits;
        0 nanoseconds spent performing 0 L2C misses;
        0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
        0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
    }
    It took: 00:08:37.032 to execute query on DB using JPA Native query
    Creating 14445 records from DB result It took: 00:00:00.006

For the JDBC query I can see 1) that executing the query is quite fast, but 2) processing each ResultSet element in a loop takes the most of the time 00:09 seconds int total
On the other for the JPA Native query 1) executing the query by calling the query.getResultList() method takes a lot of time 10:14 seconds on the other hand 2) processing each result is quite fast here. Analytics shows that a huge amount of time is spent on executing 1 JDBC statement. Even with FETCH_SIZE = 2000 nothing changed significantly.
Why JPA Native is quite slow when compare with pure JDBC? Would it be the type conversions? In my case I am talking about varchar2 and numbers. I was expecting identical results to JDBC. but from 8 seconds to 10mins its a lot.
What can I do to improve the JPA Native query?

A: You seem to compare two different queries, quite possibly resulting in the database coming up with different query plans.
There are lots of ways to investigate the problem but none of those are available to us because you don't provide a minimal reproducible example. I'll therefore suggest some options for you to investigate this yourself:

*

*Enable debug logging for your Java application including Hibernate and Oracle JDBC driver as explained in their documentation

*Watch where the delay is coming from, is it the database, the network, or your Java application? If in doubt check the network traffic with Wireshark on both sides of the connection or check Oracles database statistics on slow/heavy queries before and after the problematic queries

*If the problem is a slow database make sure your query parameters have matching types with your database index

*If you are sure the network and database are not causing the issue and debug logging doesn't help you further try using advanced tools like a cpu profiler with e.g. JVisualVM

*If you're still having problems maybe you have some extreme memory problem like to little system memory causing swapping or very frequent Full Garbage Collection which you can see from Garbage Collection logging

A: Please note, that if you want to compare two concepts you must try to isolate the main feature and get rid of other factors, that may disturb the result.
So to see if the JDBC query and JPA native query differes in behaviour I'd propose following scenario:

*

*use only one query with the 1000 element list

*use a plain table instead of a view
Here a simple setup to validate a performance. The table has 50 rows for each GRP_ID resulting in getting 50K rows for 1000 keys (see below the script to setup the table)
List params = (13001L..14000L)
def query = session.createNativeQuery("select * from tab where grp_id in (:paramsList) ")
query.setFetchSize(2000)
query.setParameterList("paramsList", params);
result = query.getResultList();

Sample run shows this result
 got 50000 rows in 1.388 seconds

So I thing there is no need to repeat the test with plain JDBC  you will see a comparable result.
What is more interesting is to repeat the run and remove the line
query.setFetchSize(2000)

which will effectivelly reset the fetch size to the default (was 20 in my case), the result for the same data is
 got 50000 rows in 1 minutes, 0.903 seconds

1) So the fetch size is the most propable explanation of the observed behaviour. The important thing is to check, if the JDBC drive got the right value and uses it - in doubt you must use the 10046 trace to see what fetch size uses the database. But for me the above statement worked perfectly.
2) There is no substantial difference between a native JPA query and a manually written JDBC execute + fetch of a prepared statement that would explain your observation. Both perform execute of the statement in the database followed by a number of fetches - the count depend on the used fetch size
3) Of course the view can also have influence, but it will be a difference in the query - not betwen the JDBC v. JPA.
4) You didn't mention it, so I'm not going in details here and assume your view doesn't contain any CLOB columns. This could of course play a role.
5) The last point is in your mention of two queries - do you use two independent queries or one query whith OR concatenated IN list? You din not provide details so it's hard to comment. Anyway two independent queries shoudl  have no influence.
Having said that one word of warning.
The limitation of the IN list count has its purpose. It is acceptable for an ad Hoc script to use a large IN list selection, but for a regular running query this could be a
parsing problem. Why?
You use a bind variables to be able to consider the following quereis as a single statament (that is parsed only once)
select * from tab where ID = 1
select * from tab where ID = 2

which leads to
select * from tab where ID = ?

But following two queries (with different length of the IN list) remains different and must be each extra parsed
select * from tab where ID in ( ? )
select * from tab where ID in ( ?, ? )

So re-thing if for your purpose with 30K rows+ the Hibernate is the best option
Hibernate was designed to elegantly get gid of the need of using SQL which is by majority of developers considered a cool think (contrary to the majority of the DB people that have an opposite meaning;).
This concept works fine, the simple the use case is the better. On the other side for batch processing it is sometimes better to approach it directly with SQL
Test Data
create table tab as
select
rownum id,
trunc(rownum /  50) +1 grp_id,
rpad('x',100,'y') pad
from dual connect by level <= 1000000;
create index idx on tab(grp_id);

A: JDBC is generally faster then JPA, but in JPA you can benefit from caching and this way get better performance.
I dont know the purpose of this query and how is used (reporting?), but you should consider to use different criteria then just list of so many ids. I doubt some user have chosen 1000+ ids manually, so i guess they are chosen batch by some other criteria. Try to use this creatia instead.


text:
Q: Remote access via ssh with password During my experiments with VPS (11.10 x86) I meet some problem with remote access to my machine.
After installing the system, I'm able to login via Putty from Windows machine (default account with root privileges) with password.
In next step I've created new user:
adduser gsa

After that I've tried to login via ssh:
ssh gsa@localhost

and everything works correctly (so password is correct).
In situation when I'm trying to access my machine as gsa user (from Putty@Windows) I receive Access denied.
Some extra info:
ssh -vv gsa@xxx.xxx.xxx.xxx
.
.
debug2: we did not send a packet, disable method
debug1: Next authentication method: publickey
debug1: Trying private key: /root/.ssh/id_rsa
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Trying private key: /root/.ssh/id_ecdsa
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
gsa@80.82.23.124's password:
debug2: we sent a password packet, wait for reply
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
Permission denied, please try again.

In /etc/ssh/sshd_config, I have placed:
PasswordAuthentication yes
AllowUsers gsa

Do you have any suggestions how can I resolve this problem?

A: Do you have a shell set for the gsa user?
You should not need to have the AllowedUsers line in there, by default anyone allowed to login should be able to ssh  in as well (well, aside from root).
On the ssh server what does 'getent passwd gsa' return?


text:
Q: QT - CSS: decoration on focus I'm experimenting a bit with CSS for making a cool user interface for my QT application.
I have this problem: I have a QPushButton and when it is on focus it has a rectangle on it that I want to remove. Here some screen-shot:
Normal button:

Focused button:

I have tried to add something (backgroundcolor, text-decoration, etc)
QPushButton:focus

but it keeps on highlighting..
Some hints?
here is the QPushButton css code:
QPushButton
{
    color: #b1b1b1;
    background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);
    border-width: 1px;
    border-color: #1e1e1e;
    border-style: solid;
    border-radius: 6;
    padding: 3px;
    font-size: 12px;
    padding-left: 5px;
    padding-right: 5px;
}

QPushButton:pressed
{
    background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);
}

QPushButton:hover
{
    border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);
}

QPushButton:focus {
    /*background-color: red;*/
}

ps. I'm on Ubuntu 12.04,with Qt 4.8 and I'm using this wonderfull css: http://www.yasinuludag.com/darkorange.stylesheet

A: One more alternative (works in windows and in ubuntu), for simplicity I use solid colors:
ui->pushButton->setStyleSheet(
    "QPushButton { background-color: #0188cc; color: #ffffff; outline: none }"
);

Note "outline: none" property - it removes focus rectangle from the button.
And one more related tip for checkable buttons: by default checked buttons drawed with dot pattern, not solid color as I expected for
"QPushButton:checked { background-color: #0188cc; color: #ffffff; }".
I added "border: none" to the button stylesheet:
"QPushButton:checked {  background-color: #0188cc; color: #ffffff; border: none }",
and dotted pattern disappeared! Now my checked buttons are clean, as I expected with solid background style.

A: I ran this snippet of code both on Windows 7 (Qt5) and on Ubuntu 12 (Qt4.8).  There are no problems with it:
QFile file("style.css");
if(file.open(QIODevice::ReadOnly))
{
  QString data = file.readAll();

  // "this" is the derived QMainWindow class
  this->setStyleSheet(data);
}

And alternatively...
ui->pushButton->setStyleSheet("QPushButton"
                              "{"
                              "color: #b1b1b1;"
                              "background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646);"
                              "border-width: 1px;"
                              "border-color: #1e1e1e;"
                              "border-style: solid;"
                              "border-radius: 6;"
                              "padding: 3px;"
                              "font-size: 12px;"
                              "padding-left: 5px;"
                              "padding-right: 5px;"
                              "}"
                              "QPushButton:pressed"
                              "{"
                              "background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525);"
                              "}"
                              "QPushButton:hover"
                              "{"
                              "border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a);"
                              "}"
                              );

qDebug() << ui->pushButton->styleSheet();

A: Thanks to Huytard's answer I have found out that is not a Qt CSS problem but it is the normal behavior of my Ubuntu Appearance setting to add an Orange rect on focused buttons.
The theme Ambiance is the default theme in Ubuntu 12.04 and it has the graphical behavior of enhancing focused elements with an orange inner rectangle.
If I change the theme the effect I posted about and I thought was QT CSS problem is gone away. So.. it is not a QT CSS problem but Ubuntu. If someone is interested in that.. http://askubuntu.com is full of information about changing the main theme color.

A: For some reason the accepted answer doesn't seem to work (at least on Qt5.6). This makes the work for me:
QPushButton:focus {
   border: none;
   outline: none;
}

A: The highlighted rectangle may be the QStyle::PE_FrameFocusRect styling. The only way to get rid of it is by implementing a custom style. Fortunately, Qt provides a way to implement just a proxy, which uses another style in the general case. For the focus rectangle you'd implement:
class Style_tweaks : public QProxyStyle
{
    public:

        void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
                           QPainter *painter, const QWidget *widget) const
        {
            /* do not draw focus rectangles - this permits modern styling */
            if (element == QStyle::PE_FrameFocusRect)
                return;

            QProxyStyle::drawPrimitive(element, option, painter, widget);
        }
};

qApp->setStyle(new Style_tweaks);


text:
Q: I can't seem to get a Docker-Nginx-Django app to refresh the static files I currently have a Django website that runs on a server using Nginx an Docker. Every time I update my main css file and deploy it, nothing changes, despite hard refreshing the site. When new static files are added, they end up working, but modified files don't seem to change.
This led me to believing that nginx or Docker was caching the file.
I've tried the following:
Clearing the cache in the nginx container, setting the lines expires -1 and sendfile off, rebuilding the containers, with no luck.
The last time I had this problem, I believe I had to delete the volume for it to refresh, which I don't think is a good solution.
Can someone explain what I am doing wrong?
Settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

nginx configuration:
upstream my_server {
    server web:80;
}

server {
    listen 80;
    server_name mywebsite.com;

    location / {
        proxy_pass http://my_server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $Host;
        proxy_redirect off;
        return 301 https://$host$request_uri;
    }
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    location /static/ {
        alias /code/staticfiles/;
        expires -1;
    }
}
server {
    listen 443 ssl;
    server_name mywebsite.com;
    ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem;

    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        proxy_pass http://my_server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;

    }
    location /static/ {
        alias /code/staticfiles/;
        expires -1;
    }

}

Docker Compose File
version: '3.7'

services:
    web:
        build:
            context: .
            dockerfile: Dockerfile.prod
        environment:
            - ENVIRONMENT=production
            - SECRET_KEY=@^la7#2kl%8$$o9rl)8$$aqvrwq5_x1=r!xc-1p#+(!m4r2vue*&
            - DEBUG=0
            - EMAIL_HOST_USER=apikey
            - EMAIL_HOST_PASSWORD=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
        volumes:
            - .:/code
            - static_volume:/code/staticfiles
        networks:
            - nginx_network
            - db_network
        depends_on:
            - db
    nginx:
        image: nginx:1.17.0
        ports:
            - 80:80
            - 443:443
        volumes:
            - ./config/nginx/conf.d:/etc/nginx/conf.d
            - static_volume:/code/staticfiles
            - ./data/certbot/conf:/etc/letsencrypt
            - ./data/certbot/www:/var/www/certbot
        depends_on:
            - web
        networks:
            - nginx_network
        command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s
        reload; done & nginx -g \"daemon off;\"'"
    db:
        image: postgres:11
        env_file:
            - config/db/db_env
        networks:
            - db_network
        volumes:
            - db_volume:/var/lib/postgresql/data/
    certbot:
        image: certbot/certbot
        volumes:
            - ./data/certbot/conf:/etc/letsencrypt
            - ./data/certbot/www:/var/www/certbot
        entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew;
        sleep 12h & wait $${!}; done;'"
networks:
    nginx_network:
        driver: bridge
    db_network:
        driver: bridge
volumes:
    db_volume:
    static_volume:

Dockerfile:
# Pull base image
FROM python:3.7

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Set work directory
WORKDIR /code

# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system

# Copy project
COPY . /code/

RUN apt update
RUN apt install -y cron

CMD /code/script_prod.sh


text:
Q: How to set custom filter in form validation in CodeIgniter? I am using CodeIgniter's form validation. Here is an example:
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

The documentation say:

Any native PHP function that accepts one parameter can be used as a
  rule, like htmlspecialchars, trim, MD5, etc.

What if I want the value to pass through my own custom filter? For example, I would like the value to be cleaned of "badWord".
function curseWordRemove($original = '') {
    return str_replace('badWord', '', $original);
}

CodeIgniter already provides ways to do custom validation, but not custom filters. The custom validation only returns true or false, not the filtered string.
function isPolite($string = '') {
    if (strpos($string, 'badWord') !== false) {
        $this->form_validation->set_message(
            'fieldName',
            'contains a very bad word'
        );
        return false;
    } else {
        return true;
    }
}

A: Jojo, you must have missed it the userguide, its called a callback, and here is the documentation.
An Example:
<?php

class Form extends CI_Controller {

    public function index()
    {
        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
        $this->form_validation->set_rules('password', 'Password', 'required');
        $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');

        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('myform');
        }
        else
        {
            $this->load->view('formsuccess');
        }
    }

    public function username_check($str)
    {
        if ($str == 'test')
        {
            $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

}
?>

Basically, create a validation called callback_check_bad_words and a matching function in your controller called check_bad_words($value).  Return a boolean as a result (as the result goes back to the validation).
Since you can only pass back a boolean, you need to either use a global variable, OR run the 'sanitization' of your word later on, you don't need it in validation UNLESS you want to stop it from submission.
If your intent is to sanitize the input for bad words, just do it, don't validate for it.


text:
Q: how to get the state for outgoing calls In the OnReceive method  I have something like this:
    Bundle bundle=intent.getExtras();
   String phonenumber=intent.getStrngExtra(Intent.EXTRA_PHONE_NUMBER);

How to chech if the dialing call is still on or the client hanged up the call?
How to check if the call was answered?
I need to print up a toat when the client hanged up the call or when the called client answered to the call.

A: You will need a broadcast receiver registered for action android.intent.action.PHONE_STATEiF THE phone state has not changed to idle once it is offhook, it means the call is still going on.
the call was answered if the state in read phone state broadcast receiver changes to offhook.  Put a toast as need in these states.
   public class CallDurationReceiver extends BroadcastReceiver {

static boolean flag =false;
static long start_time,end_time;
@Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if(action.equalsIgnoreCase("android.intent.action.PHONE_STATE")){
            if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                                TelephonyManager.EXTRA_STATE_RINGING)) {

               //tOAST FOR INCOMING CALL, NOT YET PICKED UP

            }
            if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                    TelephonyManager.EXTRA_STATE_IDLE)) {
                end_time=System.currentTimeMillis();
 //Total time talked =
                long total_time = end_time-start_time;
                //Store total_time somewhere or pass it to an Activity using intent

}     if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
                    TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                 start_time=System.currentTimeMillis();

}

    }
    }

Register your receiver in your manifest file like this:
<receiver android:name=".CallDurationReceiver">
       <intent-filter>
           <action android:name="android.intent.action.PHONE_STATE" />
       </intent-filter>
    </receiver>
        }

Also add the uses permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

A: Well all I find out a solution for this and I successfully implemented it.Its not possible to fetch the exact time when the callee has accepted an outgoing call.
Before picking up a call in the other end it has already passed through 2 stages namely on_State_idle and on_state_offhook. On_state_ringing is not working for the outgoing calls.
Let's assume a phone is ringing for 40sec (this am not sure) continuously if the person at the other side didn't pick the call.

*

*Start a timer along with the starting stage of on_State_idle and on_state_offhook.

*Two cases if the timer cross above 40sec means the person at the other hand pick my call.

*If on_State_idle->on_state_offhook->on_State_idle worked within 40sec means the other hand didn't pick my call.

*If the second case is true, fetch the call talk duration from the call log.

*Totaltimer running time - time in call log gives you the exact time of picking of the outgoing Call!

A: you can use the below code for handling call state:::
    private Runnable callMonitor = new Runnable() {
        public void run() {
            try {
                EndCallListener callListener = new EndCallListener();
                TelephonyManager mTM = (TelephonyManager)m_activity.getSystemService(Context.TELEPHONY_SERVICE);
                mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
            } catch(Exception e) {
                Log.e("callMonitor", "Exception: "+e.toString());
            }
        }
    };

    private class EndCallListener extends PhoneStateListener {
        private boolean active = false;
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            if(TelephonyManager.CALL_STATE_RINGING == state) {
                Log.i("EndCallListener", "RINGING, number: " + incomingNumber);
            }
            if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
                //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.
                active = true;
                Log.i("EndCallListener", "OFFHOOK");
            }
            if(TelephonyManager.CALL_STATE_IDLE == state) {
                //when this state occurs, and your flag is set, restart your app
                Log.i("EndCallListener", "IDLE");
                if (active) {
                    active = false;

                    // stop listening
                    TelephonyManager mTM = (TelephonyManager)m_activity.getSystemService(Context.TELEPHONY_SERVICE);
                    mTM.listen(this, PhoneStateListener.LISTEN_NONE);

                    // restart the inbox activity
//                  Intent intent = new Intent(m_activity, MDInboxActivity.class);
//                  m_activity.startActivity(intent);
                }
            }
        }
    }


text:
Q: How to store mysql query result to a global varibale in node js I am beginner to node and I am trying to get the result of mysql query in to a global varible. How can I do that? I want to access that value for later use.Please help
Here is what I have tried.

var last_id ='';
function callback(val){
   last_id =val;
}

var sesion_sql = "INSERT INTO session_waterfall (event, step,campaign_id,session_id,timestamp,elapsed) VALUES ('gfdgdfgfd', ' 2',' 23','1234','0','0')";
  connection.query(sesion_sql, function (err, result) {
    if (err) throw err;
    callback(20);
  });
});

 console.log(last_id);


text:
Q: How to initalize 2 firebase on single application? I am building a e-commerce website with admin dashboard.
Website using its own hosting, firestore and authentication.
Right now I am trying to get my admin dashboard to use its own hosting and authentication BUT using website firestore and I keep getting this error:

index.esm.js:769 Uncaught FirebaseError: Firebase: Firebase App named
'[DEFAULT]' already exists (app/duplicate-app).

import firebaseAuthOnly from 'firebase/app'
import firebase from 'firebase/app'
import "firebase/firestore";
import "firebase/storage";
import "firebase/auth";
import "firebase/functions";
import "firebase/analytics";
import "firebase/performance";

const firebaseAuthOnlyConfig = {
    apiKey           : process.env.REACT_APP_FIREBASE_AUTH_API,
    authDomain       : process.env.REACT_APP_FIREBASE_AUTH_AUTH_DOMAIN,
    projectId        : process.env.REACT_APP_FIREBASE_AUTH_PROJECT_ID,
    storageBucket    : process.env.REACT_APP_FIREBASE_AUTH_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_AUTH_MESSAGING_SENDER_ID,
    appId            : process.env.REACT_APP_FIREBASE_AUTH_APP_ID,
    measurementId    : process.env.REACT_APP_FIREBASE_AUTH_MEASUREMENT_ID
}

const firebaseConfig = {
    apiKey           : process.env.REACT_APP_FIREBASE_API,
    authDomain       : process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    databaseURL      : process.env.REACT_APP_FIREBASE_DATABASE_URL,
    projectId        : process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket    : process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
    appId            : process.env.REACT_APP_FIREBASE_APP_ID,
    measurementId    : process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
}

// Initialize Firebase
firebaseAuthOnly.initializeApp(firebaseAuthOnlyConfig);
firebaseAuthOnly.analytics();
firebaseAuthOnly.performance();

firebase.initializeApp(firebaseConfig);

A: You need to name your different instances (Apps as Firebase calls them); by default you're working with the [DEFAULT] App, because that's the most common use case, but when you need to work with multiple Apps then you have to add a name when initialising:
// Intialize the "[DEFAULT]" App
var mainApp = firebase.intializeApp({ ... });

// Intialize a "Secondary" App
var secondaryApp = firebase.initializeApp({ ... }, "Secondary");
...
mainApp.database().ref("path/to/data").set(value);
secondaryApp.database().ref("path/to/data").set(anotherValue);

You can find a more example scenarios in the updated Initialize multiple apps section of the Add Firebase to your JavaScript Project guide.


text:
Q: ASP.Net MVC - how to handle exception in JSON action (return JSON error info), but also publish the exception for filters? I'm using a filter to log exceptions thrown by actions which looks like this:
public override void OnActionExecuted(ActionExecutedContext filterContext) {
  if (filterContext.Exception != null) {
    //logger.Error(xxx);
  }
  base.OnActionExecuted(filterContext);
}

Now I'd like to handle all my JSON actions to return JSON result with exception information. This allows the Ajax calls to determine if there was any error on the server instead of receiving the error page source, which is useless for Ajax. I've implemented this method for JSON actions in my AppControllerBase:
public ActionResult JsonExceptionHandler(Func < object > action) {
  try {
    var res = action();
    return res == null ? JsonSuccess() : JsonSuccess(res);
  } catch (Exception exc) {
    return JsonFailure(new {
      errorMessage = exc.Message
    });
  }
}

This works nice, but obviously the catch() statement prevents all filters from handling the exception, because there's no exception thrown actually. Is there any way how to leave exception available for filters (filterContext.Exception)?

A: You could store the exception in the RequestContext and intercept it in your filter.

A: The solution:
Action:
public ActionResult JsonExceptionHandler(Func < object > action) {
  try {
    var res = action();
    return res == null ? JsonSuccess() : JsonSuccess(res);
  } catch (Exception exc) {
    controller.ControllerContext.HttpContext.AddError(exc);
    return JsonFailure(new {
      errorMessage = exc.Message
    });
  }
}

Filter:
public override void OnActionExecuted(ActionExecutedContext filterContext) {
  var exception = filterContext.Exception ? ? filterContext.HttpContext.Error;
  if (exception != null) {
    //logger.Error(xxx);
  }

  if (filterContext.Result != null &&
    filterContext.HttpContext.Error != null) {
    filterContext.HttpContext.ClearError();
  }

  base.OnActionExecuted(filterContext);
}


text:
Q: SonarLint, Array of String: Declare this local variable with "var" instead = error With Java 11, for this code:
String[] arrayString = {"foo", "bar"};

SonarLint say Declare this local variable with "var" instead.
So, I have tried:
var arrayString = {"foo", "bar"};
// or
var[] arrayString = {"foo", "bar"};

But now I get these errors:

*

*Array initializer needs an explicit target-type

*'var' is not allowed as an element type of an array
How can I declare correctly array variables or attributes.

A: You could use
var arrayString = new String[]{"foo", "bar"};


text:
Q: Firebase Push Notification send through http protocols click event analytics Is there any way to get the count of the notifications clicked which are sent through firebase push notifications (fcm) HTTP protocol over web app?

A: Notification Open
You can listen for notification clicks for Data payloads by adding the following to your firebase-messaging.js file:
self.addEventListener('notificationclick', function(event) {
  event.notification.close();

  // Do something as the result of the notification click
});

Notification Close
You can listen for notification close events with:
self.addEventListener('notificationclose', function(event) {
  // Do something as the result of the notification close
});

Ref: notificationclick