text:
Q: Yii Models: Using dynamic table name in a Yii model I have a Yii model that will be using (later) multiple databases and the table prefix will be based on a code.
For example:
AMI_tablename, BMI_ AMI_tablename etc
These all tables are same but in different databases.
I want to know how could I provide the dynamic table name to Yii model at run time?
I tried to using a setter function but the parent class CActiveRecord gives an error as it does not get the value from the child model class.
so here is my model code (only the part I have problem)
class RevShareModel extends CActiveRecord
{

    public $prefix;

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return $this->prefix . '_revshare_model';
    }

now somewhere in my controller
$obj = RevShareModel::model();
$obj->prefix ="BMI";
$obj->tableName();
$obj->findByPk(1);

exit;

But what I get the error is:
CDbException

The table "_revshare_model" for active record class "RevShareModel" cannot be found in the database.

C:\wamp\www\framework\db\ar\CActiveRecord.php(2264)

seems like when tableName() method is called by CActiveRecord it does not get $prefix.

A: You've got such error because the table name is actually stored in model's metadata. You can see that by checking contents of $model->getMetaData() which returns CActiveRecordMetaData object. To refresh metadata you should call $model->refreshMetaData() after changing the 'prefix' attribute of your model, e.g.:
...
$obj->prefix ="BMI";
$obj->refreshMetadata();
...

This will definitely do the trick.

A: You have to override the CActiveRecord::tableName method (probably in an abstract base class for your models). Here's what it does by default:
public function tableName()
{
    return get_class($this);
}

And here's what you could change it to:
abstract class MyActiveRecord extends CActiveRecord
{
    public $prefix; // should probably be private, your call

    public function tableName()
    {
        return $prefix.'_'.get_class($this);
    }
}

A: This is how I've solved that problem.
private static $_tableName;

public function __construct($tableName)
{
    if(strlen($tableName) == 0)
    {
        return false;
    }

    if(strlen($tableName)>0){
        self::$_tableName = $tableName;
    }

    self::setIsNewRecord(true);
}

public static function model($tableName)
{
    if(strlen($tableName) == 0)
    {
        return false;
    }

    $className=__CLASS__;

    if(strlen($tableName)>0){
        self::$_tableName = $tableName;
    }

    return parent::model($className);
}

public function tableName()
{
    return '{{'.self::$_tableName.'}}';
}

public function setTableName($tableName)
{
    self::$_tableName = $tableName;
}

...

When I use this model, I simply put the name of the table in brackets:
$model = new ClassName($tableName);

A: I have same problem.
I have a model, but I want the data to be saved in different table .So  I change the table name before save the data.
public $tbl_name = 'tbl_user_1';//default table
public function tableName()
{
return $this->tbl_name;
}
public function saveDataReg(){
    $mKey = $this->selfMHash($this->username);
    $modKey = $mKey % 2;
    $this->tbl_name = 'tbl_user_' . $modKey;

    $this->refreshMetadata();//change the default Metadata

    $this->save();
}
public function selfMHash($key){
    $md5 = substr(md5($key), 0, 8);
    $seed = 31;
    $hash = 0;

    for($i=0; $i<8; $i++){
        $hash = $hash * $seed + ord($md5{$i});
        $i++;
    }

    return $hash & 0x7FFFFFFF;
}

Now I find the Metadata not be changed when the function of refreshMetadata be used.
Last I change the original code
    public function refreshMetaData()
{
    $finder=self::model(get_class($this));
    $finder->_md=new CActiveRecordMetaData($finder);
    if($this!==$finder)
        $this->_md=$finder->_md;

    //return var_dump($this);
}

public function new_refreshMetaData()
{
    $finder=self::model(get_class($this));
    $finder->_md=new CActiveRecordMetaData($this);
    if($this!==$finder)
        $this->_md=$finder->_md;

    //return var_dump($this);
}

I override the function of refreshMetaData and chage the param of CActiveRecordMetaData.
$this->new_refreshMetadata();//use new function

Then it worked.
I don't understand the reason of problem.

A: You can use with MyModel::model()->tableName(), but please don't forget write {{table}}.


text:
Q: Checkbox in the first row of datagrivew does not respond to click (does not check and un check) I have a winforms window with three tabs. All the three tabs have datagridviews. In first 2 tabs the datgridview is in virtual mode.
While the last tabs datagridview is databound. All these DataGrids have checkbox column(column0).
On 1 machine the checkbox in the row0 does not get checked or unchecked.
Sorting the datagridview does not help either even though there is new data in row0 the checkbox does not respond.
This happens in all 3 datagridviews.
It appears checkbox is not changing state upon mouse click however pressing space on the checkbox of row0 does check it.
Cannot understand what is the issue! help
I tried commenting the events and launched the exe. The issue still persists. I commented the below events 1 at a time and ran the exe.
The issue still persists. I have captured a logs.
CellFormatting
CellMouseDown
CellMouseEnter
CellPainting
CellValueChanged
CellValueNeeded
CellValuePushed
ColumnHeaderMouseClick
CurrentCellDirtyStateChanged
DataError
This is the log of mouse click on Row 0 Column 0:
dataGridContactAndGroups_CellMouseDown  RowIndex 0 ColumnIndex 0
dataGridContactAndGroups_CellValueNeeded Row 0 Column 0 checkvalue False
dataGridContactAndGroups_CellValueNeeded  Row 0 Column 0 checkvalue False
dataGridContactAndGroups_CellValueNeeded  Row 0 Column 0 checkvalue False
dataGridContactAndGroups_CellValueNeeded  Row 0 Column 0 checkvalue False
This is the log of mouse click on Row 1 Column 0:
dataGridContactAndGroups_CellValueNeeded  Row 0 Column 0 checkvalue False
dataGridContactAndGroups_CellMouseDown CHECKBOX ISSUE RowIndex 1 ColumnIndex 0
dataGridContactAndGroups_CellValueNeeded  Row 0 Column 0 checkvalue False
dataGridContactAndGroups_CurrentCellDirtyStateChanged CHECKBOX ISSUE Dirty Cell is Row 1 Column 0
dataGridContactAndGroups_CurrentCellDirtyStateChanged  Is cell dirty?  True
dataGridContactAndGroups_CellValuePushed CHECKBOX ISSUE Before if RowIndex1 ColumnIndex 0
dataGridContactAndGroups_CellValuePushed CHECKBOX ISSUE RowIndex1 ColumnIndex 7 Selected Value True
dataGridContactAndGroups_CellValueChanged CHECKBOX ISSUE RowIndex 1 ColumnIndex 0
dataGridContactAndGroups_CellValueNeeded  Row 0 Column 0 checkvalue False
dataGridContactAndGroups_CurrentCellDirtyStateChanged CHECKBOX ISSUE Dirty Cell is Row 1 Column 0
If you notice after CellMouseDown in Row 1 Column 0. CurrentCellDirtyStateChanged, CellValuePushed & CellValueChanged have been fired
where as in Row 0 Column 0 these events have not fired.
Also i want to mention we are using wienfenlou docking control within a docked window these datagrids are placed

A: I might be late but for anyone with the same problem try increasing the row height.
For to me unknown reasons the row height in DataGridView can cause checkboxes to not show (for me at row height 20 and lower)
and also for all of them to work except the first one ( at row height 24 and lower).
If anyone knows why this works, please let me know.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to print first element in list of string which is delimited by Pipe symbol in python How to get the first element from each pipe delimiter value.
test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df|

For Example: I want to print the output like this:
test-123-2
lskd-929-8282
ploi-90293-2
opuye-8392-kl

I tried something like this:
value=test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df|
result = value.split('|')
restult[0]

But its not coming the output which i expected. Can someone guide how can I print all first element in each column which is delimited by Pipe symbol
Thanks in advance.

A: Combine split(',') with split('|') like below:
res = [w.split(',')[0] for w in s.split('|')]

Output:
>>> for v in res[:-1]:
...     print(v)
...
test-123-2
lskd-929-8282
ploi-90293-2
opuye-8392-kl

A: We can do a double split, being careful with the empty values. Try this:
s = 'test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df|'
result = [data.split(',')[0] for data in s.split('|') if data]

Now result contains the expected values, so ya can do with them what you need to:
result
=> ['test-123-2', 'lskd-929-8282', 'ploi-90293-2', 'opuye-8392-kl']

A: Another, not so elegant way of doing it wihout using list comprehension is this:
test = "test-123-2,abc,1232,,21,fd|lskd-929-8282,vbd,3221,,983,ew|ploi-90293-2,xsw,9073,,34,mn|opuye-8392-kl,few,45432,,234,df|"

result = list(map(lambda y: y.split(',')[0], list(map(lambda x: x, test.split('|')))))

for r in result:
    print(r)

The result is:
test-123-2
lskd-929-8282
ploi-90293-2
opuye-8392-kl


text:
Q: Writing a partial sum of Fourier series as an integral
Show that the partial sum in equation (3) may be written as:$$f_N(x)=\frac{2}{\pi}\int_{0}^x \frac{\sin(2Nt)}{\sin(t)}\,dt$$

Can someone please explain me how to show these 2 are equal? The first step I can only think of is to use property of an even function.
Equation (3):
$$
f_N(x) = \frac{4}{\pi} \sum_{n=1}^N \frac{\sin((2n-1)x)}{2n-1}
$$

A: Observe that both terms of the desired identity vanish at $x=0$, then by differentiating (a finite sum and a primitive), it is sufficient to prove that
$$
\sum_{n=1}^{N} \cos ((2n-1)\theta)=\frac{\sin (2N\theta)}{2\sin\theta}.\tag1
$$
To prove $(1)$, here are some possible steps:
$$
\begin{align}
\sum_{n=1}^{N} \cos ((2n-1)\theta)&=\Re \sum_{n=1}^{N} e^{i(2n-1)\theta}\\\\
&=\Re\left( e^{i\theta}\frac{e^{2iN\theta}-1}{e^{2i\theta}-1}\right)\\\\
&=\Re\left( e^{i\theta}\frac{e^{iN\theta}\left(e^{iN\theta}-e^{-iN\theta}\right)}{e^{i\theta}\left(e^{i\theta}-e^{-i\theta}\right)}\right)\\\\
&=\Re\left( e^{iN\theta}\frac{2i\sin(N\theta)}{2i\sin\theta}\right)\\\\
&=\Re\left( \left(\cos (N\theta)+i\sin (N\theta)\right)\frac{\sin(N\theta)}{\sin\theta}\right)\\\\
&=\frac{\cos (N\theta)\sin (N\theta)}{\sin\theta}\\\\
&=\frac{\sin (2N\theta)}{2\sin\theta}.
\end{align}
$$


text:
Q: Scala Validates Recursive JSON with Reads (Play Framework) I trying to implemente a json validations for a filter like this:
import play.api.libs.json._
import play.api.libs.functional.syntax._

trait IFilterClause

case class ComparisonClause(operand: String, operator: String, value: String, valueType: String) extends IFilterClause{
  implicit val comparisonClauseReads: Reads[ComparisonClause] = (
    (JsPath \ "operand").read[String] and
    (JsPath \ "operator").read[String] and
    (JsPath \ "value").read[String] and
    (JsPath \ "value_type").read[String]
  )(ComparisonClause.apply _)
}

case class LogicalClause(operator: String, children: List[IFilterClause]) extends IFilterClause {
  implicit lazy val logicalClauseReads: Reads[IFilterClause] = (
    (JsPath \ "logical_operator").read[String] and
      ((JsPath \ "children").read[LogicalClause] or (JsPath \ "children").read[ComparisonClause])
  )(LogicalClause.apply _)
}

as you can see on my LogicalClause, my children could be the a json with the same format of a LogicalClause or a json with the format of a ComparisonClause, but I can figure it our how to make this work.
Any suggestiong?
I'm getting the following error:

No Json deserializer found for type
  com.userzoom.analytics.explorerapi.models.LogicalClause. Try to
  implement an implicit Reads or Format for this type. [error]
  ((JsPath \ "children").read[LogicalClause] or (JsPath \
  "children").read[ComparisonClause])

A: First you should put your implicits in the companion object, not in your case class. You can try this code, it should compile:
import play.api.libs.json._
import play.api.libs.functional.syntax._

trait IFilterClause

case class ComparisonClause(operand: String, operator: String, value: String, valueType: String) extends IFilterClause
object ComparisonClause {
  implicit val comparisonClauseReads: Reads[ComparisonClause] = (
    (JsPath \ "operand").read[String] and
      (JsPath \ "operator").read[String] and
      (JsPath \ "value").read[String] and
      (JsPath \ "value_type").read[String]
  )(ComparisonClause.apply _)
}

case class LogicalClause(operator: String, children: List[IFilterClause]) extends IFilterClause
object LogicalClause {
  implicit lazy val logicalClauseReads: Reads[LogicalClause] = (
    (JsPath \ "logical_operator").read[String] and
      (JsPath \ "children").read[List[IFilterClause]]
  )(LogicalClause.apply _)
}

object IFilterClause {
  implicit lazy val reader: Reads[IFilterClause] = {
    // needed because Reads is invariant
    val reader1 = ComparisonClause.comparisonClauseReads.map(f => f: IFilterClause)
    lazy val reader2 = LogicalClause.logicalClauseReads.map(f       => f: IFilterClause)
    reader1 orElse reader2
  }
}


text:
Q: How do I get items to stack in Flex? I'm trying to create a rock, paper, scissors game and I'm having trouble getting the items to stack. I have three images on one row and I would like to display the fourth image below them (this image would be the resulting image displaying either rock, paper or scissors).
I tried using flex-wrap, changing width's, etc and after an hour of searching, I figured I'll just ask you guys who will probably solve it in a minute lol Here is my code and thanks in advance for the help :D

@import url("https://fonts.googleapis.com/css?family=Germania+One");
$primary-color: #000000;
$serif: "Germania One",
cursive;
html {
  background: #4d1c17;
  font-size: 66%;
}

h1 {
  font-size: 4rem;
  text-align: center;
  margin-top: 100px;
}

h2 {
  text-align: center;
  font-size: 3rem;
}

h1,
h2 {
  color: $primary-color;
  font-family: $serif;
}

.container {
  text-align: center;
  width: 100%;
  img {
    height: 12rem;
    padding: 20px;
    &:hover {
      height: 13rem;
    }
  }
}

#rock,
#paper,
#scissor {
  display: flex;
  justify-content: center;
  border-radius: 20px;
  cursor: pointer;
}

#scissor {
  margin-left: 30px;
  padding-left: 10px;
  color: green;
}

p {
  font-size: 4rem;
  width: 100%;
  height: auto;
  margin-top: 200px;
  display: flex;
  justify-content: center;
}

#rock_win,
#paper_win,
#scissor_win {
  justify-content: center;
  width: 50%;
  height: auto;
  flex-wrap: wrap;
  border-radius: 20px;
  cursor: pointer;
}

#scissor_win {
  margin-left: 30px;
  padding-left: 10px;
}

Rock, Paper, Scissor's

Choose your fate

A: *

*Make sure you close your img's. They are missing the ending bracket.

*The display: flex goes on the container, and the children all get a flex assigned to them (Flex Guide).

*I added the SASS tag, since it seems you're using that

$primary-color: #000000;
    $serif: "Germania One", cursive;

    html {
      background: #4d1c17;
      font-size: 66%;
    }

    h1 {
      font-size: 4rem;
      text-align: center;
      margin-top: 100px;
    }

    h2 {
      text-align: center;
      font-size: 3rem;
    }

    h1,
    h2 {
      color: $primary-color;
      font-family: $serif;
    }

    .container {
      text-align: center;
      width: 100%;

      img {
        height: 12rem;
        padding: 20px;
        &:hover {
          height: 13rem;
        }
      }
    }

    .items {
      display: flex;
    }

    #rock,
    #paper,
    #scissor {
      flex: 1;
      /* justify-content: center; */
      border-radius: 20px;
      cursor: pointer;
    }

    #scissor {
      color: green;
    }

    p {
      font-size: 4rem;
      width: 100%;
      height: auto;
      margin-top: 200px;
      display: flex;
      justify-content: center;
    }
    #rock_win,
    #paper_win,
    #scissor_win {
      margin: 0 auto;
      clear: both;
      width: 50%;
      height: auto;
      border-radius: 20px;
      cursor: pointer;
    }
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Rock, Paper, Scissors

Choose your fate

I'm having trouble posting my inline code here with SCSS, so here's a jsbin link in addition. jsbin

A: The display: flex; setting needs to be applied to the container/parent element, not to the flex-items/children.
Since you have a structure of .container as a container for items and #scissor_win, and items  again contains three items-to-be stacked, the CSS rules should (partly) look like this:
.container {
  display: flex;
  flex-direction: column;
}
.items {
  display: flex;
  flex-direction: column;
}

The single items don't need display: flex, unless you want to center their contents using flex.

A: using @kauffee000 snippet, I reduced the amount of css required.
Hope it helps.
explanation:
the trick here is to make .container be a flex and have a flex-direction of column, while .items be flex with a flex-direction of row.
$primary-color: #000000;
$serif: "Germania One", cursive;

html {
  background: #4d1c17;
  font-size: 66%;
}

h1 {
  font-size: 4rem;
  text-align: center;
  margin-top: 100px;
}

h2 {
  text-align: center;
  font-size: 3rem;
}

h1,
h2 {
  color: $primary-color;
  font-family: $serif;
}

.container {
  text-align: center;
  width: 100%;
  display: flex;
  flex-direction: column;

  img {
    height: 13rem;
  }
}

.items {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  & div {
    border-radius: 20px;
    flex: 1;

    &:hover {
      img {
        height: 5rem;
      }
    }
  }
}


text:
Q: What are best use cases of shared_ptr, unique_ptr and weak_ptr? While it is easy to learn about std::shared_ptr, std::unique_ptr and std::weak_ptr by knowing what are they, it seems to be very difficult for me to understand in what circumstances they proved to be useful.
Can anyone give one or two concrete example of three of them?

A: I assume you know what each of these smart pointers do so I am not going to explain them. Instead I will give you examples of how I have used them in my own code or from libraries I have used that need them.
std::unique_ptr: Can be returned from an API to indicate that the resource needs to be managed by the caller and that it is not safe to share the object. For example, gRPC creates CompletionQueue instances like this. CompletionQueue has sensitive lifetime and synchronization requirements. By returning unique_ptr it is clear that the caller is responsible for lifetime management and it makes it cumbersome to share the CompletionQueue. It is still not impossible to share it (can get the raw pointer from the unique_ptr or use a reference to the unique_ptr, both of which are typically code smells).
std::shared_ptr/std::weak_ptr: Not the simplest use case, but here we go...
AudioPlayer::AudioPlayer() {
   thread_local std::weak_ptr<AudioPlayerMixer> mixedOutput;

   if (mixedOutput.expired()) {
      m_mixedOutput = std::make_shared<AudioPlayerMixer>();
      mixedOutput = m_mixedOutput;
   } else {
      m_mixedOutput = mixedOutput.lock();
   }
}

In this example, all AudioPlayer instances on a thread need to have their audio mixed together using AudioPlayerMixer. So, each AudioPlayer has a shared_ptr<AudioPlayerMixer> so that when the last AudioPlayer instance holding the shared_ptr is destroyed, the mixer will be as well. The usage of thread_local just facilitates having a unique AudioPlayerMixer per thread. The thread_local storage of the AudioPlayerMixer should not prolong the life of the mixer as the lifetime of the AudioPlayerMixer is decided by the existence of AudioPlayer instances (ie. no AudioPlayer => no AudioPlayerMixer) - this is why a weak_ptr is used. mixedOutput.expired() == true means that either no AudioPlayer has been created on this thread or all previously existing players were deleted. mixedOutput.expired() == false means another AudioPlayer exists on this thread and the current AudioPlayer needs to get a shared_ptr to the same mixer. Note you have to be careful when using shared_ptr and weak_ptr from multiple threads as they are not thread safe. In this example, thread_local and the fact that AudioPlayer is only created and destroyed within the same thread ensures it is safe.
Of course, this could have all be done without the smart pointers but the smart pointers help communicate the intent of the code better.


text:
Q: Android error: W/Ads: Not enough space to show ad. Needs 320x50 dp, but only has 384x0 dp Others too have this issue, but mine is unique (I think) in that this error only occurs when I open the keyboard within the app like this. It does not happen when the keyboard is not opened.
Again, the error is:
W/Ads: Not enough space to show ad. Needs 320x50 dp, but only has 384x0 dp.

Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">

<EditText
    android:id="@+id/input"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="Enter your Number"
    android:textAlignment="center"
    android:layout_gravity="center"
    android:inputType="text"
    android:ems="25"
    android:textColor="@color/colorPrimary"
    android:textSize="20sp"
    android:maxLength="31"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="45dp"/>

<TextView
    android:id="@+id/from"
    android:text="@string/from"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textColor="@color/colorPrimary"
    android:textSize="16sp" />

<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:entries="@array/spinner_entries1"
    android:background="@null"
    android:layout_marginBottom="25dp"/>

<TextView
    android:id="@+id/to"
    android:text="@string/to"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textColor="@color/colorPrimary"
    android:textSize="16sp" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@null"
    android:cursorVisible="false"
    android:entries="@array/spinner_entries2"
    android:layout_marginBottom="20dp"/>

<EditText
    android:id="@+id/output"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:layout_gravity="center"
    android:inputType="text"
    android:ems="25"
    android:textColor="@color/colorPrimary"
    android:textSize="20sp"
    android:maxLength="31"
    android:layout_marginBottom="30dp" />

<Button
    android:id="@+id/button"
    android:text="@string/button_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:textColor="#FFFFFF"
    android:onClick="convert"
    android:layout_gravity="center" />

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    ads:adSize="BANNER"
    ads:adUnitId="@string/admob_id"
    android:layout_marginTop="50dp"
    />

</LinearLayout>

How do I go about fixing this?
EDIT: I wouldn't bother fixing this, because the ad returns back to normal when the keyboard goes away, BUT Views flicker when the keyboard 'touches' a view.

A: Fixed by adding
 android:windowSoftInputMode="adjustPan"

to AndroidManifest.xml under <activity</>
Answer found here


text:
Q: Constraint check condition adding current date I have tried the following code
CONSTRAINT employees_hire_date_ck CHECK (WHERE hire_date=NULL THEN curr_date ELSE hire_date END)

i need to assign current date if  my column hire_date is null using constraint check condition in sql server

A: Try
CASE WHEN hire_date IS NULL THEN GETDATE()
ELSE
hire_date
END AS hire_date

A: I'd suggest to use a calculated column or a trigger for this purpose.
,employees_hire_date as case when [hire_date] is null
                             then curr_date
                             else hire_date end


text:
Q: Is it possible that enriched iron can "lose" it's enrichness? I am doing Mössbauer spectroscopy at room temperature while using my source as a $^{57}$Co and using as my absorber enriched iron. The result I got for some reason is much more similar to iron than enriched iron, I compared my results to the results that appear in this paper (page 3, table 1) :
http://web.mit.edu/dvp/www/Work/8.14/dvp-mossbauer-paper.pdf
I am trying to think why this can happen. I wonder if is it possible that enriched iron can "lose" it's richness and become with spectrum like iron. The second option that I have is that there is mistake in the laboratory by tagging the matter as "enriched iron" instead just iron.

A: Enrichment means that the abundance of a particular isotope of the material is heightened compared to what you would have in the naturally occurring material. No, that level of enrichment does not change.
Iron oxide has absolutely nothing at a to do with enrichment, but instead, is a chemical compound. Yes, the chemical composition of a material can change over time. In particular, iron can oxidize.
Based on what you write, and based on the standard Mössbauer lab experiment, my guess is that there is a confusion of terms, and a misunderstanding, and that actually you have a block of iron.


text:
Q: Loading Data into Listview (WPF) I'm trying to make a duplicate file detector (related question: Compare adjacent list items).  My general structure is this:

*

*Scan directory and load needed details for each file into a DupInfo object

*Calculate CRCs for any that have a size match with another file

*Display any with matching size and CRCs (and optionally Base Directories), and allow the users to check which they want to delete (both manually, and using a button like "Check all first duplicates").

*Delete the selected files.

I'm having trouble with step 3.  My data from steps 1 and 2 is in a List of DupInfo objects.  Here is the class definition.
public class DupInfo
    {
        public string FullName { get; set; }
        public long Size { get; set; }
        public uint? CheckSum { get; set; }
        public string BaseDirectory { get; set; }
        public DupInfo(FileInfo file, Crc32 crc, int level)
        {
            FullName = file.FullName;
            Size = file.Length;
            CheckSum = crc.ComputeChecksum(File.ReadAllBytes(FullName));
            BaseDirectory = FullName.Substring(0,FullName.NthIndexOf("\\",level));
        }
        public DupInfo(FileInfo file, int level)
        {
            FullName = file.FullName;
            Size = file.Length;
            BaseDirectory = FullName.Substring(0, FullName.NthIndexOf("\\", level));
        }

    }

My question is:

*

*What is the best way to load data into a Listview object from a custom classs (DupInfo) list?

*If a Listview isn't the best tool for displaying my duplicate sets, what is the best?

A: I would use a DataGrid bound to an ObservableCollection<DupInfo>.
<Window x:Class="DataGridDupInfoStack.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid ItemsSource="{Binding items}">

    </DataGrid>
  </Grid>
</Window>

Codebehind:
public partial class MainWindow : Window
{
    public ObservableCollection<DupInfo> items { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        items = new ObservableCollection<DupInfo>();

        items.Add(new DupInfo() { BaseDirectory = "Directory1", CheckSum = 0xFF, FullName = "Info1", Size = 100 });
        items.Add(new DupInfo() { BaseDirectory = "Directory2", CheckSum = 0xFE, FullName = "Info2", Size = 150 });
        items.Add(new DupInfo() { BaseDirectory = "Directory2", CheckSum = 0xFD, FullName = "Info3", Size = 200 });
        this.DataContext = this;

    }
}

And this is your DupInfo class. I've omitted the constructor to deal with it faster.
public class DupInfo
{
    public string FullName { get; set; }
    public long Size { get; set; }
    public uint? CheckSum { get; set; }
    public string BaseDirectory { get; set; }
}

Result:

Update 1:
We don't have AddRange available but define an extenstion method for that:
public static class ExtensionMethods
{
    public static void AddRange(this ObservableCollection<DupInfo> value, List<DupInfo> list)
    {
        foreach (var dup in list)
            value.Add(dup);
    }
}

This is our new version:
public partial class MainWindow : Window
{
    public ObservableCollection<DupInfo> items { get; set; }

    List<DupInfo> initialList { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        items = new ObservableCollection<DupInfo>();
        initialList = new List<DupInfo>();

        initialList.Add(new DupInfo() { BaseDirectory = "Directory1", CheckSum = 0xFF, FullName = "Info1", Size = 100 });
        initialList.Add(new DupInfo() { BaseDirectory = "Directory2", CheckSum = 0xFE, FullName = "Info2", Size = 150 });
        initialList.Add(new DupInfo() { BaseDirectory = "Directory2", CheckSum = 0xFD, FullName = "Info3", Size = 200 });

        items.AddRange(initialList);

        this.DataContext = this;

    }
}

public static class ExtensionMethods
{
    public static void AddRange(this ObservableCollection<DupInfo> value, List<DupInfo> list)
    {
        foreach (var dup in list)
            value.Add(dup);
    }
}

So we are loading our elements from a list .. we can use an array there or whatever else according to your needs.
But pay attention if you change the object on which our reference points to. In that case, you will have to use a DependencyProperty or implement INotifyPropertyChanged.
Your property will look like this:
    public  ObservableCollection<DupInfo> items
    {
        get { return ( ObservableCollection<DupInfo>)GetValue(itemsProperty); }
        set { SetValue(itemsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for items.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty itemsProperty =
        DependencyProperty.Register("items", typeof( ObservableCollection<DupInfo>), typeof(MainWindow), new PropertyMetadata(null));

Update 2:
XAML:
<Window x:Class="DataGridDupInfoStack.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <DataGrid ItemsSource="{Binding items}" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Full Name" Binding="{Binding FullName}" />
                <DataGridTextColumn Header="Size" Binding="{Binding Size}" />
                <DataGridTextColumn Header="CheckSum" Binding="{Binding CheckSum}" />
                <DataGridTextColumn Header="BaseDirectory" Binding="{Binding BaseDirectory}" />
                <DataGridTemplateColumn Header="Mark for deletion">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding Path=ToDelete, UpdateSourceTrigger=PropertyChanged}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Content="Delete" Click="btnDelete_Click"/>
    </StackPanel>
</Grid>
</Window>

Codebehind:
public partial class MainWindow : Window
{

    public ObservableCollection<DupInfo> items
    {
        get { return (ObservableCollection<DupInfo>)GetValue(itemsProperty); }
        set { SetValue(itemsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for items.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty itemsProperty =
        DependencyProperty.Register("items", typeof(ObservableCollection<DupInfo>), typeof(MainWindow), new PropertyMetadata(null));

    List<DupInfo> initialList { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        items = new ObservableCollection<DupInfo>();
        initialList = new List<DupInfo>();

        initialList.Add(new DupInfo() { BaseDirectory = "Directory1", CheckSum = 0xFF, FullName = "Info1", Size = 100 });
        initialList.Add(new DupInfo() { BaseDirectory = "Directory2", CheckSum = 0xFE, FullName = "Info2", Size = 150 });
        initialList.Add(new DupInfo() { BaseDirectory = "Directory2", CheckSum = 0xFD, FullName = "Info3", Size = 200 });

        items.AddRange(initialList);

        this.DataContext = this;
    }

    private void btnDelete_Click(object sender, RoutedEventArgs e)
    {
        foreach (var dup in items.ToList())
        {
            if (dup.ToDelete)
            {
                items.Remove(dup);
            }
        }
    }
}

public static class ExtensionMethods
{
    public static void AddRange(this ObservableCollection<DupInfo> value, List<DupInfo> list)
    {
        foreach (var dup in list)
            value.Add(dup);
    }
}

And your updated DupInfo class:
public class DupInfo : INotifyPropertyChanged
{
    private bool _ToDelete;

    public bool ToDelete
    {
        get { return _ToDelete; }
        set
        {
            _ToDelete = value;
            PropertyChanged(this, new PropertyChangedEventArgs("ToDelete"));
        }
    }

    public string FullName { get; set; }
    public long Size { get; set; }
    public uint? CheckSum { get; set; }
    public string BaseDirectory { get; set; }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

That's about it. Good luck!


text:
Q: Purpose of holding a strong local copy of a delegate variable As part of ResearchKit, I have seen code like this:
- (void)finishWithReason:(ORKTaskViewControllerFinishReason)reason error:(NSError *)error {
    __strong typeof(self.delegate) strongDelegate = self.delegate;
    if ([strongDelegate respondsToSelector:@selector(taskViewController:didFinishWithReason:error:)]) {
        [strongDelegate taskViewController:self didFinishWithReason:reason error:error];
    }
}

What's the purpose of storing a local strong variable pointing to the delegate before calling its method? Is this to prevent the delegate being freed from another thread between the respondsToSelector: check and the method call? Can this happen at all?
If that's the case, why would you want to call the delegate method? Why not let it be freed and perform the no-op that is sending a message to a nil pointer variable?

A: There are Clang warnings that flag messages sent to weak (possibly nil) pointers, and repeatedly accessing weak (possibly nil) pointers. These encourage the developer to reason about "what if this pointer is nil when I'm accessing it?" and "what if this weak reference goes nil after I test for not nil?" and requires temporary strong storage in the calling scope to satisfy the compiler.
Regarding your specific question about whether it's possible for a delegate (or other weakly referenced object) to be freed from another thread in between testing the "if" condition and the next line of code, the answer is yes, as noted in the description accompanying the warning being added to LLVM here:
http://reviews.llvm.org/rL164854
As to the question about why not let the delegate be freed and just have the message be a no op to a nil pointer: the compiler has no way of understanding whether that behavior is safe or intended, and so requires the developer (if you have those warnings enabled) to use a strong reference to the receiving object as a guarantee that the message will succeed as the code implies it is expected to.
More discussion on this in the WWDC 2013 "Advances in Objective-C" session here:
https://developer.apple.com/videos/play/wwdc2013/404/  (around 47:30)
And in the mailing list thread here:
http://lists.apple.com/archives/objc-language/2012/Aug/msg00001.html


text:
Q: Data Type Conversions with SQL and sqlalchemy.types I am creating a table in SQL and sending data to it though some helper functions using python. For my function (call it: submit_to_sql), I send the dataframe, table name, and the data types. That data is then in the table on SQL. However, for one of my columns, I am having trouble figuring out which datatype I should provide.
The values I would like to pass are in the form of a decimal, 00.00. There are 2 significant digits with (in theory) unlimited characteristics before it. What is the correct data type that I should assign my column within my script, such that on SQL, the values display properly?
This is how I defined it at first, but it rounded the values:
# Define Column types in my script
import sqlalchemy
from sqlalchemy import types as types
#... skipping some code for brevity
'Column': types.Numeric()

--Create MyTable in SQL
CREATE TABLE [Table].[TableName](
[Column] [dec] NULL
)


text:
Q: How to achieve functionality of idleBetweenPolls in spring kafka with spring boot(2.1.6 version) I would like to set the polling interval between 2 polls. I know that this can be achieved using spring kafka version- 2.3 above using idleBetweenPolls property setting at container level
But how this feature can be achieved with spring boot version 2.1.6 version of spring kafka ? I could not go higher versions of spring boot.
Help would be greatly appreciated!!
EDIT: Application will consume the messages in batch. So we would like to set the polling interval at 5 min.


text:
Q: ProgressBar Style/Theme Android After modifying the theme for my Activity to display an ActionBar (ActionBarSherlock to be precise), my progress bar changed from:

to:

(Thin blue line).  I need to be able to define the height of the progressbar, which I can't with the Holo theme. How can I specify a theme for my progress bar that's not the same as my activity or what's the other way to fix this?
Thanks!

A: As per i know, You are implementing Android inbuilt progressbar which appear the different in different devices and as per then android version.
If you want to implement the Same for all Devices then put make the custom progressbar. Which appear same for all.
Hope it will help you.
Enjoy.
:)


text:
Q: Break up PHP select menu i´m kind of a noob in php things and i got the following problem:
i got a plugin which helps me making a website with 2 languages. So i tell the plugin which languages i want to have in my contao-backend and then i can use them in the frontend. I can then chose wether i want to be able to switch the language by clicking on a flag or by clicking the language in a select box. But there is no option to just have the languages next to each other without a flag. Just a text like "German Spanish". its always a select box or flags.
I then opened the template for the select box and it tells me this:
<?php
/**
 Menu for switching between languages of a page.
 */

?><form name="<?php echo $this->type;?>" method="post"  style="display:inline"
><select name="language" onchange="this.form.submit();">

<?php foreach ($this->items as $item): ?>
<option value="<?php echo $item['language'];?>" <?php
    if ($item['isActive']) {
        echo ' class="active" selected="selected"';
    } ?>><?php
    echo $this->languages[$item['language']];
?></option>
<?php endforeach; ?></select><input type="hidden" name="REQUEST_TOKEN" value="{{request_token}}" /></form>

(This is the one where i can switch by a select box)
and:
<form name="<?php echo $this->type;?>" method="post"  style="display:inline"
><?php foreach ($this->items as $item): ?><input
    class="language" type="radio" name="language"
    id="language_<?php echo $item['language'];?>"
    onchange="this.form.submit();"
    value="<?php echo $item['language'];?>" <?php
if ($item['isActive']) {echo ' class="active" checked="checked"';} ?>  />
<label for="language_<?php echo $item['language'];?>" <?php
    if ($item['isActive']) {echo ' class="active"';} ?>><img src="<?php
echo 'system/modules/i18nl10n/html/flag_icons/png/'.$item['language'].'.png';?>"
title="<?php echo $this->languages[$item['language']];?>"
alt="<?php echo $this->languages[$item['language']];?>"
/><?php endforeach; ?><input type="hidden" name="REQUEST_TOKEN" value="{{request_token}}"></form>

(this is the one which lets me change the language by clocking on the flag)
....
my question now is if someone knows how i can edit this code in a way that it simply shows me the languages i can chose in a text like "german spanish".
Sorry for my english :P
greetings

A: You can just remove the  tag and replace it with the language name:
(I have also improved the code formatting for better readability)
<form name="<?php echo $this->type;?>" method="post"  style="display:inline">
    <?php foreach ($this->items as $item): ?>
        <input class="language" type="radio" name="language"
             id="language_<?php echo $item['language'];?>"
             onchange="this.form.submit();"
             value="<?php echo $item['language'];?>"
             <?php
                 if ($item['isActive']) {
                     echo ' class="active" checked="checked"';
                 }
             ?>
        />
        <label for="language_<?php echo $item['language'];?>"
            <?php if ($item['isActive']) { echo ' class="active"'; } ?>
        >
            <?php echo $this->languages[$item['language']];?>

    <?php endforeach; ?>
    <input type="hidden" name="REQUEST_TOKEN" value="{{request_token}}">
</form>


text:
Q: Float to fixed length string I was trying to convert float value to a fixed length string. I got an unexpected output when the format is greater than %.6. Sample code and output are below,
public class Test {

    public static void main(String[] args) {
        float a=10.9f;
        System.out.println(String.format("%07.2f", a));
        System.out.println(String.format("%09.4f", a));
        System.out.println(String.format("%011.6f", a));
        System.out.println(String.format("%012.7f", a));
        System.out.println(String.format("%013.8f", a));
    }

}

Output
0010.90
0010.9000
0010.900000
0010.8999996
0010.89999962

Why am I getting 8999996 & 89999962 instead of 9000000 & 90000000?


text:
Q: Custom vs. browser-native scrollbars Including customizable, JavaScript-based scrollbars (and scrolling functionality in general, i.e. bind the control to the mouse scroll wheel) in your webapp can be a great temptation.
However all solutions I could find were developed by individuals (which can equal lack of formal or future support). In addition I fail to remember any mainstream site using them.
In my particular case, no-JavaScript or IE6/odd-browser environments are not intended to be supported.
Should custom scrollbars be avoided nowadays? If not, what's the best option one can choose?

A: If you add your own custom scroll bars, users will have to wait and process it in their minds for a couple of moments -- before they can use it. This isn't always good -- you already have content on your site for users to see and comprehend, let everything else come off as expected.
Always try to make you site EASY to navigate. Beauty should not demand (or activate) cognizance.

A: I think that replacing scroll bars is not a good idea. When you are used to an os and browser - scrolling does not require much input from your brain. Having nicely designed ones is awesome but you will confuse your customers. Is the added value enough to offset the annoynance for the fist few times they use it.

A: My idea is that using custom scrollbars, if remain in the scope of aesthetics, i.e. look like just changing the skin of the default scrollbar, is not a bad idea. Users immediately understand other custom parts of a web page like custom buttons, custom checkboxes, etc. Do you have problem understanding the clickable attribute of vote buttons in stackexchange sites? Or do you have problem interacting with custom input text boxes for tagging questions in stackexchange sites, or Yahoo mail? Scrollbars also can be fast-recognizable by end users, as long as they don't change the layout, or the expected functionality of the browser, for example scrolling in the reverse direction, or creating a circular scrollbar. You're good to go as long as you only change the skin.
However, there are some problems with custom scrollbars that you should consider:

*

*They usually need a considerable amount of time to become cross-browser

*They might not be forward-compatible, i.e. by releasing new versions of browsers, they may break functioning.

*You have to manually implement scrolling behavior. For this item, consider HTML buttons. When you add disabled='disabled' attribute to them, browser simply won't accept clicks or enters anymore on them. However, when you use a <div> element to mimic the behavior of a button, then you should implement disabled behavior on your own. Custom scrollbars also should implement scrolling functionality, which is already implemented by browser.

In spite of the things we say, I recommend you start a hobby project (not production) to experience using and implementing custom scrollbars. See this page for good examples.

A: One very important argument that is always convincing to me when it comes to usability is consistency. You may want to make all the handles in your site look the same, noble goal, but think about how someone uses your app or site. They're not just using yours, they're using loads. In fact, I have got 8 tabs of 6 different websites open right now. I can switch to any tab and still have the same scrollbar, looking the same, no matter where. I always know where I can scroll my content.
So if at all possible, and if it doesn't angry any graphic designer, stick with what people know :) Unless you have a brilliant new idea, which is going to be a new revolution in scrolling!

A: Jacob Nielsen has a great entry on scrollbars and what you should do with them. He specifically recommends not using the OS's scrollbars and warns against horizontal scrolling.


text:
Q: Function to return prime numbers I want to write a function in R which accepts a list of integers and returns only the values which are prime.
So far I have this:
 primefindlist<-function(n){
 return(n[n==2 | all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0)])
 }

But I keep getting an error message when I run the function e.g;
 primefindlist(c(7,11))

Error in seq.default(2, ceiling(sqrt(n)), by = 1) :
    'to' must be of length 1

Anyone got any ideas how to overcome this?
Also the code below tells me if a single integer is prime or not ie is.prime(7) outputs TRUE
is.prime <- function(n) n == 2L || all(n %% 2L:ceiling(sqrt(n)) != 0)

A: The function is not vectorized. Try
primefindlist<-function(x){
  return(x[x==2 | sapply(x, function(n)all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0))])
}

or
primefindlist<-function(n){
  return(n[n==2 | all(n %% seq(2,ceiling(sqrt(n)),by=1) !=0)])
}
vPrimefindlist <- Vectorize(primefindlist, vectorize.args = "n")
vPrimefindlist(c(7,11))

A: How about using isprime from the gmp library?
myPrimes <- function(x) {x[which(isprime(x)>0)]}

Here are some tests:
set.seed(33)
randSamp <- sample(10^6,10^5)

system.time(t1 <- myPrimes(randSamp))
user  system elapsed
0.07    0.00    0.08

system.time(t2 <- primefindlist(randSamp))
user  system elapsed
7.04    0.00    7.06

all(t1==t2)
[1] TRUE

If you are interested, the isprime function implements the Miller-Rabin primality test.  It is fairly easy to write this algorithm yourself if you are determined to not use any external libraries. Rosetta Code is a good place to start (there currently isn't an R implementation yet).


text:
Q: RN version 0.55.2 appear "React Native version mismatch" this is error pic
I want to Integrate react native into existing app. I have done anything by https://facebook.github.io/react-native/docs/integration-with-existing-apps.html, but when I run the native app with Xcode, the result is

[error][tid:com.facebook.react.JavaScript] React Native version mismatch.

I try to resolve it with google , but I can't do it!
Environment:
leecodeMacBook-Pro-5:MyApp wj$ react-native info
    Scanning folders for symlinks in /Users/wj/workspace/demo/MyApp/node_modules (10ms)
    OS: macOS High Sierra 10.13.3
Node: 9.11.1
Yarn: 1.5.1
npm: 5.6.0
Watchman: 4.9.0
Xcode: Xcode 9.3 Build version 9E145
Android Studio: 3.0 AI-171.4443003

Packages: (wanted => installed)
react: 16.3.1 => 16.3.1
react-native: ^0.55.2 => 0.55.2

A: If you trying to upgrading your RN did you follow the update guide?
https://facebook.github.io/react-native/docs/upgrading.html
If you did and still seeing the error
did you try to clear cache?
https://gist.github.com/jarretmoses/c2e4786fd342b3444f3bc6beff32098d


text:
Q: How to capture keybd events at document level, but let editable fields have their events? EDIT: Since nobody has responded, I'll try to restate my question more succinctly.  When handling keystrokes on a browser page (like left/right/space) how does one tell whether the keystroke is going to be handled by the element on the browser page that has focus or whether it's not going to be handled by that object and it would be OK to handle it globally?  Ideally, you'd let the focus object see the keystroke and be able to tell whether it handled it or not.  If not, you could then process it yourself.  If it handled it, you would do nothing with it (assuming that the focus object has a more important use for the keystroke).
Here's a typical example in a non-browser setting.  Imagine you have a Windows dialog that has a bunch of typical dialog box controls, a couple buttons and a rich edit control in it.  If you're in a typical dialog box control, the Enter key on the keyboard will activate the OK button on the dialog and accept the dialog's changes.  If you're in the rich edit control, the Enter key will enter a new line.  The dialog box is somehow able to tell whether the current control in the dialog box wants to process the enter key or whether it should be handled globally.
In my particular browser case, I'm using YUI2 event handling to capture keystrokes at the document level so that I can allow the user to use the left/right arrows on the keyboard to move through a slideshow on the page without having to explicitly set the focus to any particular element on the page (a feature my users like).  But, if the page contains any editable fields, I want those left/right arrows to be processed by that field on the page and not by my slideshow.  I'm looking for an elegant way to do that.
I realize I can look at the original event target and "try" to figure out if that target is capable of handling the left/right arrows (input, textarea, contenteditable, etc...), but I was hoping for a more foolproof method.  Is there any way to handle a keystroke at the document level ONLY when it isn't otherwise handled by an object on the web page.  In my YUI keyboard handler now, I'm getting all keyboard events, even ones that will actually be handled by the target object.
Here's what my code looks like now and I'm looking for a more elegant way to do this that doesn't require the ObjectWantsKeys function which is somewhat brittle:
JF.Slideshow.prototype._HookupKeyNav = function () {
    var k = YAHOO.util.KeyListener;
    var key = k.KEY;
    // see if keyboard handling is enabled or not
    if (((this._config.keyboardNav == "auto") && (JF.SlideshowCnt <= 1)) || (this._config.keyboardNav == "on")) {
        this._keyListener = new YAHOO.util.KeyListener(
        document, {
            ctrl: false,
            shift: false,
            alt: false,
            keys: [key.LEFT, key.RIGHT, key.SPACE]
        }, {
            fn: this._HandleKeys,
            scope: this,
            correctScope: true
        });
        this._keyListener.enable();
    }
}
JF.Slideshow.prototype._HandleKeys = function (type, args, obj) {
    var keyCode = args[0];
    var event = args[1];
    var target = event.srcElement || event.target;
    if (JFL.ObjectWantsKeys(target)) return; // if the current focus object wants keystrokes, then we shouldn't process them
    var key = YAHOO.util.KeyListener.KEY;
    switch (keyCode) {
    case key.LEFT:
        this.Back();
        break;
    case key.RIGHT:
        this.Forward();
        break;
    case key.SPACE:
        this.StartStopToggle();
        break;
    default:
        break;
    }
}
JFL.ObjectWantsKeys = function (o) {
    // list of HTML object types that want the keystroke if they have focus
    var list = {
        "input": true,
        "textarea": true
    };
    try {
        // unfortunately o.contentEditable set to an empty string means it is editable so we need this more complicated comparision
        if ((typeof o.contentEditable !== "undefined") && (o.contentEditable === "true" || o.contentEditable === true || o.contentEditable === "")) {
            return (true); // focus object is editable
        }
        if (o.tagName && list[o.tagName.toLowerCase()]) {
            return (list[o.tagName.toLowerCase()]); // focus object can take keys
        }
    } catch (e) {}
    return (false);
}

A: I solved this by checking the type of element that had focus:
var tag = document.activeElement.tagName;
if (tag == "INPUT" || tag == "TEXTAREA")
  return;

This wasn't perfect because I also didn't want the KeyListener to handle keystrokes when a YAHOO.widget.Dialog was displayed (which would give a tag name of "BODY").  I had to throw something together using a YAHOO.widget.OverlayManager and check the active dialog.  If it's null I process the keystroke.
It's not elegant and I'm hoping for a better solution.  I posted a message at the YUI forums:
http://yuilibrary.com/forum/viewtopic.php?p=26413
If I get an answer there it may help you as well.


text:
Q: Count Total PL/SQL Code Lines without Comments I was tasked to modify a Package and while doing so, i commented out the lines to be modified to retain versioning and commented it with Version Numbers.
Now that i'm done modifying the Package, i want to compare the total number of code lines of the Original the Modified Scripts without the line comments.
Is there any way this feature is available in SQL Developer / Notepad ++ / PL/SQL Developer or any other freeware / online tool?
Thanks in Advance!

A: Do you have backup package and clone package.then You cna use "Beyond Compare" tool.it is very useful to comapre the text files. you can open both backup package and clone package then easily to find the changes in your code.
Best Regards

A: I use Microsoft Visual Studio Source Control Explorer to compare versions either on the server or on the file system.  I recommend it over many other compare tools.  Attached is an example image.

A: Based on one of my posts -
SQL/Regex Challenge/Puzzle: How to remove comments from SQL code (by using SQL query)?

create or replace package dmarkovitz.old_code as
1
2       2
3
/* yada yada yada */
4
5  '-- not a comment '
6
-- bla bla bla
7
8  "/* also not a comment"
9
10 'and again, not a comment */'
end;
/

create or replace package dmarkovitz.new_code as
1
2  /* bla bla bla */     2
-- 3
/* yada yada yada */
4
5  '-- not a comment '
/*6
-- bla bla bla
7
8  "/* also not a comment"
9 */
10 'and again, not a comment */'
end;

select      owner
           ,object_name
           ,object_type
           ,ddl
           ,uncommented_ddl
           ,regexp_count (uncommented_ddl,chr(10))  as lines

from       (select      owner
                       ,object_name
                       ,object_type
                       ,ddl
                       ,regexp_replace (ddl,'(''.*?''|".*?")|/\s*\*.*?\*/\s*|\s*--.*?(?=$|\z)','\1',1,0,'mn') as uncommented_ddl

            from       (select      owner
                                   ,object_name
                                   ,object_type
                                   ,dbms_metadata.get_ddl (object_type,object_name,owner)   as ddl

                        from        all_objects

                        where       owner       = 'DMARKOVITZ'
                                and object_name in ('OLD_CODE','NEW_CODE')
                                and object_type = 'PACKAGE'
                        )
            )
;

OWNER         OBJECT_NAME    OBJECT_TYPE    DDL     UNCOMMENTED_DDL    LINES
----------    -----------    -----------    ----    ---------------    -----
DMARKOVITZ    NEW_CODE       PACKAGE        CLOB    CLOB               8
DMARKOVITZ    OLD_CODE       PACKAGE        CLOB    CLOB               13

OLD_CODE uncommented_ddl
  CREATE OR REPLACE PACKAGE "DMARKOVITZ"."OLD_CODE" as
1
2       2
3
4
5  '-- not a comment '
6
7
8  "/* also not a comment"
9
10 'and again, not a comment */'
end;

NEW_CODE uncommented_ddl
  CREATE OR REPLACE PACKAGE "DMARKOVITZ"."NEW_CODE" as
1
2  2
4
5  '-- not a comment '
10 'and again, not a comment */'
end;


text:
Q: Algorithms to automatically determine optimal responsive image breakpoints Cloudinary has published a tool that automatically generates breakpoints for responsive images: http://www.responsivebreakpoints.com/
The breakpoints and images are tuned using these knobs:

*

*The resolution range (ex. 200 px to 1400px)

*The minimum file size difference between each image

*The maximum number of images to generate

*Art direction by cropping the image to different aspect ratios

The problem of art direction can be easily solved by using smart crop tools and face detection. One example would be smartcrop.js.
The first 3 conditions are further complicated by:

*

*Different image formats will have different file-size to image-size ratios.

*Depending on the image itself, it will also have different file-size to image-size ratios.

The only way I can think of is to generate a few breakpoints, generate those images and then check the constraints and adjust and regenerate as needed. However, this brute-force approach seems to be extremely inefficient. Are there any algorithms for generating the responsive breakpoints (without the brute-forcing), given these conditions?

A: My thoughts about the points:

*

*The resolution range (ex. 200 px to 1400px)

*The minimum file size difference between each image

*The maximum number of images to generate

It might not be correct all the time, but I would make the assumption that higher resolution always results in bigger file size. With other words the size of the file is a strong monotone growing function with the parameter image size.
This might not be true for all compression algorithms, but a quite good approximation for all of them.
With this assumption you can get any file size by a binary search in the image size space. This means You do not have to create that many different images to meed your needs.
Remark:
They seam not to use different image formats for the generated images. So the process is always done with only one file format.


text:
Q: Service with AlarmManager running always every minute I'm trying to set a service run every 5 minutes in background. But it's acting weird:
At onCreate of Main activity, I'm scheduling it to run every 5 minute:
   public void scheduleAlarm(Context context) {
        Intent intent = new Intent(context, AdSyncStartReceiver.class);
        final PendingIntent pIntent = PendingIntent.getBroadcast(context, AdSyncStartReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        long firstMillis = System.currentTimeMillis(); // alarm is set right away
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                firstMillis,
                5 * 60 * 1000, // 5 min
                pIntent);
    }

AdSyncStartReceiver.java:
public class AdSyncStartReceiver extends BroadcastReceiver {

  // Triggered by the Alarm periodically (starts the service to run task)
  @Override
  public void onReceive(Context context, Intent intent) {
    Intent i = new Intent(context, AdSyncService.class);
    context.startService(i);
  }
}

AdSyncService.java
public class AdSyncService extends IntentService {
    public AdSyncService() {
       super("AdSyncService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
       // Do the task here
       Log.i("AdSyncService", "AdSyncService Service running");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Manifest:
<receiver
    android:name=".AdManager.AdSyncStartReceiver"
    android:process=":remote" >
</receiver>

<receiver android:name=".AdManager.BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<service
    android:name=".AdManager.AdSyncService"
    android:exported="false" />

Logs, it's running every minute:
10-28 02:46:51.405    6820-7043/pack I/AdSyncService﹕ AdSyncService Service running
10-28 02:47:04.198    6820-7052/pack I/AdSyncService﹕ AdSyncService Service running
10-28 02:48:04.199    6820-7099/pack I/AdSyncService﹕ AdSyncService Service running
10-28 02:49:04.196    6820-7182/pack I/AdSyncService﹕ AdSyncService Service running

I'm trying to run every 5 minute to test but it's always running every minute. What's the problem?
I followed this tutorial exactly:
https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks

A: Try this, it worked for me:
 alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60 * 1000 * 5, pendingIntent);


text:
Q: Markov chain transition matrix outputing only '0.000's I am attempting to produce a transformation matrix based on the first column of a csv file. There are 59 possible states, which are integers in a list.
At the moment my output is simply a long list of '0.000s' - in the correct size as far as I can tell (59*59), but without the weights that it should have.
The data is definitely in the activities list, because it can be printed separately.
import csv
data = open('file.csv')

csv_data = csv.reader(data)
data_lines = list(csv_data)

activities = []

for row in data_lines[:5954]:
    activities.append(row[0])

activities = list(map(int, activities))

def transition_matrix(activities):
    n = 59 #number of states

    m = [[0]*n for _ in range(n)]

    for (i,j) in zip(activities,activities[1:]):
        m[i][j] += 1

    #now convert to probabilities:
    for row in m:
        s = sum(row)
        if s > 0:
            row[:] = [f/s for f in row]
    return m

t = [activities]
m = transition_matrix(t)
for row in m: print(' '.join('{0:.3f}'.format(x) for x in row))

A: You are declaring t as a list which contains activities.
However, activities is already a list.
This means that your function won't run as expected as you're not passing data in the right format. To fix this, just use t = activities, or just directly pass activites into transition_matrix() without using t.

A: It looks like you're creating a nested list when you assign t. Try removing the brackets around [activities].


text:
Q: Sencha Architect 4 - ExtJS 6.5 -> Dreamfactory 2.9 Authentication Session Token I got a little bit stuck and I would like to ask your advice, I am trying to setup a login window // authentication using DreamFactory in Sencha Architect however I am pretty much a beginner.
My current Code is:
var username = Ext.getCmp('usr').getValue(),
password = Ext.getCmp('pwd').getValue();

Ext.Ajax.defaultHeaders = {
'X-DreamFactory-Api-Key' : 'xyz',
'Content-Type' : 'application/json'
};

Ext.Ajax.request({
url: 'http://dreamfactoryaddy:8080/api/v2/user/session',
withCredentials: true,
email: username,
password: password,
cors: true,

success: function(response) {
    var obj = Ext.decode(response.responseText);
    Ext.Ajax.defaultHeaders = {
        'X-DreamFactory-Api-Key' :
'xyz', 'Content-Type' : 'application/json', 'X-DreamFactory-Session-
Token': obj.session_token
    };
    console.log(obj);
},

failure: function(response) {
        console.log(response.responseText);
}

});

I receive this error:
{"error":{"code":401,"context":null,"message":"There is no valid session for the current request.","status_code":401}}

http://prntscr.com/hate2e
Can you give me some advice how to handle Sessions properly?
UPDATE 2:
            var username = Ext.getCmp('usr').getValue(),
                password = Ext.getCmp('pwd').getValue(),
                headers = {
                    'X-DreamFactory-Api-Key' : 'xyz',
                    'Content-Type' : 'application/json'
                };

            Ext.Ajax.setDefaultHeaders(headers);
            Ext.Ajax.request({
                url: 'http://chalton.swiftmedia.ca:8080/api/v2/user/session',
                withCredentials: true,
                jsonData: {
                    "email" : username,
                    "password" : password
                },
                cors: true,

                success: function(response) {
                    var obj = Ext.util.JSON.decode(response.responseText),
                        newheaders = {
                            'X-DreamFactory-Api-Key' : 'xyz',
                            'Content-Type' : 'application/json',
                            'X-DreamFactory-Session-Token': obj.session_token
                        };
                    console.log(response.responseText);
                    Ext.Ajax.setDefaultHeaders(newheaders);
                },

                failure: function(response) {
                    console.log(response.responseText);
                }

            });
        },

A: If you check the browser console, you may find that the defaultHeaders are not correctly applied to your ajax requests.
I had the very same issue with arbitrary other headers I wanted as the default headers. Ext.Ajax.defaultHeaders = x just doesn't work, Ext.Ajax.setDefaultHeaders(x) does.


text:
Q: My applets do not display in my browser (Google Chrome) I had an issue a couple of days ago with Java applets.  Here is my code:
Hello.java class file
//Reference the required Java libraries
 import java.applet.Applet;
 import java.awt.*;
 import java.io.*;

 //The applet code
  public class Hello extends Applet {

     public static void main(String[] args)  {
       //new Main();
       System.out.println("Hello worlds");
    }
  }

And the HTML file applet.html

 <TITLE> My First Java Applet </TITLE>

Here's my first Java Applet@@@@:

 <applet code ="Hello.class"  width="200" height ="200"> APPLET </applet>

and I had taken the issue,
 "Error,click for details."

and another issue I take when I'm trying to run my applet from command prompt is
C:\Users\Andreas>cd C:\xampp\htdocs\mysite\
C:\xampp\htdocs\mysite>appletviewer applet.html

after I click enter the appletviewer window is opening but does not displaying anything.It just says: "Applet started"
I Have installed the latest version of java and Java SDK,
and I also double-check  this in java.com.
I'm running this locally.
Can anyone help me? What I'm missing? In other websites which are running java applets its just asking for permission at the top of the browser and that's all.
I'm trying to get this to work in order to write code about multitasking (any other ideas about multitasking for a website?)

A: In the Applet class, main() method is not there. Please try to execute the below example:-
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet{

public void paint(Graphics g){

g.drawString("hello world" , 25, 50);

  }
}

-

<title>Applet application</title>

<applet code="HelloWorldApplet.class" width="320" height="120">

If the browser is not java enabled then this message will be printed.

</applet>


text:
Q: Why are persistent splay trees particularly useful in functional programming? On the Splay Trees Wikipedia page it is said (in the Advantages section):

Possibility of creating a persistent data structure version of splay trees—which allows access to both the previous and new versions after an update. This can be useful in functional programming, and requires amortized O(log n) space per update.

Why is that? How is functional programming particulary making use of persistent Splay trees?

A: Your question seems to come from a persistently unfortunate bit of terminological confusion. A better phrase might be purely functional, i.e., functional programming without destructive mutation. The confusion likely arises from the fact that immutable, persistent data structures are more common in functional programming as a whole, for a variety of reasons.
In short, you can probably read that phrase as "creating persistent splay trees can be useful when programming with only immutable data structures", which borders on the tautological.

A: One of the driving goals of modern Functional Programming is a better management of state, preferrably using as little of it as necessary, since stateful programs must carefully execute the commands in the correct sequence to avoid errors.
Persistent data structures are great precisely because they do not use mutable state, allowing them to be used in pure and immutable computations
//mutable tree
var t = new_tree();
add(t, 1);
add(t, 2);
//the tree has now changed so if anyone was depending on the old value
//we will now have a problem

//persistent tree
var t = new_tree();
var t2 = add(t, 1);
var t3 = add(t2, 2);
//t1 and t2 have not changed

The quote you pointed out is just emphasizing that persistent data structures are commonly used (and preferred) in pure functional programming. There is nothing particular about splay trees in this case.

A: I'd even argue the opposite, splay trees are less comfortable to work with in functional programming because you need to return the new tree even after every find operation and keep track of the last tree for almost all operations.
Also, all the search trees I know of can be directly used functionally with O(log n) additional space per operation.
I suppose the only interesting fact in that sentence of that the memory requirement per operation stays O(log n)  amortized, even though we restructure the tree all the time, but notice that now we pay that space price even for searches.


text:
Q: Apache Spark - How to define a UserDefinedAggregateFunction after 3? I'm using Spark 3.0, and in order to use a user-defined function as a window function, I need an instance of UserDefinedAggregateFunction. Initially I thought that using the new Aggregator and udaf would solve this problem (as shown here), but udaf returns a UserDefinedFunction, not a UserDefinedAggregateFunction.
Since Spark 3.0, UserDefinedAggregateFunction is deprecated, as stated here (despite being possible to still find it around)
So the question is: is there a correct (not deprecated) way in Spark 3.0 to define a proper UserDefinedAggregateFunction and use it as a window function?

A: In Spark 3, the new API uses Aggregator to define user-defined aggregations:

abstract class Aggregator[-IN, BUF, OUT] extends Serializable:
A base class for user-defined aggregations, which can be used in
Dataset operations to take all of the elements of a group and reduce
them to a single value.

Aggregator brings performance improvements comparing to deprecated UDAF. You can see the issue Efficient User Defined Aggregators.
Here's an example on how to define a mean Aggregator and register it using functions.udaf method:
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
import org.apache.spark.sql.expressions.Aggregator

val meanAgg= new Aggregator[Long, (Long, Long), Double]() {

    def zero = (0L, 0L) // Init the buffer

    def reduce(y: (Long, Long), x: Long) = (y._1 + x, y._2 + 1)

    def merge(a: (Long, Long), b: (Long, Long)) = (a._1 + b._1, a._2 + b._2)

    def finish(r: (Long, Long)) = r._1.toDouble / r._2

    def bufferEncoder: Encoder[(Long, Long)] = implicitly(ExpressionEncoder[(Long, Long)])

    def outputEncoder: Encoder[Double] = implicitly(ExpressionEncoder[Double])
}

val meanUdaf = udaf(meanAgg)

Using it with Window:
val df = Seq(
  (1, 2), (1, 5),
  (2, 3), (2, 1),
).toDF("id", "value")

df.withColumn("mean", meanUdaf($"value").over(Window.partitionBy($"id"))).show
//+---+-----+----+
//| id|value|mean|
//+---+-----+----+
//|  1|    2| 3.5|
//|  1|    5| 3.5|
//|  2|    3| 2.0|
//|  2|    1| 2.0|
//+---+-----+----+


text:
Q: How to save value of a string even after the activity/app is destroyed? I have 2 int in my navigation drawer, the value of whom changes upon clicking different button on different locations in the app.
I got the code to successfully  increment and update them, but the problem is that they got reset when I open the app after closing or exiting it.
How can I make them stay there after getting updated?
If you want any code from my app, then please tell me.
Sorry for bad formatting of the question, but I have no idea how to do this and hence I haven't posted any code.

A: You must save the info in a persistent storage.
You can use SharedPreferences.
SharedPreferences prefs= getSharedPreferences("aName", MODE_PRIVATE);
 //save the value
        prefs.edit()
                .putInt("nameOfTheValue", theValue).apply();
        // get the data
        prefs.getInt("nameOfTheValue", aDefaultValue);

A: You should save them as User SharedPreferences in onDestroy method.
  public void onDestroy() {
     super.onDestroy();
     SharedPreferences settings;
     settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);
     //set the sharedpref
      Editor editor = settings.edit();
      editor.putInt("FIRST_INT", firstIntValue);
      editor.putInt("SECOND_INT", secondIntValue);
      editor.commit();
    }

And then you can get them back wen needed:
  SharedPreferences settings;
  settings = getSharedPreferences("TWO_INT_SAVING", Context.MODE_PRIVATE);

  //get the sharepref
  int firstInt = settings.getInt("FIRST_INT", 0);
  int secondInt = settings.getInt("SECOND_INT", 0);


text:
Q: Enumerating paragraph with manual number I have just started using Latex today and I have been looking into how to manually number the paragraphs inside enumeration. I am writing up the solutions to the problems which are not in consecutive order; what I am trying to get looks like the following:
Chapter 8
8.3  Let F = 492 N, x = 33, y = 42
     Since we know the magnitude...
     (a)  ...
          ...
     (b)  ...
          ...

8.12 We know the resultant of two vectors ...
     A graphical sketch of ...
                     +--------+
                     |        |
                     | Figure |
                     |        |
                     +--------+
8.15 ...

In the above representation, I would like to have the ability to:

*

*manually number the problems of each enumerated paragraph (8.3 -> 8.12 -> 8.15)

*and to indent each of the whole paragraph as shown above

I have tried the following code but it automatically numbers each item for me in an increasing order. Could anyone point me how to manually number each item/each paragraph?
\begin{enumerate}
\item
Let $F = 492 N, x = 33, y = 42$\\
Since we know the magnitude...

\item ...

\item ...
\end{enumerate}

A: You can use the optional argument of \item:
\documentclass{article}

\begin{document}
\begin{enumerate}
\item[8.2]
Let $F = 492 N, x = 33, y = 42$\\
Since we know the magnitude...

\item[8.12] ...

\item[8.15] ...
\end{enumerate}
\end{document}


text:
Q: What type of PCB material should I use? I'm making my first  4 layer PCB (1 signal, 2 GND plane, 3 PWR plane, 4 signal) with impedance control. I was checking the layer stack up for Altium to make sure the thickness and dielectric constant (dk) were correct and I realized they were not. Checking a couple of manufacturers I quickly realized I don't know what I'm doing.
My experience is low speed PCBs that work fine with FR4 on 2 layers and no impedance control. It looks like the dk varies by material and thickness. Asking the manufacturers what dk value their PCB material has just leads to "for what PCB material" question. I don't know, FR4 ok? LOL.
The design I'm working on has an Infineon psoc62, an eMMC memory and a GPS module. The only controlled impedance traces are for the eMMC, GPS antenna (both 50 Ω impedance) and USB 2.0 ports (one on the MCU and another from the GPS module, both 90 Ω impedance). The eMMC will have the highest clock source (from the MCU) at 45 MHz. I see different types of PCB material and their properties but I'm baffled.
How do you know what type of material to use? Is FR4 material ok for the 50 Ω and 90 Ω impedance? Is there a range for the value of the dielectric constant (dk) for a specific material and if so how do I know what to set it up in the stack up?

A:
How do you know what type of material to use?

For sub 100MHz signals it's not as critical to have a controlled impedance and FR4 is fine.  zThe main thing is knowing what the dielectric permittivity \$ \epsilon_r \$ of the material is. Once you know what the range AND the layer stackup is you can plug that in to a tool (like saturn PCB toolkit) and calculate impedance for single pair transmission lines or diff pairs. (you need to know the height above the reference and \$ \epsilon_r \$.
You can find the dielectric permittivity and the stackup by asking the PCB manufacturer.
For signals that are in the 30-50MHz you probably won't have to worry much if you keep the traces short and also watch capacitance (of both traces and ports). It's also a good idea to avoid vias with these signals if possible.
If not you may need to leave a terminating SMT pad for a resistor to reduce reflections if you see them on those lines.

A: FR4 material is a composite material, not originally designed for controlled impedance, which is why the dk specifications are somewhat loose. However, it can be used for GHz designs (it's the staple for 2.45GHz WiFi), if the application is tolerant enough. This means almost all applications, so RF or high speed logic signals between modules and ICs. Do not use it for microwave filters, or metrology, for which you would use a proper RF material like RO4350.
A good rule of thumb for 50 ohms microstrip (trace above ground) on FR4 is for the track to be twice as wide as the substrate is thick.
Avoid using a pre-preg layer as the substrate, as if FR4 is poorly specified, pre-preg is even worse. Most board fabs will try to sell you a central core with two outer foils, as it's often a slightly cheaper build. Insist on two cores stuck together, this gives you core FR4 between the top signal layer and the ground reference plane below.


text:
Q: Sequelize : how to create data with a nested table relationship using include I want to create nested table data using User.create() and includes. The table relationships are:
User.hasMany(models.Project, { onDelete: "CASCADE" });
User.hasMany(models.Task, { onDelete: "CASCADE" });
Project.belongsTo(models.User);
Project.hasMany(models.Task, { onDelete: "CASCADE" });
Task.belongsTo(models.User);
Task.belongsTo(models.Project);

This is what I have tried:
await models.User.create(
    {
      username: "un",
      projects: [
        {
          name: "project1",
          tasks: [
            {
              text: "task1",
            },
            {
              text: "task2",
            },
          ],
        },
      ],
    },
    {
      include: [{ model: models.Project, include: [{ model: models.Task }] }],
    }
  );

But this is the generated SQL:
Executing (default): INSERT INTO "users" ("id","username","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3) RETURNING *;
Executing (default): INSERT INTO "projects" ("id","name","deleted","createdAt","updatedAt","userId") VALUES (DEFAULT,$1,$2,$3,$4,$5) RETURNING *;
Executing (default): INSERT INTO "tasks" ("id","text","completed","deleted","createdAt","updatedAt","projectId") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6) RETURNING *;
Executing (default): INSERT INTO "tasks" ("id","text","completed","deleted","createdAt","updatedAt","projectId") VALUES (DEFAULT,$1,$2,$3,$4,$5,$6) RETURNING *;

The problem is that it is missing the User:Task relationship on inserting the tasks. You can see that the tasks inserted were given an associated projectId, but not a userId. This has created an a:b:c relationship rather than the desired a:b, b:c, a:c


text:
Q: How to disable CTRL press in power bi iframe We are trying to build a writeback functionality in PowerBI. As a part of it as the user selects/clicks on a visual, we keep tracking it. Let's say the user presses Ctrl and selects several data points on 2 visuals, the data selected of PowerBI js returns the last visual on which the user has clicked.
While trying to capture the keypress we are facing a CORS issue. Is there a way by which we can capture all the selected filters?

A: Currently capturing selected data points from multiple visuals is not supported. You can select several data points in each visual using the Ctrl key.
For example, lets say you have two visuals: visual 1 and visual 2.

*

*Click Ctrl and select a data point in visual 1 -> one data point in visual 1 is selected.

*Click Ctrl and select a data point in visual 2 -> one data point in visual 2  is selected.

*Click Ctrl and select a data point in visual 1 -> two data points in visual 1  are selected.

*Click Ctrl and select two data points in visual 2 -> three data points in visual 2 are selected.


text:
Q: How to copy Event Listener's attached anonymous function? I'm trying to build a Tampermonkey user script that modifies the functionality of an event applied to an element.
Let's say the source website have this:

…

And within the source website's Javascript:
document.getElementById("item_1").addeventlistener("click", function(){
    // Source website's lines of code for the function to be applied on click event occurrence.
}

I know that I can easily overwrite the event functionality by using:
document.getElementById("item_1").addeventlistener("click", function(){
    // My lines of code here
}

But what I'm looking for is to first copy the anonymous function that was previously passed-in to the addEventListener method. I want to copy it to a temporary variable so that I can retrieve the original Event Listener attached function back.
There's another question having an answer telling that copying functions of Event Listeners is impossible. I believe this may be possible somehow as I think that the passed-in anonymous function is stored within the heap with some reference. If I'm able to get that reference, I will be able to get a copy for the code to another variable.
I don't have access to edit the source's script. I know that I could have refactored the code to handle event population. Also, I know I can do some manipulation on the source's JavaScript, but I don't want to go this way as my user script code will get too complicated and if the source code was changed a little, my code will be broken easily. I want to easily copy the Event Listener function to a variable I have.


text:
Q: Removing HTML until a certain point in a file The problem is pretty simple: I have a few thousand HTML files that I'd like to loop through and remove everything until the second instance of this:
<!--------------------------------------------------------->
I know how to load files, write loops, etc., in Python, but all my attempts to parse the files as text are failing.

A: Your can try split the string, and get the stuff after the second occurrence.
source = "YOUR HTML FILE CONTENT"
print source.split('<!--------------------------------------------------------->')[2:]


text:
Q: Swift instantiateViewController without storyboard ?programming Is there any way instantiateViewController  without using storyboard ? I did not use storyboard.

A: Yes you can init you're controller with nib name:
let main = UIViewController(nibName: "Second", bundle: nil)

Also you can call constructor without parameters like:
let main = UIViewController()


text:
Q: Inconsistent accessibility: field type is less accessible I have 2 classes that references a list inside the main game function. Classes Block and MovingPlatform both have a list that holds all the objects.
public List<Block> Blocks;
public List<MovingPlatform> Platforms;

I also have a Collision Manager class which uses the 2 lists to see if platforms is colliding with a block and then make platforms go another direction.
I then transfer over the lists to the class Collision Manager:
public class Collision_Manager
{
    Game1 game1;

    public void Initialize(Game1 game1)
    {
        this.game1 = new Game1();
    }

    public void Update(GameTime gameTime, Game1 game1)
    {
        this.game1 = game1;

        for (int i = 0; i < game1.Blocks.Count; i++)
        {
            Rectangle BlockBounds = new Rectangle(
                (int)game1.Blocks[i].Position.X,
                (int)game1.Blocks[i].Position.Y,
                game1.Blocks[i].Texture.Width,
                game1.Blocks[i].Texture.Height);

            Rectangle top = new Rectangle((int)BlockBounds.X + 5, (int)BlockBounds.Y - 10, BlockBounds.Width - 10, 10);
            Rectangle bottom = new Rectangle((int)BlockBounds.X + 5, (int)BlockBounds.Y + BlockBounds.Height, BlockBounds.Width - 10, 10);
            Rectangle left = new Rectangle((int)BlockBounds.X - 10, (int)BlockBounds.Y + 5, 10, BlockBounds.Height - 10);
            Rectangle right = new Rectangle((int)BlockBounds.X + BlockBounds.Width, (int)BlockBounds.Y + 5, 10, BlockBounds.Height - 10);

            for (int b = 0; b < game1.Platforms.Count; b++)
            {
                Rectangle PlatformBounds = new Rectangle(
                (int)game1.Platforms[i].Position.X,
                (int)game1.Platforms[i].Position.Y,
                game1.Platforms[i].Texture.Width,
                game1.Platforms[i].Texture.Height);

                if (top.Intersects(new Rectangle(PlatformBounds.X, PlatformBounds.Y, PlatformBounds.Width, PlatformBounds.Height)) && game1.Blocks[i].BlockState == 3)
                {
                    game1.Platforms[i].Thing = false;
                }

                if (bottom.Intersects(new Rectangle(PlatformBounds.X, PlatformBounds.Y, PlatformBounds.Width, PlatformBounds.Height)) && game1.Blocks[i].BlockState == 3)
                {
                    game1.Platforms[i].Thing = true;
                }

                if (left.Intersects(new Rectangle(PlatformBounds.X, PlatformBounds.Y, PlatformBounds.Width, PlatformBounds.Height)) && game1.Blocks[i].BlockState == 3)
                {
                    game1.Platforms[i].Thing = false;
                }

                if (right.Intersects(new Rectangle(PlatformBounds.X, PlatformBounds.Y, PlatformBounds.Width, PlatformBounds.Height)) && game1.Blocks[i].BlockState == 3)
                {
                    game1.Platforms[i].Thing = true ;
                }
            }
        }
    }
}

For some reason I am getting the error: Inconsistent accessibility: field type 'System.Collections.Generic.List<Game.Block>' is less accessible than field 'Game.Game1.Blocks'
Inconsistent accessibility: field type 'System.Collections.Generic.List<Game.MovingPlatform>' is less accessible than field 'Game.Game1.Platforms'
How do I fix my problem?

A: The Block and Platform classes must be public because you use them in public fields.
Or you can use the same or a lower accessor for the property as the one you use in your class.
For example if your class is declared internal use also internal for your field.

A: Your classes Block and MovingPlatform have lesser access than your public fields List<Block> Blocks and List<MovingPlatform> Platforms.
You probably haven't defined any access specifiers with your classes Block and MovingPlatform, so they are considered internal by default, which is less accessible then public.
You can fix the issue by making those classes as public or you can have your fields marked as internal. You should decided your access to properties/classes according to your requirement. You may see Access Modifiers (C# Reference)


text:
Q: Put Postgres query result in array How can I put an sql query result in a string array with Postgres?
I have some attributes in the column 'zone' of the table 'mytable' and I must put them all in a String[] areas;
This is my first request, sorry if I made some format mistake.

A: You can use an array constructor:
select array(
select zone
from mytable)
as areas;


text:
Q: Is there a VBA to number different sets of data using autofill I am wanting to number sets of data that are separated by an empty row. I am thinking an autofill VBA would be what I am needing but cannot seem to find anything that fits specifically what I am looking to do. The issue I am running into is that the data will vary and will not always have the same exact number of rows in each sequence. Given that, I would like Column A (Count) to increase according to information being in Column C (Last Name) and start over when there is an empty row until the end of the sheet. I have put an example of what I am looking for as the end result below. Thank You!
Count   ID   Last Name First Name
1   344969  Test    Test
2           Test    Test
3   344971  Test    Test
4           Test    Test
5   344973  Test    Test
6   344974  Test    Test
7   344975  Test    Test
8           Test    Test
(Blank Row)
1           Test 2  Test 3
2   200474  Test 2  Test 3
3   200475  Test 2  Test 3
4   200476  Test 2  Test 3
5           Test 2  Test 3
6   200478  Test 2  Test 3
7   200479  Test 2  Test 3
8           Test 2  Test 3
9           Test 2  Test 3
10  200482  Test 2  Test 3
(Blank Row)
1   195959  Test 5  Test 6
2   195960  Test 5  Test 6
3   195961  Test 5  Test 6
4   195962  Test 5  Test 6
5   195963  Test 5  Test 6
6   195964  Test 5  Test 6
7   195965  Test 5  Test 6
8   195966  Test 5  Test 6
9   195967  Test 5  Test 6
10  195968  Test 5  Test 6

I have tried conditional formatting with no luck. I have several other macros in place and would like to add one that performs this function.

A: Something like this might work for you:
Sub countSomething()

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("sheet name")
Dim lrow As Long: lrow = ws.Cells(Rows.Count, "B").End(xlUp).Row 'get last row at the column that will always be populated
Dim R As Long, X As Long: X = 1

For R = 2 To lrow
    If WorksheetFunction.CountA(ws.Cells(R, 1).Resize(1, 4)) = 0 Then 'empty row
        X = 1
    Else
        ws.Cells(R, 1) = X
        X = X + 1
    End If
Next R

End Sub


text:
Q: Использование SQLXML в .NET Установил SqlXml 4.0 Service Pack 1 (SP1), в References проекта добавил %PROGRAMFILES%\SQLXML 4.0\bin\Microsoft.Data.SqlXml.dll
Пытаюсь получить данные так
string s = "Provider=SQLOLEDB;server=(localdb)\\MS;database=Test;Integrated Security=SSPI";
SqlXmlCommand c = SqlXmlCommand(s);
c.CommandText = "select * from tbl";
SqlXmlAdapter a = SqlXmlAdapter(c);
DataSet d = new DataSet();
a.Fill(d);

Получаю ошибку

Microsoft.Data.SqlXml.SqlXmlException: [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied. ---> System.Runtime.InteropServices.COMException: [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.

Хотя SQL Server работает нормально и можно подключиться через SqlConnection.


text:
Q: Jenkins groovy script execution for dynamic parameters I am trying to use active choice parameters in jenkins . I am executing a shell command and trying to show the output in the choice parameters.
1) Working scenario -
Text file already generated by the output of shell command and able to see the parameters -
list = []
def process = "cat /home/ansible/test1.txt".execute()
process.text.eachLine {list.add it}
return list

Here test1.txt is already populated with the values
2) Failure scenario
Instead of pre-populating the file trying the get the shell command output and write into a file and then show it to the choice parameters-
list = []
def process1=" sh script.sh > test1.txt".execute()
def process = "cat /home/ansible/test1.txt".execute()
process.text.eachLine {list.add it}
return list

This is not working
Is there any suggestions ?

A: Use pure groovy to read file lines
new File('/home/ansible/test1.txt').readLines()

For your case - wrap your code with try-catch to see the error.
Without error message it's hard to help you...
try{
  def list ....
}catch(e){ return [e.toString()] }


text:
Q: php SoapClient parameter sequence with the same name I've to do a soap call where the parameter contains a sequence of complex type.
I don't find the good format for the parameter.
Here the xsd :
<xs:complexType name="createOspService">
    <xs:sequence>
        <xs:element name="OSP" type="tns:OSP" minOccurs="0"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="ospServiceResponse">
</xs:complexType>
<xs:complexType name="OSP">
    <xs:sequence>
        <xs:element name="OSP_ID" type="xs:int" minOccurs="1" maxOccurs="1"/>
        <xs:element name="DATE_OSP" type="xs:dateTime" minOccurs="1" maxOccurs="1"/>
        <xs:element name="CUSTOMER_ID" type="xs:int" minOccurs="1" maxOccurs="1"/>
        <xs:element name="RECIPIENT_ID" type="xs:int" minOccurs="1" maxOccurs="1"/>
        <xs:element name="ITEMS" type="tns:ITEMS" minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="ITEMS">
    <xs:sequence>
        <xs:element name="ITEM" type="tns:ITEM" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="ITEM">
    <xs:sequence>
        <xs:element name="OSP_ITEM" type="xs:string" minOccurs="1" maxOccurs="1"/>
        <xs:element name="QUANTITY" type="xs:double" minOccurs="1" maxOccurs="1"/>
        <xs:element name="UNIT_PRICE" type="xs:double" minOccurs="1" maxOccurs="1"/>
        <xs:element name="VAT_CODE" type="xs:string" minOccurs="1" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

The php call :
$client = new \SoapClient('http://10.55.12.90:18180/NABSCamel/lgg/osp/ws?wsdl', $options);
try {
    $osp = new \stdClass();
    $osp->OSP = new \stdClass();
    $osp->OSP->OSP_ID = $this->meetingRoomBookingI;
    $osp->OSP->DATE_OSP = $date->format('c');
    $osp->OSP->CUSTOMER_ID = $customer->Id();
    $osp->OSP->RECIPIENT_ID = $recipientId;

    $items = [];

    $item = new \stdClass();
    $item->OSP_ITEM = 'test 1';
    $item->VAT_CODE = 21;
    $item->QUANTITY = 2;
    $item->UNIT_PRICE = 3;

    $items[] = $item;

    $item = new \stdClass();
    $item->OSP_ITEM = 'test 2';
    $item->VAT_CODE = 21;
    $item->QUANTITY = 2;
    $item->UNIT_PRICE = 3;

    $items[] = $item;

    $osp->OSP->ITEMS = $items;

    $response = $client->createOspService($osp);
}
catch (\SoapFault $fault){
    echo $fault->faultstring;
}

I got this error :
SOAP-ERROR: Encoding: object has no 'ITEM' property

I don't find what it's missing something near ITEMS parameter.
ITEMS must be an array with ITEM but where I put this word ITEM in my array ?!
thanks,
Phil

A: If you really don't know how to construct the request and don't want to wonder, then you should definitively use a WSDL to PHP generator that'll generate the associated classes. You won't have to wonder how to construct the request as you'll have each class for each struct. Moreover, the response handling will be easier too.
I suggest you tru the PackageGenerator project which is a good generator.