text:
Q: How to shift device in Doze Mode (Android Preview M / Marshmallow)? I followed steps described here:
https://developer.android.com/preview/testing/guide.html#doze-standby
Circumstances:

*

*Android Debug Bridge version 1.0.32

*Nexus 9 with Preview M
Shell:
$ adb shell dumpsys battery unplug

=> worked, device unplugged
$ adb shell dumpsys deviceidle step

=> Output: Stepped to: ACTIVE
$ adb shell dumpsys deviceidle -h

=> does not work => Output:
Device idle controller (deviceidle) dump options:

[-h] [CMD]

-h: print this help text.

Commands:

step

disable

enable

whitelist

I tried it with:
adb shell dumpsys deviceidle enable

But it didn't work.
So my question, as mentioned above, how to shift the device in Doze-Mode?
What did i make wrong?
EDIT - JUNE, 2016:
New Link:
https://developer.android.com/training/monitoring-device-state/doze-standby.html

A: There is a better way to achieve this in the new releases:

$ adb shell dumpsys deviceidle force-idle

No need to unplug from power, no need to wait for the screen to turn off.

A: Yes, it appears that Google's developer testing guideline is incorrect. I just recently discovered this as well and posted a bug about it here with the correct steps to get the device to idle (aka doze).

A: Ok, i got it. The trick was to turn the screen off! After that
$ adb shell dumpsys deviceidle step
outputs:
IDLE_PENDING
then
SENSING
then
IDLE
then
IDLE_MAINTENANCE
then
IDLE
then
IDLE_MAINTENANCE
and so on...
Many thanks to this site:
https://newcircle.com/s/post/1739/2015/06/12/diving-into-android-m-doze

A: $ adb shell dumpsys deviceidle -h

This command only outputs a help message like common unix program.
IDLE means Doze mode.
In the article you linked, you can regard Doze mode as device idle mode.

A: You can find my full answer posted on the similar topic here:
How to test Doze Mode on Android?
Idle State - In order to put the device into an Idle state you can use the following adb commands:
>adb shell dumpsys battery unplug
>adb shell dumpsys deviceidle force-idle

Active State - In order to put the device back into the Active state you may simulate the following key event:
> adb shell input keyevent KEYCODE_WAKEUP

I also needed a quick option to toggle between Active and Idle states so I wrote a batch script adbIdleModeSwitch.bat for these purposes, you may download and use it: https://drive.google.com/file/d/0B81qFnPX_eUUYTMxOTd1UG94NVk/view


text:
Q: Multiple PDF files with mpdf is return me only one value in all generated files I have a MySQL database wirh orders records and I want to generate PDF if status order is payed from all id's and I'm trying with mpdf but is generate me the files but all with the same value.
$qry = mysqli_query($dbs, "SELECT * FROM orders WHERE orderstatus='payed'");
$row = array();
while ($data = mysqli_fetch_array($qry)) {
    $row[] = $data;

    foreach ($row as $x) {
        $folder = 'facturi' . "/" . $x[0];
        if (!is_dir($folder)) {
            mkdir($folder, 0777, true);
            $file_name = "#DPL-" . $x[0] . ".pdf";
            $mpdf->WriteHTML($x[0]); // x[0] is > id, just for testing
        }
    }

    $mpdf->Output($folder . "/" . $file_name, 'F');
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automating vba code window how to write a batch command to print text contents in vba code editor window similar to printing contents in a notepad using echo command?
echo This is for just testing > test.txt

The above command will create a notepad file called 'test' with contents 'This is for just testing'.Similarly how to write contents in vba code window.
Thanks in advance

A: Assuming myModule exists:
Sub echo(s As String)
    Call Application.VBE.VBProjects(1).VBComponents("myModule").CodeModule.AddFromString(s)
End Sub

You will probably need to activate macro editiion in the Trust Center:
File > Option > Trust Center > Trust Center Settings > Macro Settings
Check Trust access to the VBA project object model


text:
Q: SQL delete trigger I have 3 tables:
POS(IDPOS, IDCARD);
CARDS(IDCARD, IDPERSON);
PERSON(IDPERSON, PERSONTYPE).
Every time a card is associated to a POS, I need to ensure that the person that has that card can only be PERSONTYPE='Employee' or PERSONTYPE='Volunteer'.
This is what I accomplished so far, but it doesn't seem to be working when I insert valid records.
DELETE POS
FROM inserted i
INNER JOIN POS p ON i.IDPOS=p.IDPOS
INNER JOIN CARDS ON i.IDCARD=CARDS.IDCARD
INNER JOIN PERSON ON CARDS.IDPERSON=PERSON.IDPERSON
WHERE PERSONTYPE <> 'Employee' or PERSONTYPE <> 'Volunteer';

This trigger is done on the POS table and is an after insert, update.
Does someone know were is the mistake?

A: Use NOT IN:
WHERE PERSONTYPE NOT IN ('Employee', 'Volunteer');

Your logic requires an AND, not OR.

A: I believe you have used alias for POS, you need to put alias for delete. Also you can use NOT EXISTS() instead of joining another table :
with alias usage :
DELETE P
FROM POS AS P
INNER JOIN INSERTED AS I ON i.IDPOS=p.IDPOS
INNER JOIN CARDS ON I.IDCARD=CARDS.IDCARD
WHERE NOT EXISTS (SELECT 1
                    FROM PERSON
                    WHERE CARDS.IDPERSON=PERSON.IDPERSON
                    AND PERSONTYPE IN ('Employee','Volunteer')
                 );

normal usage :
DELETE
FROM POS
INNER JOIN INSERTED AS I ON I.IDPOS=POS.IDPOS
INNER JOIN CARDS ON I.IDCARD=CARDS.IDCARD
WHERE  NOT EXISTS (SELECT 1
                    FROM PERSON
                    WHERE CARDS.IDPERSON=PERSON.IDPERSON
                    AND PERSONTYPE IN ('Employee','Volunteer')
                 );


text:
Q: Как отсылать email из локального сервера? Нужно сделать отправку email сообщения через сервис Mandrill.
Сделал пример по гайду, но письмо не отсылается!
Подозреваю что это из за того, что я не зарегистрировал SPF и DKIM, но работаю на локальном сервере, и не знаю как зарегистрировать DNS.
Возможно ли отсылать email из локального сервера ?
скрипт:
<?php

require_once ('mandrill-api/src/Mandrill.php');

$mail = new Mandrill('5l-qONinNOuZ8a0iZg_Hrg');

/* Блок динамического контента */
$tpl_con = array(
    array(
        'name' => 'my-label',
        'content' => '
Моя рассылка
'
    )
);

$data = array(
    'html' => 'It is html text',
    'text' => 'It is simple text',
    'subject' => 'My mess',
    'from_email' => 'friend@example.com',
    'from_name' => 'Michael',
    'to' => array(
        array(
            'email' => 'vitaliyprokopovoak@gmail.com',
            'name' => 'Lucas',
            'type' => 'to'
        )
    ),
    'global_merge_vars' => array(
        array(
            'name' => 'NAME',
            'content' => 'Lucas'
        )
    ),
    'merge_vars' => array(
        array(
            'rcpt' => 'vitaliyprokopovoak@gmail.com',
            'vars' => array(
                array(
                    'name' => 'NAME',
                    'content' => 'Lucas'
                )
            )
        )
    ),
    'subaccount' => 'prokopov-sub'
);

try {
    /* Отправка обычного письма */
    $result = $mail->messages->send($data);
    print_r($result);
} catch(Mandrill_Error $error) {
    echo 'Error: ' . get_class($error) . ' - ' . $error->getMessage();
}

результат:

Array ( [0] => Array ( [email] => vitaliyprokopovoak@gmail.com
  [status] => rejected [_id] => 8b597ab4d9b04b49ab6366e232831306
  [reject_reason] => unsigned ) )


text:
Q: "Autoscroll to Source" missing in IntelliJ 2020.1.1 where did my "target" icon go...I don't even see the options in the menu anymore...  Using version 2020.1.1
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360006983339-Autoscroll-to-Source?page=1#community_comment_360001785219

A: The button is removed when you have "Always Select Opened File" option enabled as this option does the same.


text:
Q: svn call from python not working on ubuntu box I have a python script in my django project that grabs information from an 'svn log' call and displays it on a page.
Something like:
cmd = 'svn log svn://(blahblahblah)'
subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

This call works locally in my Windows environment, but when deployed to our ubuntu instance, it doesn't seem to return anything.
When I ssh onto the box, I am able to do 'svn log' just fine from the command line, not sure if my ssh session uses different credentials than what django is running as. I also tried specifying --username and --password in my 'svn log' call, but this actually prompts me for a username and password - not sure why that is.

A: Why are you using subprocess? Maybe you can use os.system:
import os
cmd = 'svn log svn://(blahblahblah)'
os.system(cmd)

Also, take care about shell=True because it can be a security hazard.


text:
Q: The limit $\lim_{x \to 0} \sqrt{x}$ and the existence of limits in simlar cases If I'm not wrong, $\lim_ {x \to 0} \sqrt{x} = 0$ , even though $\lim_ {x \to 0^{-}} \sqrt{x}$ does not exist.
Then in this following graph of $f(x)$ :

Does $\lim_{x \to 1} f(x)$ exist? Would it still exist if $f(1)$ were not defined?

A: Since $\sqrt x$ is undefined when $x<0$, it doesn't make sense to talk about $\lim_{x\to0^-}\sqrt x$.
And, yes, $\lim_{x\to1}f(x)=1$, even if $f(1)$ is undefined.


text:
Q: How to show that if $V \in C^{m \times m}$ unitary and $A \in C^{m \times m}$ then $||AV||_2=||A||_2$ How to show that if $V \in C^{m \times m}$ is unitary and $A \in C^{m \times m}$ then $$||AV||_2=||A||_2$$
Where $$||A||_2 = \sup_{ ||x||_2=1 } ||Ax||_2$$ and
$$||AV||_2 = \sup_{ ||x||_2=1 } ||AVx||_2$$

A: You have
$$\Vert V x\Vert^2 = \langle V x,V x \rangle = \langle x , V^* V x \rangle = \langle x,x\rangle = \Vert x\Vert ^2 $$
for any $x$. So for any $x$ you have $\Vert Vx\Vert = \Vert x\Vert$.
Hence $V$ has norm $1$. $V^{-1}$ as well is unitary and so it has norm $1$.
Clearly $\Vert A V\Vert \leq \Vert A \Vert \Vert V\Vert = \Vert A\Vert$.
For the other inequality you have
$$\Vert A\Vert = \Vert AV V^{-1}\Vert \leq \Vert A V\Vert \Vert V^{-1}\Vert = \Vert AV\Vert\,.$$
Then $\Vert AV \Vert = \Vert A\Vert$.


text:
Q: A button does not move When I run this code, the controls button appears on the top. I want to change size of the button and the place of the button. I tried to use setBounds() method but it doesn't change anything.
import javax.swing.*;
import java.awt.*;

public class GameFrame
{

    public JFrame gameframe;
    public JPanel panel;
    public JButton b1;
    public JLabel lab;

    public GameFrame()
    {
        gui();
    }

    public void gui()
    {
        gameframe = new JFrame("Poop MAN");
        gameframe.setVisible(true);
        gameframe.setSize(800, 900);
        gameframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();

        panel.setBackground(Color.yellow);

        b1 = new JButton("CONTROLS");
        b1.setBounds( 300,70,590,300);
        //b1.setSize(new Rectan

        panel.add(b1);

        gameframe.add(panel);
    }

        public static void main(String[] args)
        {
                new GameFrame();
        }
}

A: After you change the position or text of the button you need to call repaint() on the JFrame. Make sure the button is added to the JFrame first.


text:
Q: pytest-mock assert_called_with failed for class function I am planning to use pytest and pytest-mock for validating the Python code. Being a newbie, wrote a sample code to validate the mock on class and seeing failure. I am wondering what went wrong.
src/main.py
class Main(object):
    def __init__(self, my_var=None):
        self.var = my_var

    def internal_func(self, var=10):
        my_var = var + 20
        return my_var

    def test_func(self):
        val = self.internal_func(20)
        return val + 40

tests/test_main.py
    import pytest
    from pytest_mock import mocker
    from src.main import Main

    def new_func(cls, *args, **kwargs):
        return 2

    def test_main_mock(mocker):
        mocker.patch.object(Main, 'internal_func')
        val = Main().test_func()
        assert Main.internal_func.assert_called_with(20)

It fails with the following error
    ======================================================================================== FAILURES ========================================================================================
    _____________________________________________________________________________________ test_main_mock _____________________________________________________________________________________

    mocker = <pytest_mock.MockFixture object at 0x7f34f490d8d0>

        def test_main_mock(mocker):
            mocker.patch.object(Main, 'internal_func')
            main = Main()
            val = main.test_func()
        #    assert val == 80
    >       assert Main.internal_func.assert_called_with(20)
    E       AssertionError: assert None
    E        +  where None = <bound method MagicMock.wrap_assert_called_with of <MagicMock name='internal_func' id='139865418160784'>>(20)
    E        +    where <bound method MagicMock.wrap_assert_called_with of <MagicMock name='internal_func' id='139865418160784'>> = <MagicMock name='internal_func' id='139865418160784'>.assert_called_with
    E        +      where <MagicMock name='internal_func' id='139865418160784'> = Main.internal_func

    tests/test_main.py:13: AssertionError

A: The return_value or side_effect must be set before the patched func take effect
def test_main_mock(mocker):
    # mock internal_func of class Main
    mocked_internal_func = mocker.patch.object(Main, 'internal_func')
    # assign return_value or side_effect
    mocked_internal_func.return_value = -10
    # class instance
    ma = Main()
    val = ma.test_func()

    assert ma.internal_func.assert_called_with(20)

Correction of mistake, the assert should not be used together with assert_called_with, they are independent assert.

    assert val == 30
    mocked_internal_func.assert_called
    ma.internal_func.assert_called_with(20)
    mocked_internal_func.assert_called_with(20)


text:
Q: What does this error means and how to fix it? I was creating a little bmi calculator in Python 3.5.1, but weirdly it doesn't work. In Python 2.7 it was working, but it isn't working here. My code is:
print ('Geef uw gewicht in kg: ')
gewicht_kg = input()
print ('Geef uw lengte in meters: ')
lengte_meters = input()
bmi = gewicht_kg / (lengte_meters * lengte_meters)

The string are written in Dutch, but that doesn't matter. If I run the program, the input does work (so I can type whatever I want) but when it suppose to make the calculation, it gives the following error:
can't multiply sequence by non-int of type 'str'

What does this mean and how can I fix it?

A: The error message indicates that Python is trying to multiply a list of characters with a string value, which makes no sense. Indeed: Your input is string (and should be entered unquoted), so it must be translated into a numeric format first.
Use
gewicht_kg = float(raw_input())

and similar for the other input and it will work out better.


text:
Q: Package not deploying everything in it to server I have a package solution as,
<Solution xmlns="http://schemas.microsoft.com/sharepoint/" SolutionId="id" SharePointProductVersion="14.0">
  <Assemblies>
    <Assembly Location="myaSSEMBLEY.dll" DeploymentTarget="GlobalAssemblyCache" />
  </Assemblies>
  <TemplateFiles>
    <TemplateFile Location="Layouts\myWebServices\ssServices.asmx" />
    <TemplateFile Location="Layouts\myWebServices\ssServices.asmx" />
  </TemplateFiles>
</Solution>

but it's deploying dlls to gac but not deploying my web services to layout's folder, what could be wrong ???

A: Try to use <RootFiles>, <RootFile> tags
For example,
<Solution xmlns="http://schemas.microsoft.com/sharepoint/" SolutionId="id" SharePointProductVersion="14.0">
  <Assemblies>
    <Assembly Location="myaSSEMBLEY.dll" DeploymentTarget="GlobalAssemblyCache" />
  </Assemblies>
  <RootFiles>
    <RootFile Location="Layouts\myWebServices\ssServices.asmx" />
    <RootFile Location="Layouts\myWebServices\ssServices.asmx" />
  </RootFiles>
</Solution>


text:
Q: Ansible - Is it possible to override an inventory file to run for specific tasks within a playbook? I am trying to re-design a playbook, where I am using idiomatic Ansible in order to create new configuration objects. I am basically sending the following command, in order to start the playbook:
ansible-playbook test-playbook.yaml -v -i roles/test-role/vars/inventory

The playbook calls various roles, which in turn use delegations and override the inventory_hostname variable in order to use the correct target hostname. For example, in this playbook snippet:
- name: "Upload certificate"
  import_role:
    name: certificate_manager
    tasks_from: certificate_upload
  delegate_to: localhost
  vars:
    inventory_hostname: "{{ target_hostname }}"

This of course uses the files contained within the roles/test-role/vars/inventory folder as an inventory file; this contains the configuration.yml file which specifies the details of the configuration object which will be created.
If useful, the configuration.yml file is formatted like so:
virtual_servers:
  hosts:
   test-1.test.local
     name: test-1.test.local
     type: 'standard'
     description: 'Test'
...

This, however, closes the possibility to use the actual inventory, which also contains other useful variables - also considering that within the playbook I am using tasks from other roles.
Since the approach to use the actual inventory (without the -i override) I think is better, especially considering that it is going to be centrally updated if the need arises, is there a better (and maybe simpler) way to run the configuration file with the hosts definition, without impacting the actual inventory?
Thanks in advance for any inputs you might have.

A: Q: "Override the inventory_hostname variable in order to use the correct target hostname."
A: The variable inventory_hostname is a special variable provided for your convenience. It does not make sense to override it because this variable doesn't control any connection plugin. Test it. For example,
- hosts: test_11:test_12:test_13
  tasks:
    - command: hostname
      register: hostname
      vars:
        inventory_hostname: foo.bar.baz
    - debug:
        var: hostname.stdout

gives
PLAY [test_11:test_12:test_13] ***************************************************************

TASK [command] *******************************************************************************
changed: [test_11]
changed: [test_12]
changed: [test_13]

TASK [debug] *********************************************************************************
ok: [test_11] =>
  hostname.stdout: test_11
ok: [test_12] =>
  hostname.stdout: test_12
ok: [test_13] =>
  hostname.stdout: test_13

PLAY RECAP ***********************************************************************************
test_11: ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
test_12: ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
test_13: ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

You can see that overridden inventory_hostname didn't influence which remote host was connected.


text:
Q: Code first foreign keys substitution in unit testing Let I use code first models with foreign keys like:
class Employee
{
    public int EmployeeId { get; set; }

    public int CompanyId { get; set; }

    [ForeignKey("CompanyId")]
    public virtual Company Company { get; set; }
}

And I want to use in my biz services queries like:
class EmployeeService
{
    ...
    var company = employee.Company; // <-- it is substituted by Entity Framework
    ...
}

The question is how can I substitute foreign key navigation properties (like Employee.Company) in my unit tests?
As for me, I found these solutions:

*

*Write constructions like employee.CompanyId = 1; employee.Company = _companyRepo.GetById(1).

*Create constructor like Employee(Company company). It will make the code smaller, but not ideal from my point of view

Anyone knows better solution?


text:
Q: Finding the "Visible" tkinter Frame I am working with Python's tkinter package. I've constructed a Notebook object, and assigned two frames that can be "tabbed" between...
notebook=ttk.Notebook(root)
frame1=ttk.Frame(notebook)
frame2=ttk.Frame(notebook)
notebook.add(frame1,text="Tab 1")
notebook.add(frame2,text="Tab 2")

However, I can't figure out how to do one thing in this configuration. I want to write a function that can tell which "tab" the user is looking at. Perhaps it is called every five seconds, and it prints a "1" if the user is on tab 1 and a "2" if the user is on tab "2"? I'm hoping there is a simple function like frame1.isvisible() or something like that, but I haven't been able to find it in the documentation.

A: I see 2 problems here:

*

*How to find which tab is selected?

You should use the notebook's .select() method without any arguments. It returns the widget name of the currently selected pane.

*How to observe the current tab selection?

To check which tab is selected you might bind to the <<NotebookTabChanged>> event and store the infromation about selected tab. This event is called every time the tab selection changes, so there's no need to poll every X seconds about the change.
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

notebook=ttk.Notebook(root)
frame1=tk.Frame(notebook)
frame2=tk.Frame(notebook)
notebook.add(frame1,text="Tab 1")
notebook.add(frame2,text="Tab 2")

def print_tab_num(nb, event):
    print(f"Selected {nb.select()} tab which has index: {nb.index(nb.select())}")

notebook.bind("<<NotebookTabChanged>>", lambda evt: print_tab_num(notebook, evt))

notebook.pack()
root.mainloop()

A: You can actually use the method notebook.select to find the tab currently selected.
But the problem is that it will not fetch you the direct result you want and rather will return you the tab_id
So you also have to use the notebook.index method to find the actual tab index and not the tab_id.
notebook.index(notebook.select())

This should answer you. But here too if you want the actual tab names you gave then filter it using the 'text' argument -:
notebook.tab(notebook.select(), 'text')

Another way to do it is using the current tag which saves the current tab value -:
notebook.index('current')

Both will give results as desired.


text:
Q: Updating one table from another table I have created a new table for my use , lets say t1 which has 8 columns in it. I have populated 3 columns through a procedure. Column 1 is name. Now I want to populate the 4th column for corresponding name. This would be update with where clause.
The scenario is I have created a query which has the result, calling that t2 which has name and total_amount. Now I want to populate total_amount into the 4th column of t1.
The approach that I'm right now following is looping through each name in t1 and finding its counter total_amount in t2(with clause) and updating the value in t1. But it is taking infinite time. First is because of looping in t1 , secondly the t2 is itself a query which is executing again and again.
Now, the actual task is much more complicated and I have just provided the crux of it. Please suggest me an approach which is fast.
create or replace procedure proc
is

temp_value number(18,2);

CURSOR total is
select name, age, sex from data_table where
{conditions};

/*Gives me name and age in 1st and 2nd column and likewise data in 3rd column */

begin

FOR temp IN total LOOP

    with aa as (SELECT b.name,
         NVL (SUM (c.amount), 0) as total_amount
    FROM data_table2 b, data_table3 c
   WHERE     {joins and groub by}
   )
   /* This gives me total amount for corresponding name. There is no repetition of name */

   select nvl(sum(total_amount),0) into temp_value from aa where name = temp.name;

    update t1 set amount = temp_value where name = temp.name;

    END LOOP;

END;
/

A: Cant add a comment to question, hence putting it here.
Per your example:
    with aa as (SELECT b.name,
     NVL (SUM (c.amount), 0) as total_amount
FROM data_table2 b, data_table3 c
WHERE     {joins and groub by}
)
/* This gives me total amount for corresponding name. There is no repetition of name */

select nvl(sum(total_amount),0) into temp_value from aa where name = temp.name;

update t1 set amount = temp_value where name = temp.name;

In your with clause you you take some sum, and then populate the sum of those sum for all names in your cursor. Why cant you directly do:
    SELECT SUM(NVL(total_amount, 0)) INTO temp_vale FROM
       data_tabl1, data_tabl2, data_tabl3
       WHERE
        --JOIN CONDITIONS
      AND data_tabl1.total)name = --data_tabl2/3.name
    GROUP BY --clause;

Why I say this is, with clause is not always a good idea. If your 'with' has a huge data, then it will run forever. 'With' is used to take care of repetitive tables with small data being joined again and again.
Also for tuning purpose, try some hints.
Also, NVL(SUM..) why not SUM(NVL(total_amount, 0))?


text:
Q: How to get Vector in DataFrame I get some Feature Vector using SparkML TF-IDF algorithm. Now I want to get the Vector in the column of "idfFeatures".

My code is:
val vectors = allDF.select("idfFeatures").map{
  case Row(vector: Vector) =>
    vector
}
vectors.foreach(println(_))

There is a bug in console:
Error:(38, 24) type Vector takes type parameters
  case Row(vector: Vector) =>
                   ^

If I change Vector to String, there is another bug:
scala.MatchError: [(262144,[622,4200,7303,8501......,2.1972245773362196,1.2809338454620642])] (of class org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema)
at scala.TFIDFTest2$$anonfun$1.apply(TFIDFTest2.scala:37)

How can I get the Vector?

A: Spark 1.x:
import org.apache.spark.mllib.linalg.Vector

Spark 2.0:
import org.apache.spark.ml.linalg.Vector

Example:
// https://spark.apache.org/docs/latest/ml-features.html#tf-idf

import org.apache.spark.ml.feature.{HashingTF, IDF, Tokenizer}

val sentenceData = spark.createDataFrame(Seq(
  (0, "Hi I heard about Spark"),
  (0, "I wish Java could use case classes"),
  (1, "Logistic regression models are neat")
)).toDF("label", "sentence")

val tokenizer = new Tokenizer().setInputCol("sentence").setOutputCol("words")
val wordsData = tokenizer.transform(sentenceData)
val hashingTF = new HashingTF()
  .setInputCol("words").setOutputCol("rawFeatures").setNumFeatures(20)
val featurizedData = hashingTF.transform(wordsData)

val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
val idfModel = idf.fit(featurizedData)

val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
val idfModel = idf.fit(featurizedData)
val rescaledData = idfModel.transform(featurizedData)

import org.apache.spark.ml.linalg.Vector
import org.apache.spark.sql.Row

rescaledData.select("features").rdd.map { case Row(v: Vector) => v}.first


text:
Q: How to get validation for particulate fields on for submit event in Ext JS? Below is my code.
I get two fieldset each one contains some textboxes and a button.
I want to validate only those fields on button click that belongs to that field set.
For example, there are two options: Send SMS and Send Email. Each option has a send button. If I want to send either SMS or Email then I don't want to validate all fields. This means if I want to send Email then I want to validate only Emails Text fields, not SMS's fields on click of Send button of email.
Below is my code. You can understand better.
  this.form = new Ext.form.Panel({
            margin: '10 100 10 100',
            xtype: 'panel',
            border: true,
            layout: 'hbox',
            padding: '2 2 2 2',
            items: [{
                xtype: 'fieldset',
                flex: 1,
                layout: 'anchor',
                title: 'Send Email',
                //collapsible: true,
                //collapsed: true,
                border: false,
                defaults: { anchor: '100%' },

                items: [{
                    xtype: 'textfield',
                    name: 'txtRecipients',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Recipients email address',
                    padding: '2 2 2 2 '
                },
                {
                    xtype: 'textfield',
                    name: 'txtSubject',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Subject',
                    padding: '2 2 2 2 '
                },
                {
                    xtype: 'textareafield',
                    name: 'txtMessage',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Type your message here',
                    padding: '2 2 2 2 ',
                    rows: 4

                },
                {
                    xtype: 'container',
                    items: [
                        {
                            xtype: 'button',
                            margin: '0 0 0 0',
                            text: 'Send',
                            width: 80,
                            height: 30,
                            handler: function () {
                            }
                        }
                    ]
                }]

            },
            {
                xtype: 'fieldset',
                flex: 1,
                layout: 'anchor',
                title: 'Send SMS',
                //collapsible: true,
                //collapsed: true,
                border: false,
                defaults: { anchor: '100%' },

                items: [{
                    xtype: 'textfield',
                    name: 'txtRecipients',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Contact Numbers seperated by comma(,)',
                    padding: '2 2 2 2 '
                },
                {
                    xtype: 'textareafield',
                    name: 'txt1Message',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Type your message here',
                    padding: '2 2 2 2 ',
                    rows: 3

                },
                {
                    xtype: 'tbspacer',
                    height: 45
                },
                {
                    xtype: 'container',
                    items: [
                        {
                            xtype: 'button',
                            margin: '0 0 0 0',
                            text: 'Send',
                            width: 80,
                            height: 30,
                            handler: function () {
                            }
                        }
                    ]
                }]

            }]
        });

A: You can just change the fieldset xtype to form . so that you can directly validate and get values for SMS and email seperatly.

A: You need to add a specific function for each button. In each role you add the necessary validation to E-mail or SMS.
Example:
this.form = new Ext.form.Panel({
    margin: '10 100 10 100',
    xtype: 'panel',
    border: true,
    layout: 'hbox',
    padding: '2 2 2 2',
    items: [{
            xtype: 'fieldset',
            flex: 1,
            layout: 'anchor',
            title: 'Send Email',
            //collapsible: true,
            //collapsed: true,
            border: false,
            defaults: {
                anchor: '100%'
            },
            items: [{
                    xtype: 'textfield',
                    name: 'txtRecipients',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Recipients email address',
                    padding: '2 2 2 2 '
                },
                {
                    xtype: 'textfield',
                    name: 'txtSubject',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Subject',
                    padding: '2 2 2 2 '
                },
                {
                    xtype: 'textareafield',
                    name: 'txtMessage',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Type your message here',
                    padding: '2 2 2 2 ',
                    rows: 4

                },
                {
                    xtype: 'container',
                    items: [{
                        xtype: 'button',
                        margin: '0 0 0 0',
                        text: 'Send',
                        width: 80,
                        height: 30,
                        handler: function() {
                            check_email();
                        }
                    }]
                }
            ]
        },
        {
            xtype: 'fieldset',
            flex: 1,
            layout: 'anchor',
            title: 'Send SMS',
            //collapsible: true,
            //collapsed: true,
            border: false,
            defaults: {
                anchor: '100%'
            },
            items: [{
                    xtype: 'textfield',
                    name: 'txtRecipients',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Contact Numbers seperated by comma(,)',
                    padding: '2 2 2 2 '
                },
                {
                    xtype: 'textareafield',
                    name: 'txt1Message',
                    allowBlank: false,
                    //fieldLabel: 'Last Name',
                    emptyText: 'Type your message here',
                    padding: '2 2 2 2 ',
                    rows: 3

                },
                {
                    xtype: 'tbspacer',
                    height: 45
                },
                {
                    xtype: 'container',
                    items: [{
                        xtype: 'button',
                        margin: '0 0 0 0',
                        text: 'Send',
                        width: 80,
                        height: 30,
                        handler: function() {
                            check_sms();
                        }
                    }]
                }
            ]
        }
    ]
});

function check_email(){
    // Here you do a validation of the E-mail fields
}

function check_sms(){
   // Here you do a validation of the SMS fields
}


text:
Q: Calculate Median in An Array - Can someone tell me what is going on in this line of code? This is a solution for calculating the median value in an array. I get the first three lines, duh ;), but the third line is where the magic is happening.  Can someone explain how the 'sorted' variable is using and why it's next to brackets, and why the other variable 'len' is enclosed in those parentheses and then brackets?  It's almost like sorted is all of a sudden being used as an array?  Thanks!
  def median(array)
    sorted = array.sort
    len = sorted.length
    return ((sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0).to_f
  end

  puts median([3,2,3,8,91])
  puts median([2,8,3,11,-5])
  puts median([4,3,8,11])

A: Consider this:
[1,2,2,3,4] and [1,2,3,4]. Both arrays are sorted, but have odd and even numbers of elements respectively. So, that piece of code is taking into account these 2 cases.
sorted is indeed an array. You sort [2,3,1,4] and you get back [1,2,3,4]. Then you calculate the middle index (len - 1) / 2 and len / 2 for even / odd number of elements, and find the average of them.

A: Yes, array.sort is returning an array and it is assigned to sorted. You can then access it via array indices.
If you have an odd number of elements, say 5 elements as in the example, the indices come out to be:
(len-1)/2=(5-1)/2=2

len/2=5/2=2 --- (remember this is integer division, so the decimal gets truncated)

So you take the value at index 2 and add them, and then divide by 2, which is the same as the value at index 2.
If you have an even number of elements, say 4,
(len-1)/2=(4-1)/2=1 --- (remember this is integer division, so the decimal gets truncated)

len/2=4/2=2

So in this case, you are effectively averaging the two middle elements 1 and 2, which is the definition of median for when you have an even number of elements.

A:
It's almost like sorted is all of a sudden being used as an array?

Yes, it is. On line 2 it's being initialized as being an array with the same elements as the input, but in ascending order (default sort is ascending). On line 3 you have len which is initialized with the length of the sorted array, so yeah, sorted is being used as an array since then, because that's what it is.


text:
Q: Django - how to determine if model class is abstract If a django model is made abstract, like below, is there a way to inspect the class to determine that it is abstract?
class MyModel(models.Model):
  class Meta:
    abstract = True

I would expect that I could examine MyModel.Meta.abstract, but according to Django docs:

Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False. This means that children of abstract base classes don't automatically become abstract classes themselves.

Any ideas? Thanks!

A: I'd like to point out that you don't need to instantiate a model to check if it's abstract - Django models inherit an actual metaclass that adds _meta on class instantiation.
So, similarly to @sheats's code, try
from django.db.models import Model
class MyModel(Model):
  pass
print MyModel._meta.abstract

Or, for a positive example
from django.db.models import Model
class MyModel(Model):
  class Meta(object):
    abstract = True
print MyModel._meta.abstract

Of course, this also works for built-in models and anything inheriting from Django's Model.
from django.contrib.auth.models import User
print User._meta.abstract

A: You can instantiate MyModel and then check ._meta.abstract.
So in code:
m = MyModel()
print m._meta.abstract


text:
Q: How can I programmatically construct a pack: URI to refer to a resource in a different assembly? I want to programmatically construct a pack: Uri. This fails:
Uri myuri = new Uri("pack://application:,,,/lookup2.xml");

It seems like maybe this was supported in some environments (based on other answers I've seen) but it throws System.UriFormatException: Invalid URI: Invalid port specified for me.
This works:
Uri appBase = new Uri("application:///", UriKind.Absolute);
Uri appPath = new Uri("/lookup2.xml", UriKind.Relative);
Uri packUri = PackUriHelper.Create(appBase, appPath)

That returns the pack: URI for a resource in the current assembly. Now I want to create pack://application:,,,/OtherAssembly;component/lookup2.xml.
And I cannot work out how to do that. Perhaps I'm overlooking something obvious. But if I make the /OtherAssembly;component/ part of the appPath, the "/" characters gets escaped. I get pack://application:,,,,OtherAssembly;component/lookup2.xml which isn't right as far as I can tell from the MS docs about assembly references in pack: URIs.
It looks like maybe a PackagePart would help, but I'm not sure. I can't see how to construct one from an Assembly anyway.
Pointers, please?

A: Partial answer below. First Uri output is fine. The second one gets jumbled up because I think PackUriHelper may not be able to handle this scenario. Perhaps will help.
            Uri appBase = new Uri("application:///", UriKind.Absolute);
            Uri appAssembly = new Uri("/OtherAssembly;component", UriKind.RelativeOrAbsolute);
            Uri appBaseOtherAssembly = PackUriHelper.Create(appBase, appAssembly);
            Console.WriteLine(appBaseOtherAssembly.ToString()); //pack://application:,,,/OtherAssembly;component
            Uri appPath = new Uri("/lookup2.xml", UriKind.Relative);
            Uri completeUri = new Uri(appBaseOtherAssembly, appPath);
            Console.WriteLine(completeUri.ToString());//not sure why; produces: pack://application:,,,/lookup2.xml
            var uri = PackUriHelper.Create(appBaseOtherAssembly, appPath);
            Console.WriteLine(uri.ToString()); //pack://pack:,,application:%2C%2C%2C,OtherAssembly;component/lookup2.xml


text:
Q: spring boot security creates folder in war I added the following dependency to my project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<scope>provided</scope>
</dependency>

now a folder
"org/springframework/boot/loader"
next to my index.jsp and source folder
is created in my warfile.
It contains some compiled classes like "launcher.class", "JarLauncher.class" or "LaunchedURLClassLoader.class".
How can I tell my build not to create this folder?

A: Simple answer:
remove the spring-boot-maven-plugin
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>


text:
Q: is there any way to get image using latitude and longitude based on time? I am currently using google static maps api to get the image using center - longitude and latitude. Is there any way to get the image based on time like in 2016, 2017 etc for the same lat, long?

A: Currently, Google Static Maps API doesn't have any option to show historical satellite imagery. There is a feature request in Google issue tracker for this feature. You can see the feature request here:
https://issuetracker.google.com/issues/35826354
Feel free to star the feature request to add your vote and subscribe to notifications from Google.


text:
Q: Unable to update view in MVVM architecture android I am implementing MVVM approach in my app I have created separate repository class in which I am performing network requests data is fetching properly in fragment but when there is some network error progress bar in my activity keeps on it does not stop when there is some network error. How can I update views according to repository class as progress bar is defined in fragment and network error is given by repository class?
How to hide progress bar when there is some network error?
Below is my code:
MyRepository.class
public class MyRepository {

MutableLiveData<List<Facts>> mutableLiveData = new MutableLiveData<>();
Application application;

public MyRepository(Application application) {
    this.application = application;
}

public MutableLiveData<List<Facts>> getMutableLiveData(){

    Retrofit retrofit = RetrofitClient.getInstance();
    ApiService apiService = retrofit.create(ApiService.class);

    apiService.getFacts().subscribeOn(Schedulers.io())
                         .observeOn(AndroidSchedulers.mainThread())
                         .subscribe(new Observer<List<Facts>>() {
                             @Override
                             public void onSubscribe(Disposable d) {

                             }

                             @Override
                             public void onNext(List<Facts> facts) {

                                 if(facts.size() > 0 && facts != null){

                                     mutableLiveData.setValue(facts);
                                 }
                             }

                             @Override
                             public void onError(Throwable e) {

                                 TastyToast.makeText(application,e.getMessage(),TastyToast.LENGTH_SHORT,
                                         TastyToast.ERROR).show();
                             }

                             @Override
                             public void onComplete() {

                             }
                         });

       return mutableLiveData;
   }
}

HomeFragment.class
 public class HomeFragment extends Fragment {

 RecyclerView recycle;
 FactsAdapter adapter;
 FactsViewModel viewModel;
 ProgressBar prg;

 public HomeFragment() {
    // Required empty public constructor
 }

 @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
   // Inflate the layout for this fragment
 View view = inflater.inflate(R.layout.fragment_home, container, false);

recycle = view.findViewById(R.id.recycle);
prg = findViewById(R.id.prg);

LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
recycle.setLayoutManager(mLayoutManager);
recycle.setHasFixedSize(true);

viewModel = new ViewModelProvider(this).get(FactsViewModel.class);

viewModel.getAllFacts().observe(getViewLifecycleOwner(), new androidx.lifecycle.Observer<List<Facts>>() {
       @Override
       public void onChanged(List<Facts> facts) {

           prg.setVisibility(View.INVISIBLE);

           adapter = new FactsAdapter(facts,getActivity());
           recycle.setAdapter(adapter);
       }
   });

return view;

}

A: You can wrap your Fact around a Resource object having a data and status.
Resource example code
Your return type becomes Resource, onNext sets the data to facts and status to OK. onError sets the data to null and status to NETWORK_ERROR.
On your Fragment, you observe the Resource and check the status to handle errors and OK state.
Handling resource example


text:
Q: How to speed up R loop operations over 3 Dimensional Array of variable size? I have an R script that I wrote which simulates how long particles need to equilibrate in a room. The room is represented with a 3 dimensional array of size max_size. Currently the script works as it is intended, but the real run time of the script is so slow that it is nearly unusable. I have tried adjusting my algorithm to reduce the number of times that the array needs to be looped over, but it is still many magnitudes slower than when I wrote this code in FORTRAN previously. How can I adjust this script in order to reduce the runtime?
Below is my code.
#!/usr/bin/env Rscript
options(warn=1)
max_size <- 10
use_partition = 1

cube <- array(dim=c(max_size, max_size, max_size))
cube[,,]=0.0

diffusion_coefficient <- 0.175
room_dimension <- 5
mol_speed <- 250 # speed of molecules based on 100 g/mol at RT
timestep <- (room_dimension/mol_speed)/max_size # h in seconds
dist_between <- room_dimension/max_size
DTerm <- diffusion_coefficient*timestep/(dist_between*dist_between)
cube[1,1,1] <- 1.0e21 # initial mass of particles
time <- 0 # keep up with accumulated system time
ratio <- 0
part_height <- floor(max_size*0.75)
center <- floor(max_size/2)

# the partition is defined as:
#   1 space (index) "wide" on the X axis
#   spans 75% (rounded) of the "height" (Y axis)
#   spans 100% of the "depth" (z axis)
# partition spaces are indicated with the value -69.0
# partition spaces cannot be diffused from nor into
if(use_partition == 1) {
    for (j in 1:part_height) {
        cube[center,j,] <- -69.0 # flag partition spaces with -69.0
    }
}

repeat { #R replacement for Do While
    for (i in 1:nrow(cube)) {
        for (j in 1:ncol(cube)) {
            for (k in 1:max_size) {
                if(cube[i,j,k] != -69.0) {
                    for (off in seq(from=-1, to=1, by=2)) {
                        if (i+off >= 1 && i+off <= max_size) {
                            change <- (cube[i,j,k] - cube[i+off,j,k])*DTerm
                            cube[i,j,k] = cube[i,j,k] - change
                            cube[i+off,j,k] = cube[i+off,j,k] + change
                        }
                        if (j+off >= 1 && j+off <= max_size) {
                            change <- (cube[i,j,k] - cube[i,j+off,k])*DTerm
                            cube[i,j,k] = cube[i,j,k] - change
                            cube[i,j+off,k] = cube[i,j+off,k] + change
                        }
                        if (k+off >= 1 && k+off <= max_size) {
                            change <- (cube[i,j,k] - cube[i,j,k+off])*DTerm
                            cube[i,j,k] = cube[i,j,k] - change
                            cube[i,j,k+off] = cube[i,j,k+off] + change
                        }
                    }
                }
            }
        }
    }
    time = time+timestep

    #check mass for consistency
    sumval <- 0.0
    maxval <- cube[1,1,1]
    minval <- cube[1,1,1]
    for(i in 1:nrow(cube)) {
        for(j in 1:ncol(cube)) {
            for(k in 1:max_size) {
                if(cube[i,j,k] != -69.0) {
                    if(cube[i,j,k] > maxval) {
                        maxval = cube[i,j,k]
                    }
                if(cube[i,j,k] < minval) {
                    minval = cube[i,j,k]
                }
                    sumval = sumval + cube[i,j,k]
                }
            }
        }
    }
    ratio <- minval / maxval
    cat(time, " ", ratio, " ", sumval, "\n")
    if(ratio >= 0.99) {
        break
    }
}
cat("Box equilibrated in ", time,  " seconds of simulated time.\n")


text:
Q: Raphael js, how to get a circle's center x, y position? If I have a circle object
var c = paper.circle(...)
I would like to get this circle's center x, y position, how to get?

A: You can get the SVG attributes of cx and cy with:
c.attr('cx');

A: Do something like:
var c = paper.circle(...);
var centerX = c.attr('x') + c.attr('width') / 2;
var centerY = c.attr('y') + c.attr('height') / 2;


text:
Q: What response type is better to return from reactive endpoint if we return multiple objects? If we use reactive approach in Spring we can return Flux/Mono type in methods. So in controller it's good to wrap response ResponseEntity and return it and in case of endpoints which return one object we can write in reactive next code:
@GetMapping(value = "/to-do/{toDoId}", produces = {
            MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
    public Mono<ResponseEntity<ToDo>> getToDo(@Valid @PathVariable Long toDoId) {
        return repository.findById(toDoId)
                .map(ResponseEntity::ok);
    }

But what if we want to return Flux? After some experiments I found this solution:
@GetMapping(value = "/to-do", produces = {
            MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
    public ResponseEntity<Flux<ToDo>> getToDos() {
        return ResponseEntity.ok().body(
                repository.findAll()
        );
    }

But if I understand correct here in such format, response like ResponseEntity<Flux<ToDo>> will be blocking? So it's better to do something like <Flux<ResponseEntity<ToDo>> ? If it's so, how to get it? I should subscribe?

A: It seems you don't really use the ResponseEntity to customize the reponse status so, why not just return Mono or Flux?
@GetMapping(value = "/to-do/{toDoId}", produces = {
            MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
    public Mono<ToDo> getToDo(@Valid @PathVariable Long toDoId) {
        return repository.findById(toDoId);
    }

@GetMapping(value = "/to-do", produces = {
            MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE})
    public Flux<ToDo> getToDos() {
        return repository.findAll();
    }

In any case, according to the documentation it's perfectly fine to return ResponseEntity<Mono> and ResponseEntity<Flux>, both will provide an asynchronous, non-blocking response:

ResponseEntity<Mono> or ResponseEntity<Flux> make the response
status and headers known immediately while the body is provided
asynchronously at a later point. Use Mono if the body consists of 0..1
values or Flux if it can produce multiple values.

A: There are multiple ways you can return value using ResponseEntity from your reactive controller:
Publisher can be Mono or Flux

*

*ResponseEntity<Publisher<T>> - this makes the response status and headers known immediately while the body is provided asynchronously at some later point of time.

*Publisher<ResponseEntity<T>> - this provides all three: response
status, headers, and body, asynchronously at some later point of time. It allows
the headers and response status to vary depending on the outcome of
asynchronous handling.

Also it is possible to use the following construct, less common, though:

*

*Mono<ResponseEntity<Publisher<T>>> - provide the response status and headers asynchronously first, and later response body, also asynchronously


text:
Q: RSpec: how can I spy on interactions with an existing object? I have an existing stub object, that I am using as a collaborator in my tests:
cf_client = Aws::CloudFormation::Client.new(:stub_responses => true)
stack = described_class.new("name", cf_client)

The stub object (cf_client) was not created using rspec-mocks; it's a fake implementation provided by the aws-sdk gem, and has useful properties.
However, it doesn't provide message verification, so I am hoping to wrap in a proxy that records the received messages, so I can verify them later, while still delegating to the wrapped object, e.g.
cf_client = proxy_spy(Aws::CloudFormation::Client.new(:stub_responses => true))
stack = described_class.new("name", cf_client)

stack.create

expect(cf_client).to have_received(:create_stack)

Want I want/need is the proxy_spy method. Does something like this exist? Can I use RSpec's verifying proxies here?

A: You're looking for and_call_original.
cf_client = Aws::CloudFormation::Client.new(:stub_responses => true)
expect(cf_client).to_receive(:create_stack).and_call_original
stack = described_class.new("name", cf_client)
stack.create


text:
Q: Faking record id result in poor db performance? I have modeled some data into a table, but privacy is a very important issue.  Whenever I create a new record I look for an unused random 9 digit id.  (This is to avoid anybody being able to infer the order in which records were created in a worst case scenario.)  By faking the id field do I risk losing database performance because it is used for addressing data in anyway?  For SQLite3?  This is a RubyonRails3 app and am still in a dev environment so not sure if SQLite3 will go to prod.

A: CREATE TABLE    Bargains
        (
            RowID INT IDENTITY PRIMARY KEY,
            Code AS ABS(CHECKSUM(NEWID())),
            CustomerID INT
        )

CREATE TABLE    Bargains
        (
            RowID INT IDENTITY PRIMARY KEY,
            TheOtherBit VARCHAR(4) NOT NULL DEFAULT(SUBSTRING(CONVERT(varchar(50), NEWID()),
            CustomerID INT
        )

We use NEWID() to generate a "random" value, take a few digits from that, put that in a SEPARATE field, and incorporate it in the "pretty value" shown to the user (and required when the user retrieves the data, but not required internally).
So we have
MyID INT IDENTITY NOT NULL PRIMARY KEY ...

TheOtherBit VARCHAR(4) NOT NULL DEFAULT(SUBSTRING(CONVERT(varchar(50), NEWID())

but internally for us it would be ordered on RowID and of course u wont have to generate a number randomly either and the user does not get to see ur RowID...
Here is some working code to explain how u can create Unique ids within the database
USE TEST
GO
CREATE TABLE NEWID_TEST
(
ID UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY,
TESTCOLUMN CHAR(2000) DEFAULT REPLICATE('X',2000)
)
GO
CREATE TABLE NEWSEQUENTIALID_TEST
(
ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
TESTCOLUMN CHAR(2000) DEFAULT REPLICATE('X',2000)
)
GO

-- INSERT 1000 ROWS INTO EACH TEST TABLE
DECLARE @COUNTER INT
SET @COUNTER = 1

WHILE (@COUNTER <= 50)
BEGIN
   INSERT INTO NEWID_TEST DEFAULT VALUES
   INSERT INTO NEWSEQUENTIALID_TEST DEFAULT VALUES
   SET @COUNTER = @COUNTER + 1
END
GO

SELECT TOP 5 ID FROM NEWID_TEST
SELECT TOP 5 ID FROM NEWSEQUENTIALID_TEST
GO

A: Larger ID values do not make index lookups any slower.
Smaller values use fewer bytes when stored in the database file, but the difference is unlikely to be noticeable.
For optimal performance, you should declare your ID column as INTEGER PRIMARY KEY so that ID lookups do not need a separate index but can use the table structure itself as index.


text:
Q: Getting IE8 compatibility with EaselJS and ExplorerCanvas I am using EaselJS and want to allow for backwards compatibility with ExplorerCanvas.
This should be possible using the following code (see here):
createjs.createCanvas = function () { ... return canvas implementation here ... }

However, If I put an alert in this function and run the code, the function is never run.
How do I go about getting this to work?
Edit:
Here is a simplified example of the code I am using:
<!DOCTYPE html>

    <meta charset='utf-8' />

        <button id='load'>load</button>

This example will run in Chrome and IE9 as a native canvas element is created and used. However in IE8 it fails.

A: I ran across this issue as well, trying to get ExCanvas to play nice with EaselJS. Here is how I got it working. Hope this helps with your image issue.

*

*Get the source code for EaselJS : https://github.com/gskinner/EaselJS.git. This will get all the javascript files separated out into their own parts.

*Copy all those files over to a "easel" folder in your project directory.

*The order in which the files are loaded is important, so see below on how to do it.

*EaselJS has an option to override the createCanvas method, which is required to use ExCanvas with it. This happens after loading the SpriteSheet.js file, and BEFORE loading Graphics.js, DisplayObject.js, Container.js, etc. In the code below, I used jQuery to load the rest of the js files that easelJs needed. This all happens in the $(document).ready() function.

*If done correctly, you should see a 700 x 700 canvas with a red line from top left to bottom right in IE (tested in 8).
head>

        <![endif]-->

var el = document.createElement('canvas');
G_vmlCanvasManager.initElement(el);
var ctx = el.getContext('2d');

EDIT:
After further investigation i came to the following conclusions!
There are multiple reasons for not being able to include the image into the canvas:

*

*1st probably there is a bug in the excanvas code for not being able to mimic the native canvas features. I used with more success the modified sancha code, which you can obtain here: http://dev.sencha.com/playpen/tm/excanvas-patch/excanvas-modified.js. See live example here: http://jsfiddle.net/aDHKm/  (try it on IE).

*2nd before Easeljs initialize the core objects and classes first is searching for the canvas element existence. Because IE < 9 doesn't have implemented the canvas it's obvious that easeljs core graphics API's can not be instantiated. I think these are the two main reasons that your code is not working.

My suggestion is to try to remake the code without the easeljs. I made a fiddle with the necessary modification to show you how can be done without easeljs: http://jsfiddle.net/xdXrw/. I don't know if it's absolute imperative for you to use easeljs, but certainly it has some limitations in terms of IE8 hacked canvas.


text:
Q: Changing .Net assembly name at runtime I need to load an assembly with reflection and rename it. Of course I cannot just rename the file: I must also change its internal information.
How can I do so?

A: This isn't possible.  The name of an Assembly is immutable once loaded into the CLR.  You would need to rename it before it was loaded

A: You can probably copy the assembly into a new dynamic assembly and then load the dynamic assembly: http://msdn.microsoft.com/en-us/library/8ffc3x75.aspx
But if there's another way to accomplish what you are looking for I'd recommend exploring that option, creating assemblies at run time is not going to be easy.


text:
Q: What is the difference between assertions and unparameterized predicates in Alloy? Is there a difference between an assertion and an unparameterized predicate in Alloy? You can use the "check" command on both unparameterized predicates and assertions to find a counterexample to a given constraint. Are these two constructs essentially the same? If so, why does the language have two constructs that serve the same purpose?

A: assert is from an earlier version of alloy, before you could check predicates. As of Alloy 4 that restriction on predicates has been removed and there's no reason to use assert statements in new specifications.


text:
Q: Laravel api authenication not working I am attempting to use authentication for application through api, but when I set the guard in middleware it does not work and returns 403 exception.
I have this route guard in controller constructor:
public function __construct()
{
    $this->middleware('auth:api');
}

Anytime I use Auth::user() the 403 is returned. Is something being missed?

A: For using Auth::user() make sure your routes are protected by api midlleware()
For using a user u can specify
Auth::gaurd('api')->user();

Hope this helps


text:
Q: How to install "Visual Studio Installer"? I adopted an old VB6 program and now need to do few code changes, I am being have Visual Studio 6.0 and service package 6 installed, When I opened the solution file I got an error message "The application for 'xxx.wip' is not installed", so I guess this could be caused by that I missed the Visual Studio Installer.
Then I found out a "Visual Studio Installer 2" on internet, after having downloaded, the file size is around 8.52 MB and it was a Win32 Cabinet Self-Extractor, I double-clicked it and exacted to a place but I got a "VSI2.cab" file.
So there have NO any install executable file after exaction, my question is how I can install Visual Studio Installer I downloaded? how Visual Studio 6.0 aware it and will able to open ".SLN" file without errors, I need copy it to specific folder by handy or even I get wrong download? if so please share the link to me.

A: Visual Studio Installer (the real one) is no longer available from Microsoft and VSI2.cab appears to be just part of the VSI installer package.
I have a copy that is temporarily available for download (Assuming you agree to all the original conditions from Microsoft that I can't remember here) but I still recommend using something that's built this century, maybe even this decade :)


text:
Q: Cannot log into Yahoo! Messenger I am using the Yahoo Messenger client.  The problem is that it will not log in until after I have been logged into windows for 5 minutes or so.  If I try and connect before 5 minutes, it just sits there spinning.
Yahoo! Messenger (8.1.0.421)
MyYahoo Module (8.0.0.1)
Does anyone have any ideas.  I don't really know where to start on resolving this issue.
Thanks!

A: Are you able to surf the net at that time? Perhaps you are not connected to the network yet. Doesn't seem all that likely, but maybe if you are on wireless I could see it taking a while.

A: Might be a service starting up on windows that is interfering with the requirements of YahooIM. Is it literally "five minutes," or just several minutes?

A: I know AIM does this, but not sure if Yahoo Messenger also started doing this. If you fail your sign on too many times per minute then you get locked out of your account for 5 minutes. It's a security feature called password spinning. Check and see if anything is trying to make a yahoo messenger connection during startup, and disable it.

A: i used to have this problem with vista , but it sorted out withupdating yahoo masseneger.
try Yahoo! Messenger 9.0.0.2162
it should solve problem if you are properly connected to internet.
otherwise use some alternatives like pidgin or trillian astra


text:
Q: How to migrate a class using Generic enums with the Entity Framework Core? How would you migrate this Car Class to a database using the Entity Framework?
I have a Main car class (which inherits from a Car Interface Class) with one Generic property called Part
public class Car<Parts> : GenericCarInterface
{
    public Parts Part { get; set; }
}

Then I have several enums representing different parts that can be passed into the Generic Parts property of the Car Class
public enum VokswagenParts
{
    VWWheels,
    VWLights,
    VWEngine
}

public enum TyotaParts
{
    ToyotaSpoiler,
    ToyotaAirFilter,
    ToyotaBrakes
}

public enum FiatParts
{
    FiatExhaust,
    FiatSuspension,
    FiatCVOuter
}

I envisage setting up an ApplicationDbContext as follows but the EF does not know what to make of the Part property
public class ApplicationDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"ConnectionStringHere");
    }

    public DbSet<GenericCarInterface> Cars { get; set; }
}

Any Ideas on the ways that this can be accomplished using Entity Framework Core?

A: Looking at your enums, it looks like each part has a unique name. if you don't mind whether your parts are grouped or not, you could put all your parts together in single enum.
public enum Parts {
    VWWheels,
    VWLights,
    VWEngine,
    ToyotaSpoiler,
    ToyotaAirFilter,
    ToyotaBrakes,
    FiatExhaust,
    FiatSuspension,
    FiatCVOuter
}

then in your Car class you can do this
public Parts Parts { get; set; }

EF should be able to handle the rest.

A: I think i may have figured out a solution.
If i can create a separate class in my repository to hold the enum number values and the enum type names:
public class Car
{
     public Guid CarId { get; set; }
     public Part Part { get; set; }
}

public class Part
{
    public Guid CarId { get; set; }
    public Guid PartId { get; set; }
    public int Enum { get; set; }
    public string EnumName { get; set; }
}

Then I can persist that standard class to the database then simply re-compile the code back to the original Car class format just before transferring between layers
I might create a separate enum for the part names just to keep it strongly typed but I like the idea of having the names persisted not just enum numbers


text:
Q: how to hide a text entry in the print preview c# There is no error showing. My selection is not working, I need to hide a specific field. If the field is empty the title of that field should be hidden.
I am using a printpreviewdialog to preview the details.
my code:
 private void DVPrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {

        //e.Graphics.DrawString("NAME          : " + dgvItem.CurrentRow.Cells[4].Value, new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(25, 400));
        e.Graphics.DrawString("WEIGHT      : " + txtGemWeight.Text + " Cts", new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(25, 440));

        //string txtSpecification = false;

        if (txtSpecification.Text == null)
        {
            txtSpecification.Visible= false;
        }
        else
        {
            e.Graphics.DrawString("SPECIFICATION   : " + txtSpecification.Text, new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(25, 480));
        }
    }
}

A: if(txtSpecification.Text == null)

change it to
if(txtSpecification.Text == "")

because text by default value is not null.


text:
Q: Getting Parse PFUser: relational data I have a Parse class "Posts". "Posts" has a column, "user" which stores the user that made the post. It is of type Pointer<_User>.
I want to be able to retrieve the user, and then get an image stored in the User class.
So far I have:
PFQuery *postQuery = [PFQuery queryWithClassName:@"Post"];
[postQuery includeKey:@"user"];
PFObject *result = [postQuery getFirstObject];

if (result) {
    NSLog(@"successful query"); //Successful!
} else {
    NSLog(@"unsuccessful query");
}

PFUser *user = result[@"user"];
if (user) {
    NSLog(@"successful found user");
} else {
    NSLog(@"unsuccessful found user"); //Not successful
}

I successfully get "result", but I no "user". What am I missing?

A: In this case, the User object pointed to had been deleted.  If a pointer column is included and it resolves to a non-existing object, it won't fail, but the object won't be fetched/included either.  You can probably detect this scenario after query w/ includeKey by checking for the createdAt field.


text:
Q: EF6 Method not found set_SqlServerTypesAssemblyNames I'm having difficulty deploying an console app onto a server.
I am using EF6 (6.3.0) and SqlServerTypes 14 (14.0.1016.290) and initializing before any spatial calls are made as recommended
SqlProviderServices.SqlServerTypesAssemblyName = Assembly.GetAssembly(typeof(Microsoft.SqlServer.Types.SqlGeography)).FullName; //"Microsoft.SqlServer.Types, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91";
SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

However on the setter line, the following error is thrown

System.MissingMethodException: Method not found: 'Void System.Data.Entity.SqlServer.SqlProviderServices.set_SqlServerTypesAssemblyName(System.String)'.

I have made sure that SqlServerTypes dlls are present in the bin directory.
I read that EF6 only supports up to SqlServerTypes 11 which I tried, however no luck there.
App is working fine locally.
Edit: I have now installed SQL Server System CLR Types on the server to no avail.

A: This error (and other like it) can occur when your development runtime and deployment environment have different versions of packages installed in the GAC and not all dlls from the development environment are copied into the deployment environment.
This question has guidance that might be useful: EntityFramework.SqlServer.dll not is getting added to the published folder only when I publish in RELEASE mode

*

*My preferred workaround is to follow this advice and make a code reference to a class or function within each of the DLLs that you depend on to 'trick' visual studio into including the dll in the output by default AND to force a compile time error if that assembly is not available (useful in situations where the DLL is used via injection).

If you don't know which dll might be the cause and the app runs fine in development, then a simple fix can be to mark ALL references as Copy Local = True:

Then if that works you can remove the DLLs from the output that you think you don't need, iteratively testing that the app still runs until you find the minimal set of dlls that you need to deploy


text:
Q: How to track successive CGAffineTransforms so as to arrive at a specific point on screen? How do you execute multiple CGAffineTransform operations (in animation blocks) without keeping track of every operation executed?
The translation operation doesn't take x,y coordinates but instead values to shift by.  So unless you know where you are currently translated to, say at "location 2," how do you know what values to shift by to get to "location 3?"
For example:
A UIView's frame is at (0, 0) - Position 1.  I set the transform to translate to (768, 0) and rotate -90 degrees - Position 2.  Some time passes and now I want to move to (768, 1024) and rotate another -90 degrees - Position 3.
How do I know what to translate by to move from Position 2 to Position 3?
In context, I'm trying to achieve an iPad view like the following:

*

*a UIView that takes up the entire screen

*a UIToolbar that takes up the top edge and is on top of the UIView

*when the iPad rotates, the UIView stays with the device, but the toolbar will rotate so that it is always on the top edge of the screen.

I am using CGAffineTransform translate and rotate to move the toolbar.  Works great, except when I rotate the iPad multiple times.  The first translate/rotate will work perfect.  The following transforms will be off because I don't know the correct values to shift by.
UPDATE:
It looks like if I take the current translation (tx, ty) values in the UIView.transform struct and use the difference between them and the new location, it works.  However, if the view has been rotated, this does not work.  The tx and ty values can be flipped because of the previous rotation.  I'm not sure how to handle that.
UPDATE 2:
Doing some research, I've found that I can get the original, unrotated points from tx, ty by getting the abs value of the points and possibly swapping x and y if the UIView is perpendicular.  Now I am stuck figuring out how to correctly apply the next set of transforms in the right order.  It seems no matter how I concat them, the UIView ends up in the wrong place.  It just seems like this is all too complicated and there must be an easier way.

A: The answer is, apparently, you don't track the transforms.
So the way to rotate the toolbar around the screen is by not concatenating a rotate and translate transform.  Instead, create a rotate transform and set the frame in the animation block.  Further, based on the new UIInterfaceOrientation, set the degrees to rotate based on the compass values of 0, -90, -180, -270.  Also, set the frame size base on the same locations.
So:
CGPoint portrait = CGPointMake(0, 0);
CGPoint landscapeLeft = CGPointMake(768 - 44, 0);
CGPoint landscapeRight = CGPointMake(0, 0);
CGPoint upsideDown = CGPointMake(0, 1024 - 44);

CGSize portraitSize = CGSizeMake(768, 44);
CGSize landscapeLeftSize = CGSizeMake(44, 1024);
CGSize landscapeRightSize = CGSizeMake(44, 1024);
CGSize upsideDownSize = CGSizeMake(768, 44);

CGFloat rotation;
CGRect newLocation;
switch(orientation) {
    case UIDeviceOrientationPortrait:
        NSLog(@"Changing to Portrait");
        newLocation.origin = portrait;
        newLocation.size = portraitSize;
        rotation = 0.0;
        break;

    case UIDeviceOrientationLandscapeRight:
        NSLog(@"Changing to Landscape Right");
        newLocation.origin = landscapeRight;
        newLocation.size = landscapeRightSize;
        rotation = -90.0;
        break;

    case UIDeviceOrientationLandscapeLeft:
        NSLog(@"Changing to Landscape Left");
        newLocation.origin = landscapeLeft;
        newLocation.size = landscapeLeftSize;
        rotation = -270.0;
        break;

    case UIDeviceOrientationPortraitUpsideDown:
        NSLog(@"Changing to Upside Down");
        newLocation.origin = upsideDown;
        newLocation.size = upsideDownSize;
        rotation = -180.0;
        break;

    default:
        NSLog(@"Unknown orientation: %d", orientation);
        newLocation.origin = portrait;
        newLocation.size = portraitSize;
        rotation = 0.0;
        break;
}

CGRect frame = newLocation;
CGAffineTransform transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(rotation));

if(lastOrientation) {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationBeginsFromCurrentState:YES];
}

toolbar.transform = transform;
toolbar.frame = frame;

// Commit the changes
if(lastOrientation) {
    [UIView commitAnimations];
}

lastOrientation = orientation;

This works beautifully.  However, an unexpected problem is that UI elements that iOS shows on  your behalf are not oriented correctly.  I.e., modal windows and popovers all keep the same orientation as the underlying UIView.  That problem renders this whole thing moot.


text:
Q: Terraform to show available key pair name in aws I am working on an automation so for that I want to know if terraform can just show me current available key pair name (ssh key created by users manually on AWS UI) which are present on AWS?
Once I get the key pair name then I will be using a loop to import then using import command.
terraform import aws_key_pair.importexample

A: You could import those resources - but I suspect they will be of limited use initially, other than being able to delete them, or perhaps recreate them and then re-issue - you would also need to issue a replacement private key.
The limited use is due to the fact that there will be no private key (at least not in your posession), and no public key (easily) available. :-/
You can use the aws_key_pair data source to get information about a specific aws_key_pair or all of them.
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/key_pair
eg.
data "aws_key_pair" "example" {
  key_name = "test"
  filter {
    name   = "tag:Component"
    values = ["web"]
  }
}

output "fingerprint" {
  value = data.aws_key_pair.example.fingerprint
}

output "name" {
  value = data.aws_key_pair.example.key_name
}

output "id" {
  value = data.aws_key_pair.example.id
}

A simple way to get the public key would use EC2 or ECS, then capture it to allow you to insert it into the aws_key_pair resource in your terraform code.
Perhaps you could write a user_script to run on boot and push the contents of the authorized_keys file to an S3 bucket - but you would have to do that for as many times as you have aws_key_pairs...
Luckilly terraform will do that in parallel if there are no dependancies to prevent it. :-D
So if you get the list of aws_key_pair entries from the data source, and then loop through them with a for_each you could do it, I guess... YMMV
You'll still be in a situation of having to re-create each aws_key_pair thought [see note from Hashicorp below], but at least you could do so knowing you now have the public key, and as it will be IaC life would be better. ;-)
If you craft your terraform output right, you could make life a little easier for importing the resources with terraform import
You could also go the awscli route and generate the necessary terraform code to import and create the resources in one shot.
This snippet may be of use to you if you use aws-vault - though obviously it can be easilly modified if not.
for profile in $(aws-vault list --profiles | sort);
do
  echo -e "####################\nProfile: $profile";
  for region in $(aws ec2 describe-regions | jq -r '.Regions[].RegionName' | sort);
  do
    echo "  Region: $region";
    aws-vault exec $profile aws --region $region ec2 describe-key-pairs;
  done;
done

It shouldn't be too difficult to loop over the results and inject the apropriate values into the key_pair resource once you have each public key to hand;
resource "aws_key_pair" "perhaps-use-a-template-for-this" {

  key_name        = var.key_name
  public_key      = var.public_key

  tags = var.tags
}

Note from Hashicorp:

Key Pairs can be imported using the key_name, e.g.,

$ terraform import aws_key_pair.deployer deployer-key

NOTE: The AWS API does not include the public key in the response, so terraform apply will attempt to replace the key pair. There is currently no supported workaround for this limitation.


text:
Q: How to reference current search results in a subquery I am trying to find sentences with two words adjecent to each other, using Postgres directly, not some command language extension. My tables are:
TABLE word (
    spelling text,
    wordid serial
)
TABLE sentence (
    sentenceid serial
)
TABLE item (
    sentenceid integer,
    position smallint,
    wordid integer
)

I have a simple query to find sentences with a single word:
SELECT DISTINCT sentence.sentenceid
FROM item, word, sentence
WHERE
    word.spelling = 'word1' AND
    item.wordid = word.wordid AND
    sentence.sentenceid = item.sentenceid

and what I want is to filter that in turn by some word whose corresponding item has a item.sentenceid = the current query result's item (or sentence).sentenceid and
item.position = the current query result's item.position + 1
I don't see that ALIAS's work, and I don't know how to reference current state of the query in a subquery.

A: select distinct sentenceid
from
    item i
    inner join
    item i2 using (sentenceid)
    inner join
    word w on w.wordid = i.wordid
    inner join
    word w2 on w2.wordid = i2.wordid
where
    w.spelling = 'word1' and
    w2.spelling = 'word2' and
    i.position = i2.position - 1


text:
Q: Redireccionar una ruta por un onclick en VB.NET Cordial Saludo,
Estoy trabajando con VB.NET y tengo un enlace a en el code behind que me lleva a otro sitio, necesito que el enlace se pase por un onclick dentro del a pero no logro escapar las comillas correctamente y no me ejecuta la redirección del enlace.
Cualquier ayuda es agradecida.
COD ORIGINAL VB.NET:

Opciones_Trabajador.Controls.Add(New LiteralControl("
" & sOpciones.Rows(j).Item(0).ToString & "
"))

MI INTENTO:

Opciones_Trabajador.Controls.Add(New LiteralControl("
" & sOpciones.Rows(j).Item(0).ToString & "'
"))

Pero no me funciona cuando agrego en onclick = "location.href = """

A: Encontre la solución con el siguiente código.
lo que buscaba era que el hipervinculo de la etiqueta  no se muestre en la parte de abajo bottom - left.
Con esto lo solucione.
Asigne un Data en la etiqueta y la recorri por un bucle for.

  dashboardDashboard


text:
Q: Matching with Rc> Consider the following code - which compiles and works:
use std::rc::Rc;
use std::cell::RefCell;
use crate::Foo::{Something, Nothing};

enum Foo {
    Nothing,
    Something(i32),
}

fn main() {
    let wrapped = Rc::new(RefCell::new(Foo::Nothing));
    //....

    match *wrapped.borrow() {
        Something(x) => println!("{}", x),
        Nothing => println!("Nothing"),
    };
}

Now I want to match two wrapped values instead of just one:
use std::rc::Rc;
use std::cell::RefCell;
use crate::Foo::{Something, Nothing};

enum Foo {
    Nothing,
    Something(i32),
}

fn main() {
    let wrapped1 = Rc::new(RefCell::new(Foo::Nothing));
    let wrapped2 = Rc::new(RefCell::new(Foo::Nothing));
    //....

    match (*wrapped1.borrow(), *wrapped2.borrow()) {
        (Something(x), Something(y)) => println!("{}, {}", x, y),
        _ => println!("Nothing"),
    };
}

Now this will give the compile error:
error[E0507]: cannot move out of dereference of `std::cell::Ref<'_, Foo>`
  --> src\main.rs:16:12
   |
16 |     match (*wrapped1.borrow(), *wrapped2.borrow()) {
   |            ^^^^^^^^^^^^^^^^^^ move occurs because value has type `Foo`, which does not implement the `Copy` trait

error[E0507]: cannot move out of dereference of `std::cell::Ref<'_, Foo>`
  --> src\main.rs:16:32
   |
16 |     match (*wrapped1.borrow(), *wrapped2.borrow()) {
   |                                ^^^^^^^^^^^^^^^^^^ move occurs because value has type `Foo`, which does not implement the `Copy` trait

I do not quite understand the fundamental difference between the semantics of the two examples. Why is it happening and what would be the correct way of making the second snippet work?

A:     match (*wrapped1.borrow(), *wrapped2.borrow()) {

You created a tuple here on the spot. And the values were being moved into the newly created tuple. This works though:
use std::rc::Rc;
use std::cell::RefCell;
use crate::Foo::Something;

enum Foo {
    Nothing,
    Something(i32),
}

fn main() {
    let wrapped1 = Rc::new(RefCell::new(Foo::Nothing));
    let wrapped2 = Rc::new(RefCell::new(Foo::Nothing));

    match (&*wrapped1.borrow(), &*wrapped2.borrow()) {
        (Something(x), Something(y)) => println!("{}, {}", x, y),
        _ => println!("Nothing"),
    };
}


text:
Q: How to replace multiple values in np.where? IF "AUTHORITY_CONTACTED" is NOT "Police" and POLICE_REPORT_AVAILABLE == 1
THEN Update "AUTHORITY_CONTACTED" to Police.
The unique values for AUTHORITY_CONTACTED are Ambulance, Police, None, and Others and POLICE_REPORT_AVAILABLE is a column that has 0 and 1 as its unique values which tells if the document is available if the AUTHORITY_CONTACTED is police.
Below is my code on the above query which was taken from Update data frame values as per multiple where condition using numpy
dataset['AUTHORITY_CONTACTED'] = np.where((dataset['AUTHORITY_CONTACTED'] != 'Police') & (dataset['POLICE_REPORT_AVAILABLE'] == 1), dataset['AUTHORITY_CONTACTED'].replace('Ambulance', 'Police'), dataset['POLICE_REPORT_AVAILABLE'])

*

*How can I replace multiple values in a where?

*After I run the code for the above query dataset['AUTHORITY_CONTACTED'] column is filled with 1 rather than replacing Ambulance with Police

Given dataset:

AUTHORITY_CONTACTED
POLICE_REPORT_AVAILABLE

Police
1

Ambulance
0

None
0

Others
1

Ambulance
1

Expected Output:

AUTHORITY_CONTACTED
POLICE_REPORT_AVAILABLE

Police
1

Ambulance
0

None
0

Police
1

Police
1

How can I solve these issues?

A: Try this:
# Using np.where
dataset["AUTHORITY_CONTACTED"] = np.where(
    dataset["AUTHORITY_CONTACTED"].ne("Police") & dataset["POLICE_REPORT_AVAILABLE"].eq(1),
    "Police",
    dataset["AUTHORITY_CONTACTED"]
)

# Slightly shorter code using pd.Series.mask
dataset["AUTHORITY_CONTACTED"] = dataset["AUTHORITY_CONTACTED"].mask(
    dataset["AUTHORITY_CONTACTED"].ne("Police") & dataset["POLICE_REPORT_AVAILABLE"].eq(1),
    "Police"
)


text:
Q: ¿Como puedo hacer que el código de un slider que funcione para 3 sliders? quiero hacer un código bien optimizado(para que no me ocupe mucho espacio en el js) con js vanilla y tengo 3 sliders independientes pero que se repite mucho el código ¿como puedo hacer para que el slider funcione en los 3 ocupando solo un codigo? mi idea era algo así como se hace en css .active__1, .demo__1:hover, .active__2, .demo__2:hover, .active__3, .demo__3:hover { opacity: 1;} pero con las  variables de js
todo esto lo quería hacer con un document.getElementsByCLassName o con querySelectorAll ¿se pueden agregar varias clases al mismo tiempo con una sola variable?

//SLIDER"1
document.addEventListener('DOMContentLoaded', function slider()  {

   let indice1 = 1;
     muestrario1( indice1 );

function avanzarFoto1(n1){
    muestrario1( indice1+=n1 );
}

 function posicion1(n1){
     muestrario1( indice1=n1 );
 }
 setInterval(function tiempo1(){
          muestrario1( indice1+=1 )
 },3000);
 function muestrario1(n1){
     let ite1;
     let imagenes1 = document.getElementsByClassName('slider-img__1, slider-img__2');
     let controlNavImgs1 = document.getElementsByClassName('li-control-nav__1,');

     if(n1 > imagenes1.length ){
         indice1 = 1;
     }
     if(n1 < 1){
         indice1 = imagenes1.length;
     }
     for(ite1 = 0; ite1 < imagenes1.length ; ite1++){
         imagenes1[ite1].style.display = 'none';
     }
     for(ite1 = 0; ite1 < controlNavImgs1.length ; ite1++){
         controlNavImgs1[ite1].className = controlNavImgs1[ite1].className.replace(" active", "");
     }

     imagenes1 [indice1-1].style.display = ' block';
     controlNavImgs1[indice1 -1].className += ' active';

 }

})
//lightbox

function openModal1() {
    document.getElementById("the-modal__1").style.display = "block";
  }

  function closeModal1() {
    document.getElementById("the-modal__1").style.display = "none";

  }

  let lightboxIndex1 = 1;
  showSlides1(lightboxIndex1);

  function plusSlides1(num1) {
    showSlides1(lightboxIndex1 += num1);
  }

  function currentSlides1(num1) {
    showSlides1(lightboxIndex1 = num1);
  }

  function showSlides1(num1) {
    let it1;
    let slides1 = document.getElementsByClassName("light-slides__1");
    let dots1 = document.getElementsByClassName("demo__1")
   /* let captionText = document.getElementById("caption");*/
    if (num1 > slides1.length) {lightboxIndex1 = 1}
    if (num1 < 1) {lightboxIndex1 = slides1.length}
    for (it1 = 0; it1 < slides1.length; it1++) {
        slides1[it1].style.display = "none";
    }
    for (it1 = 0; it1 < dots1.length; it1++) {
        dots1[it1].className = dots1[it1].className.replace(" active", "");
    }
    slides1[lightboxIndex1-1].style.display = "block";
    dots1[lightboxIndex1-1].className += " active";
  /*  captionText.innerHTML = dots[lightboxIndex1-1].alt;*/
  }

  ×

1 / 91

2 / 91

3 / 91

4 / 91

5 / 91

6 / 91

7 / 91

8 / 91

9 / 91

10 / 91

11 / 91

12 / 91

13 / 91

14 / 91

15 / 91

16 / 91

17 / 91

18 / 91

19 / 91

20 / 91

❮
❯


text:
Q: MDX - Dynamically Select Last Date among the dates Filtered on the Report I have a Measure - 'TEST' which is SUM across all the Dimensions except across DATE Dimension for which we need the value on the Last Day.
I created the Measure with an aggregate as 'SUM' and created a Scope statement to handle the exception
 SCOPE([Date].[Date].[All])
   THIS = TAIL([Date].[Date].MEMBERS,1).ITEM(0) ;
 END SCOPE

Its working well and picking up the Last day's value. But the problem is its always picking up the Last day's value and doesn't respect the Filters on the report.
For eg. If I have
Jan 1 - 100 ,
Jan 2 - 200 ,
Jan 3 - 300
When I get a report for Jan 1 and Jan 2 --- I do expect to see 200. Instead i get 300 with the above MDX.
Thanks. any help is much appreciated.

A: You could try to add EXISTING to your expression. This evaluates the members currently available due to filters or row or column headers. Your expression would then be
TAIL(EXISTING [Date].[Date].MEMBERS,1).ITEM(0) ;


text:
Q: SAML DNS Resolution Issue We have an application using the Spring SAML Extension and we have set it up as an SP that works running on localhost against SSOCircle. We have now deployed in our customer's test environment and we are trying to get it to work with our customer's IDP.
We gave our metadata to the IDP, substituting http://myapp-test.acme.com:8080/myapp/saml/SSO for http://localhost:8080/myapp/saml/SSO.
After authentication, we see this in the logs:
o.s.s.s.m.MetadataGeneratorFilter -
Generated default entity base URL http://someappserver.acme.com:8080/myapp based on values in the first server request.
org.opensaml.common.SAMLException: Intended destination
http://myapp-test.acme.com:8080/myapp/saml/SSO doesn't match any of the endpoint URLs for profile urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser
In the browser window, we see that the request goes to http://someappserver.acme.com:8080/myapp/saml/SSO.
So http://myapp-test.acme.com:8080/myapp/saml/SSO resolves to
http://someappserver.acme.com:8080/myapp/saml/SSO
How can we change our code / configuration to handle this? I don't think we should hard-code the metadata to the app server.

A: The URLs in the Service Provider metadata must correspond to real URLs where your Service Provider receives SAML messages from IDP. In this case the two differ.
You can update your securityContext.xml and change bean metadataGeneratorFilter by providing property entityBaseURL, with the correct URL, e.g.:
<bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
    <constructor-arg>
        <bean class="org.springframework.security.saml.metadata.MetadataGenerator">
            <property name="entityBaseURL" value="http://myapp-test.acme.com:8080/myapp"/>
        </bean>
    </constructor-arg>
</bean>

Without setting this property, Spring SAML defines the entityBaseURL and generates metadata with it based on the first request it receives. In case your application is available on multiple URLs this can of course be a different URL than the one your IDP actually sends messages to.
In case the internal URL as seen by the application server differs from the URL used by the caller (as in your case with the DNS resolution), you can force Spring SAML to think it's deployed behind a specific public URL by changing bean contextProvider to:
<bean id="contextProvider" class="org.springframework.security.saml.context.SAMLContextProviderLB">
    <property name="scheme" value="http"/>
    <property name="serverName" value="myapp-test.acme.com"/>
    <property name="serverPort" value="8080"/>
    <property name="includeServerPortInRequestURL" value="true"/>
    <property name="contextPath" value="/myapp"/>
</bean>

You can find more details in Spring SAML manual chapter Reverse proxies and load balancers.


text:
Q: Hidden controls appearing in web instance[Labview] I have created an application in which the vi has some controls and these controls are useful only during the development and on special instance can be unlocked in the application. i basically use app.kind property node to determine what environment the vi is running in and suitably hide/unhide the controls.
I have the application published on the web using the NI Web publishing tool. The computer which hosts the app works fine(and these controls remain invisible) but these controls can be sen on the web page. The vi is in "Embedd" mode. As a workaround i have pushed these controls some distance away and hence avoided the user from knowing about it. but this introduces the problem that i cannot view these controls when i unlock them.
Any help would be greatly appreciated.

A: You have built a stand-alone application and enabled web server, correct?
Are you sure the web panel is connecting to the stand-alone application (app.kind=2)
and it is not reaching the development LabView (app.kind=1) still listening on that web server port?
I would add an indicator to display the value of app.kind at all times.
What happens if you toggle the hidden fields on and off? I would add a button to do this on the vi.
Do they disappear/reappear reliably in the window where you have control?
Also, you said this was in Embedded mode - but are you also transferring control to the web page?
Those are some approaches I'd try to help pin this down.


text:
Q: GCP Dataflow throws exception Shuffle key too large I have a piece of code that groups my data but it throws an exception when I do output.
This class is used as key in KV
class CKey {
    private Long id;
    private Long subId;
}

It's part of my Dataflow job
TupleTag<CItem> itemsTuple = //...
TupleTag<CMeta> metaTuple = //...

//...

PCollection<KV<CKey, CItem>> items = null;
PCollection<KV<CKey, CMeta>> meta;

KeyedPCollectionTuple.of(itemsTuple, items).and(metaTuple, meta.next())
        .apply(CoGroupByKey.create())
        .apply(new CustomGroupPairsFn());

Custom function to join data
class CustomGroupPairsFn extends DoFn<KV<CKey, CoGbkResult>, MyCustomObject> {

        @ProcessElement
        public void processElement(@Element KV<CKey, CoGbkResult> element, OutputReceiver<MyCustomObject> out) {
            CoGbkResult pair = element.getValue();
            Iterator<CItem> citem = pair.getAll(ITEMS).iterator();
            Iterator<CMeta> cmeta = pair.getAll(METADATA).iterator();
            try {
                out.output(new MyCustomObject(citem.next(), cmeta));
            } catch (Exception e) {
                log.error("Error occurred", e);
            }
        }
    }

There is only 1 line of code in try and exception is thrown inside, exception:

How can I fix the issue?

A: This error happens because you're shuffling a key that is too large.
What does this mean? In Dataflow, the largest shuffle key allowed is 1.5 MB for streaming pipelines. You seem to have an element key that is larger than that.
Perhaps your pipeline has a GroupByKey/Shuffling operation somewhere unexpected, so that's why it would be great to have more details about it.


text:
Q: sending and receiving emoticons to webservice I have implemented the https://github.com/ankushsachdeva/emojicon lib for emoticons and emoticons get displayed in the edit text. Now I have edit text that takes in both text and emoticons. I want the text/emoticons entered in the edit text to be sent to the web service. when I just say get text from that edit text I can see only '??' of the emoticons on the server.I know i got to convert the emoticon to Unicode and then send it but I don't know how to implement it and also how to decode only the emoticons in the edit text. Please help me.
I just get the text from the edit text and save it in a 'userstatus' string and pass it to json as
List<NameValuePair> params = new ArrayList<NameValuePair>();

         Log.d("userstatus",userstatus);

        params.add(new BasicNameValuePair("my_status",userstatus));
         params.add(new BasicNameValuePair("user_id",userid));

          try{
              // getting JSON string from URL
               JSONObject json3 = jParser.makeHttpRequest(url_updateprofilestatus, "POST", params);

My json class
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

A: Emoticons are nothing but special sequence of text which refer to some emoticons on your device. While sending emoticons you don't actually send the emoticons but a sequence of text character which is associated with it. Once the device receives it, it replaces that particular text with the right emoticons (image). Like (^) is equivalent to cake emoticons in Skype.

A: I had the same issue, solved by adding in the POST method
Make sure that in the Logger you get question marks with a black background to make sure that's a emoticon
Then add:
 if (json != null)
 {
        httpPost.setEntity(new StringEntity(json, "UTF-8"));
 }