text:
Q: Pass a dict to scikit learn estimator I am trying to pass model parameters as a dict to a Scikit-learn estimator and am having no luck.  It just seems to nest my dict into one of the parameters.  For instance:
params = {
 'copy_X': True,
 'fit_intercept': False,
 'normalize': True
}

lr = LinearRegression(params)

Gives me:
LinearRegression(copy_X=True,
         fit_intercept={'copy_X': True, 'fit_intercept': False,'normalize': True},
     normalize=False)

Additionally, I created a function to iterate over the dict and can create a string like:
'copy_X=True, fit_intercept=True, normalize=False'

This was equally as unsuccessful.  Anyone have any advice here?  The only restriction I have is the data will be coming to me as a dict (well actually a json object being loaded with json.uploads).
Thanks.

A: The best solution to initialise your estimator with the right parameters would be to unpack your dictionary:
lr = LinearRegression(**params)

If for some reason you need to set some parameters afterwards, you could use:
lr.set_params(**params)

This has an advantage over using setattr in that it allows Scikit learn to perform some validation checks on the parameters.

A: I got it.  Used setattr like this.
for k,v in params.items():
   setattr(lr,k,v)

A: fit_intercept is the first argument of the LinearRegression object
http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html
So that explains why your dictionary is being passed to that argument, the other args (also optional) copy_X and normalize are receiving no parameter so they are using the default values.
You could also do:
params = {
 'copy_X': True,
 'fit_intercept': False,
 'normalize': True
}

lr = LinearRegression(copy_X = params['copy_X'], \
                      fit_intercept = params['fit_intercept'], \
                      normalize = params['normalize'])


text:
Q: Not getting expected simplification of trigonometric expressions I have two trigonometric expressions. I would like to eliminate the fraction from my 2nd expression.
A = (-Cos[ψ2] Sin[η2] Sin[θ2] + Cos[η2] Sin[ψ2])

B = (-D + d Cos[η2] Cos[θ2] Cos[ϕ2] + 1/2 l Cos[θ2] Sin[η2] + Q2 Sin[θ2] - d Sin[θ2] Sin[ϕ2] + (Q1 Cos[θ1] Cos[θ2] Sin[η2] (Cos[η2] Cos[θ2] Cos[ϕ2] - Sin[θ2] Sin[ϕ2])) / (Cos[ψ2] Sin[η2] Sin[θ2] - Cos[η2] Sin[ψ2]))

I tried Simplify and FullSimplify to suppress the denominator but the denominator in the expression B (equal to A) is not suppressed.
Simplify[A*B]

Please help me to force Mathematica to make the simplifications so as to eliminate the denominator of the expression B which is equal to A ?

A: First let me explain what is going on.
 A // FullForm

Plus[Times[-1, Cos[ψ2], Sin[η2], Sin[θ2]], Times[Cos[η2], Sin[ψ2]]]

However, what you consider the denominator of the fractional part of b is
(Cos[ψ2] Sin[η2] Sin[θ2] - Cos[η2] Sin[ψ2]) // FullForm

Plus[Times[Cos[ψ2], Sin[η2], Sin[θ2]], Times[-1, Cos[η2], Sin[ψ2]]]

So the two forms don't look the same to Mathematica and don't get cancelled.
There are many ways to solve the problem. One has already been suggested in a comment. Here is another.
AA = -1 A;
Simplify[AA B]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery validation is not working chrome version- 4.0.249.30 jquery validation is not working in chrome (4.0.249.30) for a external site,But it works for our local machine.

A: Sorry,I can`t get any solution.But it worked after re-installation of Chrome (4.0.249.30)
Thank you All


text:
Q: How to copy data inside BIGSQL table to .txt this might be very silly question but I am getting a hard time to figure out a way to copy data inside my BIGSQL table to a .txt in local file system.

A: Depending upon the size of the resulting data file, you can use the export command to get the data into one text file.  The resulting file will end up on one node.
I used the following script as an example:
\connect bigsql
drop table if exists stack.issue2;

create hadoop table if not exists stack.issue2 (
f1 integer,
f2 integer,
f3 varchar(200),
f4 integer
)
stored as parquetfile;

insert into stack.issue2 (f1,f2,f3,f4) values (0,0,'Detroit',0);
insert into stack.issue2 (f1,f2,f3,f4) values (1,1,'Mt. Pleasant',1);
insert into stack.issue2 (f1,f2,f3,f4) values (2,2,'Marysville',2);
insert into stack.issue2 (f1,f2,f3,f4) values (3,3,'St. Clair',3);
insert into stack.issue2 (f1,f2,f3,f4) values (4,4,'Port Huron',4);

select * from stack.issue2;

{ call sysproc.admin_cmd('export to /tmp/t1.unl of del select * from stack.issue2') };

\quit

Running the script:
jsqsh --autoconnect --input-file=./t1.sql --output-file=t1.out

Yields:
cat t1.out
+----+----+--------------+----+
| F1 | F2 | F3           | F4 |
+----+----+--------------+----+
|  0 |  0 | Detroit      |  0 |
|  2 |  2 | Marysville   |  2 |
|  3 |  3 | St. Clair    |  3 |
|  1 |  1 | Mt. Pleasant |  1 |
|  4 |  4 | Port Huron   |  4 |
+----+----+--------------+----+
+---------------+---------------+-------------+
| ROWS_EXPORTED | MSG_RETRIEVAL | MSG_REMOVAL |
+---------------+---------------+-------------+
|             5 | [NULL]        | [NULL]      |
+---------------+---------------+-------------+

and the exported file:
ls -la /tmp/t1.unl
-rw-r--r-- 1 bigsql hadoop 93 Mar  3 16:05 /tmp/t1.unl

cat /tmp/t1.unl
0,0,"Detroit",0
3,3,"St. Clair",3
2,2,"Marysville",2
1,1,"Mt. Pleasant",1
4,4,"Port Huron",4

A: Beauty of bigsql is you can connect just like you do a regular db2 database and call export.
[bigsql@myhost ~]$ db2 "create hadoop table test1 ( i int, i2 int , i3 int)"
DB20000I  The SQL command completed successfully.
[bigsql@myhost ~]$ db2 "insert into test1 values (1,2,3), (4,5,6),(7,8,9),(0,1,2)"
DB20000I  The SQL command completed successfully.
[bigsql@myhost ~]$ db2 "export to output.del of del select * from test1"
SQL3104N  The Export utility is beginning to export data to file "output.del".

SQL3105N  The Export utility has finished exporting "4" rows.

Number of rows exported: 4

[bigsql@myhost ~]$ cat output.del
1,2,3
4,5,6
7,8,9
0,1,2

A: Another way to extract via SQL (as csv in this example) is as follow:
create hadoop table csv_tableName
  row format delimited fields terminated by ','
  location '/tmp/csv_tableName'
as select * from tableName

You can then get the file/s from HDFS.


text:
Q: Dropdown Menu to go to specific row I want to use a dropdown item in cell M7 on sheet "Adjustments per cost center" to jump to specific rows on this sheet to make it more user-friendly and avoid long scrolling through the sheet.
I tried this code:
Sub Jump()

Dim rng As Range
Dim ws As Worksheet

Set ws = Sheets("Adjustments per cost center")

Set rng = ws.Range("G:G").Cells.Find(ws.Range("M7"), lookat:=xlWhole)

If Not rng Is Nothing Then ' the item was found
    rng.Select
Else
    MsgBox "This item is not in the list", vbInformation
End If

End Sub

1) This code is starts by clicking on a button and not by a change of the dropdown (in cell M7)
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim checkTarget As Range
    Set checkTarget = Application.Intersect(Target, Range("my_named_range"))

    If checkTarget Is Nothing Then
        Debug.Print "not active range, exit"
    Else
        MsgBox "success"
    End If
End Sub

2) Major problem: The code works only if in range (G:G) the input is done as hard code and is not a result of a formula.
Many thanks for your support


text:
Q: Function explode() after x characters, not punctuation I'm creating an application where the user is suppose to type a text as correctly as possible. The text is coming from a database and its placed in a string. I'm displaying the string in a div and if the length of the string is to long for the div I want to split it. I know there have been similar questions before, but I haven't found a solution to my problem.
This is what I'm trying to do:
Atm this happens:
--------------------
| The displayed str|ing
--------------------

And I want this:
--------------------
| The displayed st |
--------------------

This is my code so far:
while ($row = mysqli_fetch_array($result)) {
    $textline = explode(".", $row["text"]);
}

$i = 0;

foreach ($textline as $o) {
   $letters = str_split_unicode($letters[$i], 1);
   if (ctype_space($letters[0])) {
         unset($letters[0]);
   }
   foreach ($letters as $l) {
      if (ctype_space($l)) {
         echo "

";
      } else {
        echo "
$l
";
      }
   }
            $i++;
}

To sum up: I want to split the string after 'x' characters, NOT on '.' as it is now
//edit:
The code splits the text splits at punctuation, but I want it to split after "x" characters
Now it splits like this:

This is a sentence.
This is another sentence.
This is a third sentence.

But I want it to split like this:

This is a sent
ence. This is
another senten
ce. This is a
third sentence
.

Here it splits after 14 characters (including space).

A: If I understand you correctly, this will work. Replace this code:
while ($row = mysqli_fetch_array($result)) {
$textline = explode(".", $row["text"]);
}

With this:
while ($row = mysqli_fetch_array($result)) {
$string = $row['text']; $string = wordwrap($string, 80, ";;;;", true);
$oppgavelinjer = explode(";;;;", $string);
}

As long as the text doesnt contain 4 semi-colons in a row you're good Replace '80' with the length you want


text:
Q: How to remove open access after copying File? I want to remove open access after copying File and revoke the access again after performing some task
File srcfile = Paths.get(source, fileName).toFile();
File destFile = Paths.get(destination, fileName).toFile();
Boolean bool = destFile.setExecutable(false);

Bool is always returning false


text:
Q: oracle.jdbc.driver.T4CConnection cannot be cast to oracle.jdbc.OracleConnection in JBOSS EAP 6.1 I have deployed my ear in JBOSS 7.1.1 AS.
For viewing the document in application we are using the BFILE.
Below code is used:
Connection con = this.jdbcTemplate.getDataSource().getConnection();
con = unwrapConnection(con);

if(null != con)
{
    System.out.println("Is conncetion Closed" + con.isClosed());
    PreparedStatement ps = con.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while(rs.next()) {
    {
        OracleResultSet ors = rs.unwrap(OracleResultSet.class);
        bfile = ors.getBFILE(1);
        fileName = rs.getString(2);
        docFormat = rs.getString(3);
    }
    bfileMap.put("EventDocDetails", bfile);
    bfileMap.put("Format", docFormat);
    bfileMap.put("FileName", fileName);
}

private static Connection unwrapConnection(Connection connection) throws SQLException {

    System.out
        .println("Datasource is maintained by Jboss so Unwarping Jboss JDBC Connection to oracle.jdbc.OracleConnection. Driver name is "
            + connection.getMetaData().getDriverName());
    return (oracle.jdbc.OracleConnection) ((WrappedConnection) connection)
        .getUnderlyingConnection();
}

We are using Ojdc6.11.2.0.3 jar.
In the manifest of ear I have dependencies org.jboss.ironjacamar.jdbcadapters.
This works fine for JBOSS AS 7.1.1
But same ear doesnt work in JBOSS EAP 6.1
I get below exception
oracle.jdbc.driver.T4CConnection cannot be cast to oracle.jdbc.OracleConnection
19:54:51,395 ERROR [stderr] (http-/192.168.178.31:8080-5) java.lang.ClassCastException: oracle.jdbc.driver.T4CConnection cannot be cast to oracle.jdbc.OracleConnection.

I am baffled as almost all the things are same.

A: Seems like a classload issue due to two same classes exist in Jboss and in your app(WAR or EAR).
In my Jboss 6.3 I'm found jboss\modules\com\oracle\ojdbc6.jar with T4CConnection.class inside which may be cause of issue. If it exist in your jboss you can try to exclude that lib in jboss-deployment-structure.xml like:
<deployment>
    <exclusions>
        <module name="com.oracle.ojdbc6"/>
    </exclusions>
</deployment>

Hope it helps.

A: After a lot of head scratching i removed the JDBC drive from console of JBOSS and added a new one.It worked.


text:
Q: Allocating large blocks of memory with new I have the need to allocate large blocks of memory with new.
I am stuck with using new because I am writing a mock for the producer side of a two part application. The actual producer code is allocating these large blocks and my code has responsibility to delete them (after processing them).
Is there a way I can ensure my application is capable of allocating such a large amount of memory from the heap? Can I set the heap to a larger size?
My case is 64 blocks of 288000 bytes. Sometimes I am getting 12 to allocate and other times I am getting 27 to allocate. I am getting a std::bad_alloc exception.
This is: C++, GCC on Linux (32bit).

A: With respect to new in C++/GCC/Linux(32bit)...
It's been a while, and it's implementation dependent, but I believe new will, behind the scenes, invoke malloc().  Malloc(), unless you ask for something exceeding the address space of the process, or outside of specified (ulimit/getrusage) limits, won't fail.  Even when your system doesn't have enough RAM+SWAP.  For example:  malloc(1gig) on a system with 256Meg of RAM + 0 SWAP will, I believe, succeed.
However, when you go use that memory, the kernel supplies the pages through a lazy-allocation mechanism.  At that point, when you first read or write to that memory, if the kernel cannot allocate memory pages to your process, it kills your process.
This can be a problem on a shared computer, when your colleague has a slow core leak.  Especially when he starts knocking out system processes.
So the fact that you are seeing std::bad_alloc exceptions is "interesting".
Now new will run the constructor on the allocated memory, touching all those memory pages before it returns.  Depending on implementation, it might be trapping the out-of-memory signal.
Have you tried this with plain o'l malloc?
Have you tried running the "free" program?  Do you have enough memory available?
As others have suggested, have you checked limit/ulimit/getrusage() for hard & soft constraints?
What does your code look like, exactly?  I'm guessing new ClassFoo [ N ].  Or perhaps new char [ N ].
What is sizeof(ClassFoo)?  What is N?
Allocating 64*288000 (17.58Meg) should be trivial for most modern machines...  Are you running on an embedded system or something otherwise special?
Alternatively, are you linking with a custom new allocator?  Does your class have its own new allocator?
Does your data structure (class) allocate other objects as part of its constructor?
Has someone tampered with your libraries?  Do you have multiple compilers installed?  Are you using the wrong include or library paths?
Are you linking against stale object files?  Do you simply need to recompile your all your source files?
Can you create a trivial test program?  Just a couple lines of code that reproduces the bug?  Or is your problem elsewhere, and only showing up here?
--
For what it's worth, I've allocated over 2gig data blocks with new in 32bit linux under g++.  Your problem lies elsewhere.

A: It's possible that you are being limited by the process' ulimit; run ulimit -a and check the virutal memory and data seg size limits. Other than that, can you post your allocation code so we can see what's actually going on?

A: Update:
I have since fixed an array indexing bug and it is allocating properly now.
If I had to guess... I was walking all over my heap and was messing with the malloc's data structures. (??)

A: i would suggest allocating all your memory at program startup and using placement new to position your buffers. why this approach? well, you can manually keep track of fragmentation and such. there is no portable way of determining how much memory is able to be allocated for your process. i'm positive there's a linux specific system call that will get you that info (can't think of what it is). good luck.

A: The fact that you're getting different behavior when you run the program at different times makes me think that the allocation code isn't the real problem.  Instead, somebody else is using the memory and you're the canary finding out it's missing.
If that "somebody else" is in your program, you should be able to find it by using Valgrind.
If that somebody else is another program, you should be able to determine that by going to a different runlevel (although you won't necessarily know the culprit).


text:
Q: Merge multiple files preserving the original sequence in unix I have multiple (more than 100) text files in the directory such as
files_1_100.txt
files_101_200.txt

The contents of the file are name of some variables like files_1_100.txt contains some variables names between 1 to 100
"var.2"
"var.5"
"var.15"

Similarly files_201_300.txt contains some variables between 101 to 200
"var.203"
"var.227"
"var.285"

and files_1001_1100.txt as
"var.1010"
"var.1006"
"var.1025"

I can merge them using the command
cat files_*00.txt > ../all_files.txt

However, the contents of files does not follow that in the parent files. For example all_files.txt shows
"var.1010"
"var.1006"
"var.1025"
"var.1"
"var.5"
"var.15"
"var.203"
"var.227"
"var.285"

So, how can I ensure that contents of files_1_100.txt comes first, followed by files_201_300.txt and then files_1001_1100.txt such that the contents of the all_files.txt is
"var.1"
"var.5"
"var.15"
"var.203"
"var.227"
"var.285"
"var.1010"
"var.1006"
"var.1025"

A: Let me try it out,  but I think that this will work:
ls file*.txt | sort -n -t _ -k2 -k3 | xargs cat

The idea is to take your list of files and sort them and then pass them to the cat command.
The sort uses several options:

*

*-n - use a numeric sort rather than alphabetic

*-t _ - divide the input (the filename) into fields using the underscore character

*-k2 -k3 - sort first by the 2nd field and then by the 3rd field (the 2 numbers)

You have said that your files are named file_1_100.txt, file_101_201.txt, etc. If that means (as it seems to indicate) that the first numeric "chunk" is always unique then you can leave off the -k3 flag. That flag is needed only if you will end up, for instance, with file_100_2.txt and file_100_10.txt where you have to look at the 2nd numeric "chunk" to determine the preferred order.
Depending on the number of files you are working with you may find that specifying the glob (file*.txt) may overwhelm the shell and cause errors about the line being too long. If that's the case you could do it like this:
ls | grep '^file.*\.txt$' | sort -n -t _ -k2 -k3 | xargs cat

A: You can use printf sort and pipe that to xargs cat:
printf "%s\0" f*txt | sort -z -t_ -nk2 | xargs -0 cat > ../all_files.txt

Note that whole pipeline is working on NULL terminated filenames thus making sure this command even works foe filenames with space/newlines etc.

A: If your filenames are free from any special characters or white-spaces, then other answers should be easy solutions.
Else, try this rename based approach:
$ ls files_*.txt
files_101_200.txt  files_1_100.txt

$ rename  's/files_([0-9]*)_([0-9]*)/files_000$1_000$2/;s/files_0*([0-9]{3})_0*([0-9]{3})/files_$1_$2/' files_*.txt

$ ls files_*.txt
files_100_100.txt  files_101_200.txt

$ cat files_*.txt > outputfile.txt

$ rename 's/files_0*([0-9]*)_0*([0-9]*)/files_$1_$2/' files_*.txt

A: The default sorting behavior of cat file_* is alphabetical, rather than numeric.
List them in numerical order and then cat each one, appending the output to some file.
ls -1| sort -n |xargs -i cat {} >> file.out

A: You could try using a for-loop and adding the files one by one (the -v sorts the files correctly when the numbers are not zero-padded)
for i in $(ls -v files_*.txt)
do
    cat $i >> ../all_files.txt
done

or more convenient in a single line:
for i in $(ls -v files_*.txt) ; do cat $i >> ../all_files.txt ; done

A: You could also do this with Awk by splitting and sorting ARGV:
awk 'BEGIN {
    for(i=1; i<=ARGC-1; i++) {
        if(i > 1) {
            j=i-1
            split(ARGV[i], curr, "_")
            split(ARGV[j], last, "_")
            if (curr[2] < last[2]) {
                tmp=ARGV[i]
                ARGV[i]=ARGV[j]
                ARGV[j]=tmp
            }
        }
    }
}1' files_*00.txt


text:
Q: how to get current loop value in label using c# windows forms In my datagridview I have four PDF files. While these four PDF's are getting downloaded it should show that it is downloading the first file out of four file, if it is the second file it should show  that it is downloading the second file out of four files, and os on. It should be done like that until all the files are downloaded into a folder.
for (int i = 1; i <= dataGridView1.Row Count;i++ )
{
     label2.Text = i;
}

A: Run a new Thread to check on the progress of downloading. In this new Thread set the Label status.
  private void button1_Click(object sender, EventArgs e)
    {
        new Thread(() =>
        {
            CheckForIllegalCrossThreadCalls = false;
            while(CheckProgress() <= 4)
            {
               label1.Text = "Downloading " + CheckProgress() + " out of 4 files";

            }

            label1.Text = "Downloading Completed!";

        }).Start();
    }


text:
Q: Unable to locate element: {"method":"css selector","selector":"#id_gender1"} I'm trying to select a checkbox / radio button by all the possible ways that I can think of, but none of them have worked.
This is the way I am trying to identity de checkbox
WebElement selectGender = driver.findElement(By.id("id_gender1"));
selectGender.click();

Here is the HTML code

<input type="radio" name="id_gender" id="id_gender1" value="1">

       Mr.

This is the error message I am receiving.
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#id_gender1"}
  (Session info: chrome=75.0.3770.142)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'JEFFERSONPC', ip: '192.168.100.6', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_211'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 75.0.3770.142, chrome: {chromedriverVersion: 75.0.3770.140 (2d9f97485c7b..., userDataDir: C:\Users\JEFFER~1\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:63666}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 65163859269265511fa3118a5c9b1f79
*** Element info: {Using=id, value=id_gender1}

A: Induce WebDriverWait and elementToBeClickable to click on the element.
Try the following options.
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement selectGender = wait.until(ExpectedConditions.elementToBeClickable(By.id("id_gender1")));
selectGender.click()

OR
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement selectGender = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='radio-inline']/label[@for='id_gender1']")));
selectGender.click()

A: Here is your code
  findElement(By.xpath("//input[@name='id_gender']")).click();

A: --Disclaimer: cant comment yet due to lack of reputation--
the code where you fetch the id seems fine, and no spelling errors in the code either. But it could be that your answer is found here:
Unable to locate an Element By ID in Selenium
Also: please post what you have tried so far in a bit more detail. You say in all ways you know, but we dont know what that is :).
For example, reference the stackoverflow answers you have tried that are similar to yours

A: Your code works fine.
Why your error message have css Selector? when you are not using cssSelector.
if using cssSelector then:
WebElement selectGender = driver.findElement(By.cssSelector("#id_gender1"));
selectGender.click();

A: I am sure you are trying to click element which is inside the frame. First of all you have to switch driver on that frame and perform your test script.
driver123.switchTo().frame(<some frame index or id>;//Switching frame
WebElement selectGender = driver.findElement(By.id("id_gender1"));//Storing element
selectGender.click();//Clicking on element

Note: If you do not have frame id or index use xpath for switch to that frame.


text:
Q: How do I stop partial-refresh from removing paragraph breaks in the Wordpress Customizer live preview? I have added my own settings to the Wordpress customizer and set it up so that it live previews using the "postMessage" method. It is working almost perfectly apart from when I edit a field linked to paragraph text, the preview doesn't show line breaks in the paragraphs. However this is temporary, once the customizer is closed or the page is refreshed the paragraph gaps come back.
I am defining the Customizer sections in the customizer.php using the following code:
// About Section Text
$wp_customize->add_setting( 'about__text' , array(
    'default'   => 'Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis, odit unde magnam dolores quasi voluptas, impedit a nam inventore atque eaque nobis possimus officiis deleniti quisquam animi deserunt ad ipsa sapiente illo?',
    'transport' => 'postMessage',
) );

// About Section Text (CONTROL)
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'about__text', array(
    'label'      => __( 'About Section Content:', 'mytheme' ),
    'section'    => 'edit__homepage--section',
    'settings'   => 'about__text',
    'priority'   => 3,
    'type'       => 'textarea'
) ) );

I am displaying the above theme mod in my index.php file using the following code:
    <div class="about__text">
      <?php echo wpautop(get_theme_mod('about__text')); ?>
    </div>

Here's my jquery:
( function( $ ) {
    wp.customize( 'about__text', function( value ) {
        value.bind( function( newVal ) {
            $( '.about__text' ).html( newVal );
        } );
    } );
} )( jQuery );

I've tried experimenting with different jquery objects such as text() and contents() but these either have the same issue or don't work at all.
Doe anyone know if there's a way I can get the javascript preview to honour the paragraph styles? Maybe like a javascript version of wpautop()  ?

A: You can use selective refresh like this. Values are rendered server side so no need to extra JS. And since only selected wrapper element is refresh, it is more efficient than full page reload in Customizer. In the following example content only in .about__text is refreshed. Since rendering is done server side, no need to look for JS alternative of wpautop function. I believe this would be one alternative for your problem mentioned in the question.
function wpso_customize_register( $wp_customize ) {
    $wp_customize->selective_refresh->add_partial(
        'about__text',
        array(
            'selector'        => '.about__text',
            'render_callback' => function(){
                echo wp_kses_post( wpautop( get_theme_mod('about__text') ) );
            },
        )
    );
}
add_action( 'customize_register', 'wpso_customize_register' );


text:
Q: How do I use drag and drop with dynamically created HTML? (SortableJS) I'm starting to learn javascript and I have a simple todo application where I want to be able to drag and drop the different todo's created. A simple way to do this was with SortableJS library, but it doesn't work the way i want to. After implementing the simple sortable function, when dragging on a todo, it grabs the whole todo-list instead of a single todo

I think the issue is because I dynamically create the html, but I'm kinda stuck and would appreciate any suggestions.

//Selectors
const todoInput = document.querySelector(".todos-input"); //input for adding a todo
const todoButton = document.querySelector(".todos-button"); //add todo-button
const todoList = document.querySelector(".todos-list"); //the todo-list

//Event listeners
todoButton.addEventListener("click", addTodo);
todoList.addEventListener("click", deleteTodo);
todoList.addEventListener("click", completeTodo);

//Functions
function addTodo(event) {
  //prevent form from submitting
  event.preventDefault();
  //create a div for the todos-list
  const todoDiv = document.createElement("div");
  //add classlist for styling
  todoDiv.classList.add("todo");
  //Create LI
  const newTodo = document.createElement("li");
  //output the value from the add-todo field
  if (todoInput.value != "") {
    newTodo.innerText = todoInput.value;
  } else {
    return false;
  }

  //classlist for styling
  newTodo.classList.add("todo-item");
  //append child to div

  todoDiv.appendChild(newTodo);
  //complete button
  const completedButton = document.createElement("button");
  completedButton.innerHTML = '';
  completedButton.classList.add("completed-btn");
  todoDiv.appendChild(completedButton);
  //delete button
  const deletedButton = document.createElement("button");
  deletedButton.innerHTML = '';
  deletedButton.classList.add("deleted-btn");
  todoDiv.appendChild(deletedButton);

  //drag button
  const dragButton = document.createElement("button");
  dragButton.innerHTML = '';
  dragButton.classList.add("drag-btn");
  dragButton.classList.add("handle");
  todoDiv.appendChild(dragButton);

  //append div to list of todos
  todoList.appendChild(todoDiv);

  //clear input field after adding a new todo
  todoInput.value = "";

  //DRAG AND DROP
  const dragArea = document.querySelector('.todos-section');
  new Sortable(dragArea, {
    animation: 300
  });

}

//deleting todo
function deleteTodo(e) {
  //grab the item, whatever we are clicking on
  const item = e.target;
  //delete todo
  if (item.classList[0] === "deleted-btn") {
    //grab the parent element of the item, which is the todolist element in this case
    const todo = item.parentElement;
    //remove the todo
    todo.remove();
  }
}

//completing todo
function completeTodo(e) {
  //grab the item, whatever we are clicking on
  const item = e.target;
  //complete todo
  if (item.classList[0] === "completed-btn") {
    const todo = item.parentElement;
    //use the toggle because if the element has a class, then the classList.toggle method
    //behaves like classList.remove and the class is removed from the element.
    //And if the element does not have the specified class
    //then classList.toggle, just like classList.add, adds this class to the element.
    //So it basically does the add/remove operation for us depending on the state.
    todo.classList.toggle("completed-todo");
  }
}
/*Apply to all elements*/

* {
  box-sizing: border-box;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

body {
  font-family: "Merriweather Sans", sans-serif;
  background: rgba(216, 206, 206, 0.787);
}

.wrapper {
  display: flex;
  position: relative;
}

/* Add todos-section */

.todos-bar {
  position: fixed;
  top: 5%;
  left: 50%;
  font-size: 17px;
  border: 0;
  transform: translate(-50%, -50%);
  padding-left: 100px;
}

.todos-bar input {
  width: 600px;
  height: 50px;
  border: 0px;
  outline: none;
  font-size: 20px;
  padding-left: 20px;
  border-radius: 5px;
}

.todos-bar button {
  position: fixed;
  background: rgba(20, 33, 93, 0.952);
  color: white;
  font-size: 20px;
  border: 0;
  outline: none;
  height: 50px;
  padding: 10px 20px;
  right: 0px;
  border-radius: 0px 5px 5px 0px;
  cursor: pointer;
}

.todos-bar button:hover {
  background: rgb(43, 54, 73);
}

/* Todos section */

.todos-section {
  display: flex;
  position: fixed;
  top: 15%;
  left: 37%;
}

.todos-list {
  width: 600px;
}

.todo {
  margin: 1.5rem;
  background: white;
  color: black;
  font-size: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 5px;
  padding-left: 0.5rem;
  margin: 15px;
  transition: all 0.5s ease;
}

.todo li {
  flex: 1;
}

.todo-item {
  padding: 0rem 0.5rem;
  padding-left: 2.5rem;
}

.deleted-btn,
.completed-btn {
  background: rgb(248, 56, 56);
  color: white;
  border: none;
  padding: 1rem;
  cursor: pointer;
  font-size: 1rem;
}

.completed-btn {
  background: green;
}

.deleted-btn {
  border-radius: 0px 5px 5px 0px;
}

.drag-btn {
  display: block;
  position: absolute;
  background: white;
  border: 2px solid white;
}

.fa-bars {
  padding: 5px;
  margin: 2px;
  cursor: pointer;
}

.fa-trash,
.fa-check {
  pointer-events: none;
}

.completed-todo {
  text-decoration: line-through;
  opacity: 0.5;
}

  <link rel="stylesheet" href="style.css">

      <input type="text" class="todos-input" placeholder="Add to list...">
      <button class="todos-button" type="submit"></button>

A: According to the documentation,

You can use any element for the list and its elements, not just ul/li

What  you've implemented actually fits in this description since there is a ul with div tags inside. However, you are not referencing the right element in the dragArea, because it should be the direct parent (.todos-list) of your desired draggable children.
So, change it to .todos-list and in addition pass handle property to Sortable constructor to reference the icon in which you want to drag.
const dragArea = document.querySelector('.todos-list');
new Sortable(dragArea, {
    animation: 300,
    handle: '.fa-bars'
})

Working example


text:
Q: i'm not able to get FirebaseUser Method...! alredy add packege Firebse Auth   final AuthResult authResult = await _auth.signInWithCredential(credential);
  final FirebaseUser user = authResult.user;

  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);


text:
Q: How do I create an FTP share on Mac OS X Yosemite and access it from Windows 7 via FTP? I am running JRiver Media Client/Server on a Windows 7 Ultimate box accessing media files shared on a MacPro running Yosemite (can also run Mavericks).  JRiver needs to be able to read and write to the shared folders on the Mac.    I want to use FTP for this as an alternative to SMB which does not work under Yosemite.  How do I configure this?

A: You can activate the old ftp server via the terminal:
sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist

And also disable it:
sudo -s launchctl unload -w /System/Library/LaunchDaemons/ftp.plist

There is also a software for this: http://www.troncept.com/lion-ftpd-enable/
Then, as far as I know, you have to share this directory in the system settings.
EDIT: You have to type in your user account and password from your mac in the Windows 7 network drive form.

A: Try turning off SSH (remote login) in server.app->settings as it changes/enables/forces sftp connections only. That's likely what's failing for you. if you turn off remote login using SSH then it goes back to unecrypted ftp logins again.


text:
Q: Call function from php page I'm trying to display html from a php page on my home page.
I have a function to call some html in a php page called home-content.php
<?php function HomeFeed ($replStr) {
return <<<HTML

Store Location

Address Line 1

        Address Line 2

Hours

10 AM to 6:30 PM Monday through Friday

9 AM to 2 PM Saturday
<br

Call Now

(903) 769-8043

HTML;
}
?>

Now I have my homepage template that I want to call that function to display the html. Now, I'm sure this is all entirely wrong but I'm new to trying to use php, so I've moved thing around a lot and everything. I had it almost working at one point, the html was displaying but it also showed the HomeFeed return <<

<?php
require_once('home-content.php');
?>

HomeFeed()

A: You need to wrap the function call within the php escape tags. Also you might want to consider revising the function as follows.
<?php
    require_once('home-content.php');
    HomeFeed();
?>

<?php function HomeFeed () { ?>

Store Location

Address Line 1

        Address Line 2

Hours

10 AM to 6:30 PM Monday through Friday

9 AM to 2 PM Saturday
<br

Call Now

(903) 769-8043

<?php } ?>

A: try this Assign string to variable and echo it:
Wrap your function call inside php tags..
   <?php function HomeFeed () {

$returnstring = <<<HTML

Store Location

Address Line 1

        Address Line 2

Hours

10 AM to 6:30 PM Monday through Friday

9 AM to 2 PM Saturday
<br

Call Now

(903) 769-8043

HTML;
echo $returnstring;
}
?>
    <?php
     require_once('home-content.php');
      HomeFeed();
    ?>


text:
Q: multiple python versions after pip3 install I've spent a lot of time on the internet but did not found the information I need.
I've installed sudo apt-get install python3-pip from shell (I needed it for Pycharm venv - not important) but it seems that my python versions got messed up, there are new folders in lib, plus the disk size required was around 200mb which was odd.
I've since then uninstalled with sudo apt-get remove python3-pip + sudo apt-get autoremove. However, the folders in usr/lib still exist and if I try to install again it says ~80mb dependencies, meaning that some of the packages installed earlier still exist on my system.
The question - should I have installed pip3 for specific python version and why the change in python installations? Was there a better way to install pip3 on my system?
P.S. яну == Jan in date logs below.
/usr/bin$ ll -d python*
lrwxrwxrwx 1 root root       9 окт 25 14:11 python3 -> python3.6*
-rwxr-xr-x 2 root root 4522328 окт 22 14:32 python3.6*
-rwxr-xr-x 2 root root 4522328 окт 22 14:32 python3.6m*
lrwxrwxrwx 1 root root      10 окт 25 14:11 python3m -> python3.6m*

/usr/lib$ ll -d python*
drwxr-xr-x 27 root root 24576 ное 18 06:41 python2.7/
drwxr-xr-x  3 root root  4096 юли 25  2018 python3/
drwxr-xr-x 30 root root 20480 яну 26 16:05 python3.6/
drwxr-xr-x  5 root root  4096 яну 26 16:05 python3.7/

/usr/local/bin$ ll -d python*
ls: cannot access 'python*': No such file or directory


text:
Q: Elasticsearch & NetFlix Edda - NoNodeAvailableException: No node available I am trying to get Netflix open source solution Edda to work with Elasticsearch.  I know I've installed Edda correctly because I can get it working with MongoDB as a backend successfully.  I'd prefer to use Elasticsearch so I can get the benefits of Kibana rather than write my own frontend.  So I'm running Edda and Elasticsearch on the same server in AWS at the moment (just trying to get it working).  Elasticsearch is operational:
{
  "name" : "Arsenic",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.1.0",
    "build_hash" : "72cd1f1a3eee09505e036106146dc1949dc5dc87",
    "build_timestamp" : "2015-11-18T22:40:03Z",
    "build_snapshot" : false,
    "lucene_version" : "5.3.1"
  },
  "tagline" : "You Know, for Search"
}

And to show it's listening:
netstat -tulpn | grep java
tcp        0      0 ::ffff:<myip>:9300    :::*                        LISTEN      2270/java
tcp        0      0 ::ffff:<myip>:9200    :::*                        LISTEN      2270/java

My java version I updated from 1.7 to 1.8 as I believe the java version for Elasticsearch and what is running on the server have to match.  I can't see a reason why 1.8 would be causing an issue:
java -version
openjdk version "1.8.0_65"
OpenJDK Runtime Environment (build 1.8.0_65-b17)
OpenJDK 64-Bit Server VM (build 25.65-b01, mixed mode)

Here's my edda properties file:
cat /home/ec2-user/edda/src/main/resources/edda.properties | grep elasticsearch
edda.datastore.current.class=com.netflix.edda.elasticsearch.ElasticSearchDatastore
edda.elector.class=com.netflix.edda.elasticsearch.ElasticSearchElector
edda.elasticsearch.cluster=elasticsearch
edda.elasticsearch.address=<myip>:9300
edda.elasticsearch.shards=5
edda.elasticsearch.replicas=0
# http://www.elasticsearch.org/guide/reference/api/index_/
edda.elasticsearch.writeConsistency=quorum
edda.elasticsearch.replicationType=async
edda.elasticsearch.scanBatchSize=1000
edda.elasticsearch.scanCursorDuration=60000
edda.elasticsearch.bulkBatchSize=0

And in my elasticsearch.yml file:
network.host: <myip>

I haven't specified a clustername so it assumes the default 'elasticseach'.
So when I run Edda to poll AWS and populate elasticsearch with the data it finds I receive this error:
[Collection aws.hostedZones] init: caught org.elasticsearch.client.transport.NoNodeAvailableException: No node available
        at com.netflix.edda.Collection$$anonfun$init$1.apply$mcV$sp(Collection.scala:471)
        at com.netflix.edda.Utils$$anon$1.act(Utils.scala:169)
        at scala.actors.Reactor$$anonfun$dostart$1.apply(Reactor.scala:224)
        at scala.actors.Reactor$$anonfun$dostart$1.apply(Reactor.scala:224)
        at scala.actors.ReactorTask.run(ReactorTask.scala:33)
        at scala.actors.ReactorTask.compute(ReactorTask.scala:63)
        at scala.concurrent.forkjoin.RecursiveAction.exec(RecursiveAction.java:160)
        at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
        at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
        at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
        at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

Clearly it can't connect to the elasticsearch cluster yet the cluster name is correct, it's listening on the correct port and ip address as far as I can tell and I don't think there's an issue with the java version.
I'm missing something probably very simple.
Thanks in advance for all your assistance.
Regards
Neilos

A: I've figured it out, the java client used in Edda is set to use version 0.90.0 of elasticsearch which is set in build.gradle, if you install that version of Elasticsearch it works.  Obviously that's a very old version of Elasticsearch which you are not likely to want to use.  If you change the version number in this file it fails when it tries to compile due to broken paths (missing assemblies).  I'm weighing up whether it's worth trying to resolve these assembly issues to get it working with the latest version of Elasticsearch or choose to use MongoDB which works without any code changes but will only provide REST Api functionality.  At least the problem is resolved.


text:
Q: ejabberd connection failed with webclient(websocket.js) I have installed ejabberd with Ubunut OS.

*

*Configured ejabberd.yml as:
port: 5280
    ip: "::"
    module: ejabberd_http
    request_handlers:
      "/ws": ejabberd_http_ws
      "/bosh": mod_bosh
      "/a/b/": mod_foo
      "/api": mod_http_api
    web_admin: true
    http_bind: true
    register: true
    captcha: true

*Webclient: https://github.com/processone/xmpp-websocket-client
Note: able to connect and chat using jabber client and spark also.
Try to connect with webclient as get response as below:
     client Request: <?xml version="1.0"?><stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0"
 xmlns="jabber:client" to="localhost" xml:lang="en"
 xmlns:xml="http://www.w3.org/XML/1998/namespace" >

     Server Response: <stream:stream id='14754768778694635521' version='1.0' xml:lang='en'
 xmlns:stream='http://etherx.jabber.org/streams' from='localhost'
 xmlns='jabber:client'>

     <stream:features><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>DIGEST-MD5</mechanism><mechanism>SCRAM-SHA-1</mechanism><mechanism>PLAIN</mechanism><mechanism>X-OAUTH2</mechanism></mechanisms></stream:features>

     Client request: <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>

     Server Response: <challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>bm9uY2U9IjE2NDY5ODExMTQ0NDkyMDQyMjQxIixxb3A9ImF1dGgiLGNoYXJzZXQ9dXRmLTgsYWxnb3JpdGhtPW1kNS1zZXNz</challenge>

     Client Request: <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>dXNlcm5hbWU9Im1hbm9qIixyZWFsbT0iIixub25jZT0iMTY0Njk4MTExNDQ0OTIwNDIyNDEiLGNub25jZT0iZDQxZDhjZDk4ZjAwYjIwNGU5ODAwOTk4ZWNmODQyN2UiLG5jPSIwMDAwMDAwMSIscW9wPSJhdXRoIixkaWdlc3QtdXJpPSJ4bXBwL2xvY2FsaG9zdCIscmVzcG9uc2U9ImJhMjhjNTQwYzU5ZTczZGE1NGY1MmU2YjYxYTFhMjlmIixjaGFyc2V0PSJ1dGYtOCI=</response>

     Server Response: <challenge xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>cnNwYXV0aD0xMzc3MzJjMzc3M2FhMjIxNzg0Y2RmYTIxY2RkNzZjMQ==</challenge>

     CR: <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>

     SR <success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>

     CR: <?xml version="1.0"?><stream:stream xmlns:stream="http://etherx.jabber.org/streams" version="1.0"
 xmlns="jabber:client" to="localhost" xml:lang="en"
 xmlns:xml="http://www.w3.org/XML/1998/namespace" >

     SR: <stream:stream id='2280662148453655041' version='1.0' xml:lang='en' xmlns:stream='http://etherx.jabber.org/streams'
 xmlns='jabber:client'>

     <stream:error><not-well-formed xmlns='urn:ietf:params:xml:ns:xmpp-streams'/><text xml:lang='en'
 xmlns='urn:ietf:params:xml:ns:xmpp-streams'>XML or text declaration
 not at start of entity</text></stream:error>

     </stream:stream>

what's missing in server configuration or websocket.js configuration?

A: This was just problem with web-socket client, it was using old web-socket protocol version, that was available before xmpp over web-socket was standarized, I got new updated web-socket client where that client to use new protocol, Now it's working. Thanks to ejabberd team for update.


text:
Q: Update SQLITE DB with multiple python lists I'm attempting to update my sqlite db with 2 python lists. I have a sqlite db with three fields. Name, number, date. I also have three python lists with similar names. I'm trying to figure out a way to update my sqlite db with data from these 2 lists. I can get the db created, and even get a single column filled, but I cant seem to update it correctly or at all. Is there a way to INSERT both lists at once? Rather than INSERT a single column and then UPDATE the db with the other?
Here is what I have so far:
name_list = []

number_list = []

date = now.date()
strDate = date.strftime("%B %Y")

tableName = strDate

sqlTable = 'CREATE TABLE IF NOT EXISTS ' + tableName + '(name text, number integer, date text)'

c.execute(sqlTable)

conn.commit()

for i in name_list:
    c.execute('INSERT INTO January2018(names) VALUES (?)', [i])
    conn.commit()

I can't seem to get past this point. I still need to add another list of data (number_list) and attach the date to each row.
Here's what I have on that:
for i in number_list:
    c.execute('UPDATE myTable SET number = ? WHERE name', [i])
    conn.commit()

Any help would be much appreciated. And if you need more information, please let me know.

A: You can use executemany with zip:
c.executemany('INSERT INTO January2018 (name, number) VALUES (?, ?)', zip(name_list, number_list))
conn.commit()


text:
Q: Windows phone 8 app Code to find location using shake accelerometer I am trying to create code to find the location on map using the shake accelerometer on Windows phone 8 emulator.
I use reverse geocoding for displaying the location using a button, but i have no idea how to display the location using the shake sensor, can anyone help or give me links to somewhere I can learn to create code for this feature.
 private void ReverseGeocodeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
    {
        if (e.Error == null)
        {
            if (e.Result.Count > 0)
            {
                MapAddress address = e.Result[0].Information.Address;
                CurrentLocTextBlock.Text = "Current Location: ";;
                AddressTextBlock.Text = address.City + ", " + address.State;
            }
        }
    }


text:
Q: OSError: libcurand.so.10: cannot open shared object file: No such file or directory I am working on Nvidia Jetson Tx2 (with JETPACK 4.2) and installed the pytorch following this link.
When I am importing torch in python its giving me an error OSError: libcurand.so.10: cannot open shared object file: No such file or directory I have tried all the options but nothing worked.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-10.0/lib64
export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/cuda-10.0/lib64
export PATH=$PATH:/usr/local/cuda-10.0/lib64

Any guidance to debug the issue is requested. Thanks

A: emm
I found this answer as followed...
https://forums.developer.nvidia.com/t/mounting-cuda-onto-l4t-docker-image-issues-libcurand-so-10-cannot-open-no-such-file-or-directory/121545
The key is : "You can use JetPack4.4 for CUDA 10.2 and JetPack4.3 for CUDA 10.0."
Maybe downloading Pytorch v1.4.0 and Jetpack 4.2/4.3 would solve this question...
Anyway, it is helped for me... good luck
enter image description here


text:
Q: Copy unique values from two columns into a third column I have a master list of orders in a spreadsheet.
Column A lists all orders.   Column B lists a subset of all orders.  If both lists were small, I could manually do this but I have hundreds of records to look through.
What is the best way to find values from Column A that do not exist in Column B, and place them in Column C?
Visually, I am looking to create a Column C like this:
Column A       Column B       Column C
A1             A3             A1
A2             A5             A2
A3                            A4
A4
A5

Note that I am not seeking to merely highlight unique values in Column A, but I am looking to copy those unique values into a new column (C).

A: Try:
=IFERROR(INDEX($A$1:$A$100,AGGREGATE(15,6,1/(1/(ISNA(MATCH($A$1:$A$100,$B$1:$B$100,0))*ROW($A$1:$A$100)*($A$1:$A$100<>""))),ROWS($1:1))),"")

A: This is very easy with a "helper" column. In D1 enter:
=IF(ISERROR(MATCH(A1,$B$1:$B$5,0)),1,"")

and in D2 enter:
=IF(ISERROR(MATCH(A2,$B$1:$B$5,0)),1+MAX($D$1:D1),"")

and copy down.  Column D marks each row that contains useful data with a unique ID.  Column D tells use first get data from row#1, then get data from row#2, then get data from row#4
Then in C1 enter:
=IFERROR(INDEX($A$1:$A$5,MATCH(ROWS($1:1),D:D,0)),"")

and copy down:

A: I would like to suggest you a simple VLOOKUP Formula, will compare both Columns A & B and extract unique vales in Column C.

=IF(ISNA(VLOOKUP(A2,$B$2:$B$6,1,FALSE)),A2,"")

Hope this help you.


text:
Q: Dropbox photos and "date taken" I have a question. I'm using Dropbox sdk for java to do small project (extract from pom.xml).
<groupId>com.dropbox.core</groupId>
<artifactId>dropbox-core-sdk</artifactId>
<version>[1.7,1.8)</version>

What I try to do, is to get a "date taken" metadata from file uploaded to dropbox. I have seen that this info is avaiable from dropbox (it is mentioned for example here). But I was unable to find this info in api for java. I would be grateful if anyone will help/advice something me with this issue.
My current code responisble for listing files from dropbox looks like this:
        DbxEntry.WithChildren listing = client.getMetadataWithChildren(path);
        for (DbxEntry child : listing.children) {
            //Some logic inhere
        }

A: After some digging I found an answer: my problem was SDK version. In version that I used (1.7) there was no such thing (you can check it here).
However, when you update your version to 1.8 then you can find it: DbxEntry.File.PhotoInfo


text:
Q: How to customize two google maps with javascript on one page? I need two Google maps on one page. Both of maps should have multiple pins on it. One map show hotels, another one restaurants. I tried to add pins and location names with javascript but all pins shows one location name.
This is html code for maps:
Hotels map:

Restaurants map:

This is script code for maps:
Hotels map:
    var locations = [
      ['Sheraton', 41.646230, 41.649160, 1],
      ['Hilton', 41.627184, 41.5991094, 2],
      ['Radisson', 41.6296321, 41.6002718, 3]
    ];

    var map = new google.maps.Map(document.getElementById('map-accommodation'), {
      zoom: 12,
      center: new google.maps.LatLng(41.616756, 41.636745),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

Restaurants map:
    var locations = [
      ['360 Cloud bar', 41.6472564, 41.6251435, 1],
      ['Sky bar', 41.6479619, 41.6275468, 2],
      ['Sky tower', 41.6479619, 41.6275468, 3]
    ];

    var map = new google.maps.Map(document.getElementById('map-food'), {
      zoom: 12,
      center: new google.maps.LatLng(41.616756, 41.636745),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

So these maps show different locations, hotels map shows me only hotels, restaurants map shows me only restaurant pins, but all of them have one name - "sky tower".

Can you explain why and how can I fix it?

A: Use a unique array for each map (i.e. hotels, restaurants) and if you want each map to have its own InfoWindow (both maps currently share one InfoWindow), make a unique one of those as well.
var hotels = [
    ['Sheraton', 41.646230, 41.649160, 1],
    ['Hilton', 41.627184, 41.5991094, 2],
    ['Radisson', 41.6296321, 41.6002718, 3]
  ];

  var map = new google.maps.Map(document.getElementById('map-accommodation'), {
    zoom: 12,
    center: new google.maps.LatLng(41.616756, 41.636745),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infowindow = new google.maps.InfoWindow();

  var marker, i;

  for (i = 0; i < hotels.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(hotels[i][1], hotels[i][2]),
      map: map
    });
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(hotels[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }

  var restaurants = [
    ['360 Cloud bar', 41.6472564, 41.6251435, 1],
    ['Sky bar', 41.6479619, 41.6275468, 2],
    ['Sky tower', 41.6479619, 41.6275468, 3]
  ];

  var map = new google.maps.Map(document.getElementById('map-food'), {
    zoom: 12,
    center: new google.maps.LatLng(41.616756, 41.636745),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infowindow = new google.maps.InfoWindow();

  var marker, i;
  for (i = 0; i < restaurants.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(restaurants[i][1], restaurants[i][2]),
      map: map
    });
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(restaurants[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }

proof of concept fiddle

code snippet:

"use strict";

// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
  var hotels = [
    ['Sheraton', 41.646230, 41.649160, 1],
    ['Hilton', 41.627184, 41.5991094, 2],
    ['Radisson', 41.6296321, 41.6002718, 3]
  ];

  var map = new google.maps.Map(document.getElementById('map-accommodation'), {
    zoom: 12,
    center: new google.maps.LatLng(41.616756, 41.636745),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infowindow = new google.maps.InfoWindow();

  var marker, i;

  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < hotels.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(hotels[i][1], hotels[i][2]),
      map: map
    });
    bounds.extend(marker.getPosition());
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(hotels[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }
  map.fitBounds(bounds);
  var restaurants = [
    ['360 Cloud bar', 41.6472564, 41.6251435, 1],
    ['Sky bar', 41.6479619, 41.6275468, 2],
    ['Sky tower', 41.6479619, 41.6275468, 3]
  ];

  var map = new google.maps.Map(document.getElementById('map-food'), {
    zoom: 12,
    center: new google.maps.LatLng(41.616756, 41.636745),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infowindow = new google.maps.InfoWindow();

  var marker, i;
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < restaurants.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(restaurants[i][1], restaurants[i][2]),
      map: map
    });
    bounds.extend(marker.getPosition());
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(restaurants[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
  }
  map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>

  <title>Complex Marker Icons</title>


text:
Q: Detecting when user changes custom color settings in colordialog How do I detect when the user has changed the colors in the custom colors in colordialog?

A: Try recording the CustomColors() property of the ColorDialog before you display the dialog box in an Integer arrays
Then, after you've shown the dialog, compare the CustomColors property with the integer array.


text:
Q: How to cancel a file upload using an iframe I have seen this code from an answer for a previous stackoverflow question:
if (iframeObj.contentWindow.document.execCommand)
    { // IE browsers
        iframeObj.contentWindow.document.execCommand('Stop');
    }
else
    { // other browsers
        iframeObj.contentWindow.stop();
    }

The question can be viewed here But basically the question he asked was that is it possible for a hidden iframe to stop a file from uploading.
Now what I have is a "Cancel" button where when I upload a file, if I want to cancel the upload, then if I click on the "Cancel" button, I want the uploading of the file to stop.
But my question is that with the iframe I have and the "Cancel" button function I have, how is it implemented so that the code above can be used to cancel a file upload in my code?
Below is the form code which consists of the form and the iframe:
  var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return stopImageUpload(this);' class='imageuploadform' >" +
    "Image File: <input name='fileImage' type='file' class='fileImage' />

" +
    "<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />" +
    "

" +
    "<input type='button' name='imageCancel' class='imageCancel' value='Cancel' />" +
    "</form>");

Below is the startImageUpload function where it starts uploading an image, the cancel button click handler function is displayed in this function:
function startImageUpload(imageuploadform){

              $(".imageCancel").click(function() {
              $('.upload_target').get(0).contentwindow
          return stopImageUpload();

    });

      return true;
}

A: I am not sure, if I understand your question. However, if you are asking, why your code does not work, here are the issues:
1.) Your function name is startImageUpload, but in onsubmit handler you call stopImageUpload
2.) The line $('.upload_target').get(0).contentwindow is missing semicolon. The bigger issue is, that it does nothing.
3.) I do not know, how exactly your stopImageUpload function works, because you haven't post it here.
Hope this helps.


text:
Q: Why press the stop debugging button during a debugging session crashes the host? I've successfully managed to implement ZBS to debug the scripting code of a  C++ real time game.  It works really great!
However, there is still an issue that I don't know how to solve:  if I press the stop debugging button or menu option during a debugging session, my C++ host program crashes.
Would you please give me ideas of why this could be happening?
Thanks a lot in advance,
kind regards,
Mauricio.

A: Stopping debugging calls os.exit(1, true) by default, so you will need to check if the resources are correctly released in this case. If you want to provide your own handler, you can do it by setting require('mobdebug').onexit = function() --[[your exit handler]] end in your application.


text:
Q: How do I add elements to a dynamic array and exclude exsisting elements function addNumifnotThere(numer){
   var numCent = [];

     numCent.forEach(function(){
        if(numer in numCent)
         console.log("you logged that");
        else
         numCent.push(numer);

 });
return numCent;
}

This is my current code, what its attempting to do is read an array and if there is already an element exits the loop and says "you already logged that", obviously if it cannot find a similar element then it pushes it to the array.
I want this to work dynamically so we cannot know the size of the array beforehand, so the first element passed as an argument should be put into the array, (addNum(1) should have the array print out [1], calling addNum(1) again should print "you already logged that")
However there are two problems with this
1) Trying to push to a new array without any entries means everything is undefined and therefore trying to traverse the array just causes the program to print [].
2) Adding some random elements to the array just to make it work, in this case numCent=[1,2,3] has other issues, mainly that adding a number above 3 causes the code to print incorrect information. In this case addNum(5) should print [1,2,3,5] but instead prints [1,2,3,5,5,5]
I know this has to be a simple mistake but I've been dragging myself too long to not ask for help.
EDIT: Thanks to the many outstanding answers here I have now leanred about the indexOf method, thank you guys so much.

A: For every non-match you are pushing the number. Use something like this
var numCent = [];
function addNumifnotThere(numer)
{
    var index = numCent.indexOf(number);
    if(index >=0)
    {
       console.log("you logged that");
    }
    else
    {
       numCent.push(number);
    }

    return numCent;
}

A: Use Array.prototype.indexOf

var numCent = [];
function addNum(numer){

        if (numCent.indexOf(numer) > -1)
        {
            console.log("Number already in array");
        }
        else
        {
           numCent.push(numer);
        }
}

//DEMO CODE, not part of solution
document.querySelector("button").addEventListener("click", function(){
  if (document.querySelector("input").value.length > 0)
  {
      addNum(document.querySelector("input").value);
      document.querySelector("div").innerHTML = numCent.join(", ");
  }
}, false);
Output

<input />
<button>Add number</button>

indexOf tests if an element is inside the array and returns its index. If not found it will return -1. You can test for this. You can try it for your self in this snippet. It will only allow you to add a number (or any string, in this example) once.

I also was confused by the newCent array declaration inside the function. I think, based upon the content of your question, you meant this.

A: If you want the array held in the instance, you can do it like this.
function AddIf(arr){
  if( arr || !this.arr ) {
    this.arr = arr || [];
  }

  return function(number) {
    if( this.arr.indexOf(number) >= 0 ) {
      console.log("Already Present!");
    } else {
      this.arr.push(number);
    }

    return this.arr;
  }.bind(this);
}

// Usage would be like this:
// var addIf = new AddIf([1, 2, 3]);
// addIf(10);  // returns [1, 2, 3, 10]
// addIf(10);  // logs "Already Present!", doesn't add 10 to array

This basically returns a function, with this bound to the function being called.  If you pass in an initial array, it will use that array to compare to when adding it to the array.
You can catch the return function and call it as you would want to.  If you don't call new when invoking however, it will share the same array instance (and have a funky way of being called, AddIf()(10)).
I used fn.bind() to ensure the function gets called in the correct context every time, if you were wondering why I called it like that.

A: Do do this cleanly, I'd consider prototyping the global Array object and adding a method to push values but only if they're unique to the array. Something like this:
Array.prototype.pushUnique = function (item) {
    if (this.indexOf(item) != -1) {
        console.log("Item with value of " + item + " already exists in the array."
    }
    else {
        this.push(item);
    }
}

If you're not comfortable prototypeing global types like Array, you can build the same thing in a procedural pattern:
function arrayPushUnique (arr, item) {
    if (arr.indexOf(item) != -1) {
        console.log("Item with value of " + item + " already exists in the array."
    }
    else {
        arr.push(item);
    }
}

Then to use it, simply create a new empty array and start pushing things to it.
var numCent = [];
// The Array.prototype method
numCent.pushUnique(number);
// The procedural method
arrayPushUnique(numCent, number);


text:
Q: AWS IOT - RegisterThing fails -- InvalidCertificateOwnershipToken This is a real challenge.   I have been successful in everything up to this point in Fleet provisioning on an embedded device.  I have subscribed and published to topics and received new certificates and keys.  But, when I take the certificateOwnershipToken that has been given to me and I try to trigger a DeviceRegistration, I get:
{"statusCode":400,"errorCode":"InvalidCertificateOwnershipToken","errorMessage":"Certificate ownership token cannot be empty."}
My token is 466 characters long and I send it with 2 other items in this string:
{"certificateOwnershipToken":"eyF1ZXJzaW9uIjoiMjAxOTEwMjMiLCJjaXBoZXIiOiJBaURqMUdYMjBiVTUwQTFsTUV4eEJaM3ZXREU1dXZSSURoTy80cGpLS1o1VkVHdlZHQm81THNaS1VydG0zcTdoZGtVR0l1cmJZS0dLVkx2dTZNL2ViT2pkVFdIeDEwU3o3aFZPeExERkxWVlJ4OUIvL2RzcXRIeVp1WVo2RXZoU1k0L0txQ0doZ1lyRklwZGlLK05pUlNHMXlLQXJUSGJXSkNlVUxHcHRPWHJtdHJaNWJMUyt1MHFUcjNJVnlVLzNpcGZVVm1PanpmL3NCYzdSNkNyVGJPZ05Nc2xmOXdHSVRWM0tPUjd1aFFSbnZySnY0S1ZtU2hYc2REODI4K1crRE1xYnRYZGUxSXlJU29XZTVTSHh6NVh2aFF3OGl3V09FSzBwbG15Zi82dUgyeERoNjB1WS9lMD0ifQ==","parameters":{"SerialNumber":"82B910","CertificateId":"175b43a3d605f22d30821c4a920a6231978e5d846d3f2e7a15d2375d2fd5098c"}}
My templates looks right, my policy looks correct.   The role which is attached to my template seem to cover my needs.   I just don't know how AWS is failing without more information.
Does anyone have ideas on how to proceed?

A: I found my problem.   In C/C++ aws iot sdk -- there is a data structure where you must specify the payload string and a few other things.  One of those data elements is the length of the payload and I forgot to set that length before sending my payload to the $aws/provisioning-templates//provision/json   topic.   Once I set that length, then the submission worked and the template was acted upon and the thing was created


text:
Q: Custom Property interface on my own objects I know I can use the Property interface for things like Graph but I want to use it for all of my objects. This includes:

*

*SetProperty

*PropertyValue

*PropertyList

*RemoveProperty
Can I define it in some efficient, non-memory-leaky way for any object I want?

A: The answer is a definitive yes, if you're willing to work with the new Language`ExpressionStore. This goes hand-in-hand with the  Language`MutationHandler stuff to allow us to finally do custom OOP in Mathematica without any odd tricks.
if you just want to play with this scroll down to the example section
Basic Idea
But for the problem at hand, this is actually very simple. We simply make property-store:
$propStore=Language`NewExpressionStore["<PropertyStore>"];

Then we use the get-put-remove interface on this:
containsQ[x_]:=
  $propStore@"containsQ"[x];
containsQ[x_, p_]:=
  $propStore@"containsQ"[x, p];
(* ::Subsubsection::Closed:: *)
(*get*)
get[x_, p_]:=
  $propStore@"get"[x, p];
(* ::Subsubsection::Closed:: *)
(*set*)
set[x_, p_, v_]:=
  $propStore@"put"[x, p ,v];
(* ::Subsubsection::Closed:: *)
(*remove*)
remove[x_]:=
  $propStore@"remove"[x];
(* ::Subsubsection::Closed:: *)
(*keys*)
keys[]:=
  $propStore@"getKeys"[];
keys[x_]:=
  $propStore@"getKeys"[x];
(* ::Subsubsection::Closed:: *)
(*list*)
list[]:=
  $propStore@"listTable"[];

And now we can use this naturally as a property set/get mechanism.
Fun Example
I put this all into a little package that imitates the syntax of Property and friends. Load this from GitHub:
Get["https://github.com/b3m2a1/mathematica-tools/raw/master/Props.m"]

then we'll define a function that caches results in a memory cheap way:
cachedCompute[m_, p_, fn_] :=
 Replace[PropVal[m, p],
  Missing["PropertyAbsent", p] :>
   With[{val = fn[m]},
    SetProp[m, p -> val];
    val
    ]
  ]

Module[{},
  (* I  do this to avoid $HistoryLength *)
  m1 = MemoryInUse[];
  myMat = RandomReal[{}, {100, 100}];
  m1
  ];

t1 = RepeatedTiming[cachedCompute[myMat, "Inverse", Inverse]][[1]];
t2 = RepeatedTiming[Inverse[myMat]][[1]];
m2 = MemoryInUse[];

t2/t1

5.*10^1

m2 - m1

167088

Clear@myMat

MemoryInUse[] - m1

10480

And we see the caching got us a 50x speed-up but once the original matrix was cleared, the cached memory was free.
Fast properties without memory leaks, thanks to Jason B.
Direct Overloading
We can also make use of this to do some direct overloading for our own type, e.g.:
myObj /: PropertyValue[obj_myObj, key_] :=
  PropVal[obj, key];
myObj /: SetProperty[obj_myObj, p : (Rule | RuleDelayed)[key_, val_]] :=

  SetProp[obj, p];
myObj /: RemoveProperty[obj_myObj, key_] :=
  RemoveProp[obj, key];
myObj /: PropertyList[obj_myObj] :=
  PropList[obj];

Now it's pretty easy to work with:
o = myObj[];

PropertyValue[o, "test"]

Missing["PropertyAbsent", "test"]

SetProperty[o, "test" :> RandomReal[]]

PropertyValue[o, "test"]

0.131471

PropertyValue[o, "test"]

0.882595

RemoveProperty[o, "test"]

Props`Private`$$hold[RandomReal[]] (* just a byproduct of how Hold-ing is done in the package *)

Note that this is happening on the Expression itself and not the Symbol:
With[{o = o},
 SetProperty[o, "test" :> RandomReal[]];
 PropertyValue[o, "test"]
 ]

0.170485


text:
Q: Pyautogui changing my window size when I import it When I import pyautogui as pag on my gui code, the window size change. This becomes an issue when I use two different monitors which have different resolutions. I wanted to know if there is a way to just disable pyautogui from doing any form of resizing? The example bellow only works when I start it when my second monitor is not connected so I am only using my laptop monitor which has a resolution 1920 x 1200. The second monitor has a higher resolution, and for it there is not issue, even when I drag the tkinter window to the laptop monitor, there is still no issue. This issue only seems to happen when I start the program without having my second monitor connected. The button in the example is meant to show how the window changes when pyautogui is imported.
from tkinter import *

win = Tk()
win.geometry("1270x725+0+0")
win.minsize(width=1270, height=600)
win.maxsize(width=1270, height=600)

def test():
    import pyautogui as pad

button = Button(win, command=test)
button.place(relx=.5, rely=.5)

win.mainloop()

A: This is a complicated issue.  I'm assuming you are running on Windows, because I don't think the issue would occur anywhere else.
The problem here has to do with high DPI monitors.  Windows knows that most people don't like reading teeny tiny pixels and little tiny fonts on high-DPI monitors, so it lies to applications about the actual dot resolution.  That produces the best results in most cases, but some applications want to know the exact DPI so they can take their own appropriate action.  Windows calls this a "high DPI aware application".
On Windows, the first thing pyautogui does is call the SetProcessDPIAware() API, which tells Windows you don't want any remapping.  That changes the meaning of the pixel coordinates you get on your high DPI monitor.
I can see two practical workarounds.  One, you could tweak _pyautogui_win.py in the pyautogui module to delete that call.  That's going to have some effect on the internals of pyautogui, but it's not clear what.  Two, you could call SetProcessDPIAware() early in your own code.  That would put the burden on YOU to decide how to handle windows that exist on monitors of different resolution.


text:
Q: Entity Framework Context 6.1.3 not Refreshed / Destroyed? In this unittest I will verify that the MD5 of the Content byte column is calculated, persisted and fetched correctly.
However, it seems that the Entity Framework (6.1.3) context is not refreshed / destroyed, since after the raw SQL UPDATE that clearly takes effect, but not shown when fetching the row with a new context.
namespace UnitTests
{
    [TestClass]
    public class TestDataPacketServiceDebug
    {
        [TestInitialize]
        public void Setup()
        {
            CommonMethods.ResetDatabase();
            try
            {
                CommonMethods.ResetDataPacketDirectory();
            }
            catch (DirectoryNotFoundException)
            {
            }
        }

        [TestCategory("DataPacketService"), TestMethod]
        public void TestGetLocalFilePathDebug()
        {
            // Persist a DataPacket
            int dataPacketId;
            using (var testDBContext = new TestDBContext())
            {
                DataPacket dataPacket = new DataPacket
                {
                    Content = File.ReadAllBytes(@"Resources\SampleResources.zip"),
                    Description = "DataPacketSample consist of some random found .DLL files on disk",
                    Name = "SampleResources",
                    Version = "1"
                };
                testDBContext.DataPackets.Add(dataPacket);
                testDBContext.SaveChanges();
                dataPacketId = dataPacket.DataPacketId;
            }

            // Verify file path extraction
            using (var testDBContext = new TestDBContext())
            {
                DataPacket dataPacket = DataPacketService.GetByNameAndVersion("SampleResources", "1",
                    testDBContext);

                string extractedFilePath = DataPacketService.GetLocalFilePath(testDBContext,
                    dataPacket, "EntityFramework.dll");

                string validDestinationPath = String.Format(@"{0}\DataPackets\{1}_v{2}\EntityFramework.dll",
                    AppDomain.CurrentDomain.BaseDirectory, dataPacket.Name, dataPacket.Version);

                Assert.AreEqual(validDestinationPath, extractedFilePath);

                if (File.Exists(extractedFilePath) == false)
                {
                    Assert.Fail("SampleResources was not extracted correctly");
                }
            }
            // When setting a breakpoint here and take a look with external SQL Browser
            // (e.g. Microsoft SQL Server Management Studio), following is in order:
            // Note! Not all columns are shown
            // -----------------------------------------------------------------------------------------------
            // DataPacketId | Name            | RowVersion | Content     | MD5                      | Version
            //            1 | SampleResources | NULL       | 0x504B03... | 2zSV8IChaiyf0UfnezDHKg== | 1

            // Manually modify MD5 field in database for MD5 verification
            using (var testDBContext = new TestDBContext())
            {
                string sqlUpdate = String.Format("UPDATE dbo.DataPackets SET MD5 = 'another_MD5' WHERE DataPacketId = {0}",
                    dataPacketId);
                testDBContext.Database.ExecuteSqlCommand(sqlUpdate);
            }
            // When setting a breakpoint here we can clearly see that the row has been changed:
            // Note! Not all columns are shown
            // ----------------------------------------------------------------------------------
            // DataPacketId | Name            | RowVersion | Content     | MD5         | Version
            //            1 | SampleResources | NULL       | 0x504B03... | another_MD5 | 1

            // Verify MD5
            using (var testDBContext = new TestDBContext())
            {
                // Fetch dataPacket with modified MD5
                DataPacket dataPacket = DataPacketService.GetByNameAndVersion("SampleResources", "1", testDBContext);

                // Verify that the raw SQL command has been successful:
                Assert.AreEqual("another_MD5", dataPacket.MD5);
                // BANG!!!!!!!!!!!!!!
                // Result Message:  Assert.AreEqual failed. Expected:< another_MD5 >.Actual:< 2zSV8IChaiyf0UfnezDHKg== >.
            }
        }
    }
}

Entity:
public class DataPacket
{
    /// <summary>
    /// Identifier
    /// </summary>
    public int DataPacketId { get; set; }

    /// <summary>
    /// Concurrency Token
    /// </summary>
    public byte[] RowVersion { get; set; }

    /// <summary>
    /// Name
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Description of data packet
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// Version of data packet
    /// </summary>
    public string Version { get; set; }

    /// <summary>
    /// MD5 of the data packet (i.e. MD5 of Content byte array)
    /// </summary>
    public string MD5 { get; private set; }

    private byte[] content;

    /// <summary>
    /// Byte content of the data packet (i.e.
    /// </summary>
    public byte[] Content
    {
        get { return content; }
        set
        {
            content = value;
            UpdateMD5();
        }
    }

    /// <summary>
    /// TestCase navigation DataPacket <== One-To-Many ==> TestCases
    /// </summary>
    public ICollection<TestCase> TestCases { get; set; } // DataPacket <== One-To-Many ==> TestCases

    /// <summary>
    /// Update MD5 checksum depending on content
    /// </summary>
    private void UpdateMD5()
    {
        if (content != null)
        {
            this.MD5 = GetMD5ForBytes(content);
        }
    }

    /// <summary>
    /// Get MD5 checksum for content byte array
    /// </summary>
    /// <param name="content">Content byte array</param>
    /// <returns>MD5 checksum</returns>
    public static String GetMD5ForBytes(byte[] content)
    {
        if (content != null)
        {
            System.Security.Cryptography.MD5 md5Object = System.Security.Cryptography.MD5.Create();
            return System.BitConverter.ToString(md5Object.ComputeHash(content)).Replace("-", "");
        }

        return null;
    }
}

GetByNameAndVersion
public static DataPacket GetByNameAndVersion(string name, string version, TestDBContext testDBContext)
        {
            IQueryable<DataPacket> query = testDBContext.Set<DataPacket>();
            query = query.Where(t => t.Name == name).Where(t => t.Version == version);
            return query.Single();
        }

Note! I am using a localDB database.

A: It's not a EF context issue (it works as expected), but incorrect test / logic in your DataPacket class.
You have two related properties, both mapped to database table columns:
/// <summary>
/// MD5 of the data packet (i.e. MD5 of Content byte array)
/// </summary>
public string MD5 { get; private set; }

private byte[] content;

/// <summary>
/// Byte content of the data packet (i.e.
/// </summary>
public byte[] Content
{
    get { return content; }
    set
    {
        content = value;
        UpdateMD5();
    }
}

The client C# code can only set the Content which in turn updates the MD5 - fine. But what happens when EF loads the entity from the database? Indeed, it uses the same property setters (the private is not a problem because EF uses reflection / code generation, so it can call externally any type of setter).
Now everything depends on the order of calling setters. In your case the MD5 is called first, then the Content. Since your SQL command updated the MD5 column, but left Content unchanged, the first setter will set the MD5 value from the database, and the second setter will update it back from the Content. Which of course is causing the assertion to report failure.
It's up to you to decide whether updating the MD5 column in database through SQL is valid operation (basically leaving the MD5 and Content out of sync). The order of calling the property setters in undefined - currently if you move the MD5 property declaration after the Content property, the test will pass, but it's something you cannot rely on.


text:
Q: Flex: Testing UI components at the click level? I've been working on a Flex component and I'd like to write some automated tests for it. The trouble is, the UI testing tools I've looked at (FlexMonkey and Selenium Flex API) don't simulate "enough":
Most of the bugs which have come up so far relate to the way Flex deals with dragging and dropping, which these libraries can't simulate accurately enough. For example, I need to test a case where there is a "drop" event which occurs in the bottom half of a component – neither FlexMonkey nor Selenium Flex API can do that (they may simulate a mouse event, but they won't include coordinates).
So, is there any "good" way to automate that sort of testing?
Edit: After much research, it looks like the only piece of software that can do this is iMacros, which is Windows-only and the interface is... Lacking. So I'm going to be writing my own.  Basically, it will put an HTTP interface on java.awt.Robot so code (in any language) can simulate mouse/keyboard events.  If you're interested, PM me and I'll keep you updated.
Edit 2: I have published the first version of the framework I wrote, Blunderbuss, over at BitBucket: http://bitbucket.org/wolever/blunderbuss/ . You'll need Jython to run it (http://www.jython.org/), but after that the flex-client example should work.
Videos of Blunderbuss live over at Vimeo:

*

*Automating Flex testing with Blunderbuss

*Blunderbuss test suite running
At the moment this remains a proof-of-concept, as I haven't had the cycles to clean it up and make it more useable… But maybe enough people bothering me would give me that time :)

A: I've used Eggplant to test Flash and AIR apps without having to add any hooks into the code. It's a great tool but it's quite expensive. It simulates a real user by VNC-ing into a system and uses image recognition - among other things - to interact with the app.

A: I am definitely interested in your custom Java class, and (though I am not the best at Java (yet...)), I would be willing to help out if you're thinking of making this collaborative.
As to Flash MouseEvents.  Unfortunately, there really isn't an accurate way to simulate the drag/drop experience in Flash.  MouseEvents, when generated by the mouse, are handled in a very different way than regular events and while you could simulate actions by passing events into the handling functions, or by making the dispatcher fire a new DragEvent( DragEvent.DRAG_DROP..., it will not be the same as having the user interact with it.  And for some functionality (like gaining access to the clipboard), nothing inside Flash will accomplish your goals.
To be honest, you're probably headed in the right direction -- using something which is not written in Flash to drive faked mouse events is probably your best bet.

A: I've never had to use it in Flex but i recently stumbled across some info on automation packages in the MS Surface SDK... after looking into it those classes automated user behavior which can be used for testing i.e. move a fake mouse to this point, perform this action.  As you're using Flex mx.automation packages and classes.  My guess (and hope) is that you'd be able to achieve what you want using these classes.

A: You could also try auto-hotkey - it is similarly a macro-editing program but it has proven to be very efficient and you can write scripts and set it up very easily.


text:
Q: When I make a post request to add a new user, it doesn't save anything and I can't think of any reason why. Any ideas? I'm making an app with express and mongoose, https://github.com/findjashua/express_app

*

*app.coffee
app.post '/user', user.add

*models/user.coffee
createUser = (req) ->
    user = new User
        name : req.body.name
        email : req.body.email
        phone : req.body.phone
    return user

# ...

exports.add = (req, res) ->
    user = createUser req
    res.send dbService.save(user)

*services/db.coffee
exports.save = (document)->
    document.save (err)->
        if err
            console.log err
        return document

When I make a post request to add a new user, it doesn't save anything and I can't think of any reason why. Any ideas?

A: document.save() is asynchronous, so return isn't really an option within dbService.save().

*

*The res.send() will have already finished before return document is evaluated.

*It also returns document to the code that called the callback, which is within document.save, not to your code within user.coffee.

You'll need to adjust dbService.save() to accept a callback so you can res.send() the finished document:
exports.save = (document, callback) ->
    document.save (err, document) ->
        if (err)
            callback(err)
        else
            callback(null, document)

exports.add = (req, res) ->
    user = createUser req
    dbService.save user, (err, user) ->
        res.send err ? user

Note: that 1st snippet can be simplified, depending on whether or not .save() needs to do anything else:
exports.save = (document, callback) ->
    document.save callback


text:
Q: How to get the name of the current kde activity? How to print the name of the current kde activity alone?
The activity bar displays all activities, highlighting the current one.
I would find useful an unobtrusive widget to print the current activity name only.
thank you
p.

A: Using a widget (verbose instructions for future readers):
In Plasma Desktop's default panel (the bar at the bottom of the desktop), right-click on a free area and select "Add Widgets"; in the Widgets panel, search for "Activities"; drag the Activities widget to the panel. It is a relatively unobtrusive widget that shows the name of the current activity and opens the activity manager when clicked on.
Using D-Bus (noting that the question's first revision explicitly mentioned it):
CurrentActivity=$(dbus-send --session --dest=org.kde.ActivityManager \
  --type=method_call --print-reply=literal /ActivityManager/Activities \
  org.kde.ActivityManager.Activities.CurrentActivity | tr -d "[:blank:]")

dbus-send --session --dest=org.kde.ActivityManager --type=method_call \
  --print-reply /ActivityManager/Activities \
  org.kde.ActivityManager.Activities.ActivityInformation \
  "string:$CurrentActivity"

You may want to use -print-reply=literal instead of -print-reply to reduce the amount of output. It can then be filtered, piping it through something like awk 'NR==2 {print $2}' to get the current activity's name only. Note, though, that activity names can include white spaces, tabs and double quotes, making dbus-send's output hard, if not impossible, to parse reliably in the general case.


text:
Q: Why updating a running Linux system is not problematic? It's years I use Linux systems on a daily basis, and I never had major problems by updating a system when it was running, but I still wonder why this is possibile.
Let me make an example.
Suppose a program "A" from a certain package is running on a system. This program, at a certain point, needs to open another file ("B") from the same package. After that, program "A" closes "B" because it doesn't need it anymore. Suppose now I update the package "A" and "B" belong to. "A" is not directly affected by this operations, at least for the moment, since it is running in RAM and the update just replaced "A" on the hard disk. Suppose "B" has been replaced on the filesystem, too. Now "A" needs to read "B" again for some reason. The question is: is it possible that "A" could find an incompatible version of "B" and crash or malfunction in some other way?
Why nobody update their systems by rebooting with a live CD or some similar procedure?

A: Yes, what you described is possible, but most of the time if the file is included with the package, it's going to be a library or other file which is read once and only once (since it doesn't change, there's no reason to read it multiple times). Also if the file is needed long term, the application will likely leave the file handle open, in which even if it does get replaced on the actual filesystem, the open file handle will keep the old version open.
In most cases, any data which is read multiple times during the life of the process is user/variable data, and this wouldn't change during a package upgrade. Plus since the data is variable, any programmer in their right mind would make sure the program can handle it changing from one read to the next.

A:
Suppose "B" has been replaced on the filesystem, too. Now "A" needs to
  read "B" again for some reason. The question is: is it possible that
  "A" could find an incompatible version of "B" and crash or malfunction
  in some other way?

This is possible, but unlikely in most cases.  If "B" is a code library, then the original version would usually not be closed.  "A" would continue to use the original version of "B".  If you run "A" after the update, the new version of "B" would be used.  During the update, there is some risk that incompatible versions could be loaded.  However, due to the way code libraries are loaded this should only be a problem if "A" need functionality not present in the versions of "B" that it loaded.
Good coding practice keeps the interface to functions the same.  As a result it doesn't matter much which version is loaded, other than if there were bugs fixed in the newer version.
Configuration files are a slightly different matter, but are usually read during startup.  In this case, "A" would not read "B" unless a reload of the configuration was changed.  Again, it would be bad coding practice to change the format or meaning of the configuration file.  An incompatible version of the configuration file should have a different name, so it wouldn't cause a problem.

Why nobody update their systems by rebooting with a live CD or some similar procedure?

Shutting down and rebooting from a different version would lead to a service outage.  For servers, this is generally not desired.  In any case, the package manager on the running system is aware of the software and versions it has installed.  Live CDs have there own list of installed software, possibly with different versions.  This makes it difficult to reliably upgrade the running system from the live CD.
Live CDs are sometimes used when a new release of the O/S is being installed.  In this case, the a clean installation of the O/S is usually done.  This can limit the amount of unused files from the previous version being retained.  It can be more effort than upgrading the live system.  However, if different root partitions are used, it can limit the risk of being stuck with an unbootable partially updated system.

A: Updating Userland is Rarely a Problem
You can often update packages on a live system because:

*

*Shared libraries are stored in memory, not read from disk on each call, so the old versions will remain in use until the application is restarted.

*Open files are actually read from file-descriptors, not the file names, so the file contents remain available to the running applications even when moved/renamed/deleted until the sectors are over-written or the file descriptors are closed.

*Packages that require reloading or restarting are usually handled properly by the package manager if the package has been well-designed. For example, Debian will restart certain services whenever libc6 is upgraded.

Generally, unless you're updating your kernel and aren't using ksplice, then programs or services may need to be restarted to take advantage of an update. However, there's rarely a need to reboot a system to update anything in userland, although on desktops it's occasionally easier than restarting individual services.
See Also
http://en.wikipedia.org/wiki/Ring_%28computer_security%29#Supervisor_mode

A: There are some cases where this IS a problem:

*

*JDK upgrade while a java-VM is running:
I asked myselv the same question that you got - I had a running tomcat that uses java. Now after a patch-update of the JDK it still ran without problems - so it seemed.

Now the explanation is cache-memory. OK - I started a memory-hog-program to use up all available RAM - and then tomcat crashed (after I accessed the applicaton running there).

*

*Kernel-Upgrade on SuSE-systems: On SuSE the old-kernel and its modules get deleted right after patch-upgrade of the kernel. If you then want to use something new, that requires a kernel-module, that was not loaded up until now, the service will fail.


text:
Q: iisnode hang issue I am presently using node 0.8 with iisnode 0.1.21.
I have set nodeProcessCountPerApplication="4"  in the web.config under the iisnode tag.
My application starts perfectly with 4 node processes but it hangs after some time. It does not crash.
I observed that this happens once any one of the processes starts using more than 200mb of memory. Does any body know if this is a memory issue or is it something else?
Furthermore if i shutdown/endtask any one of the processes from the task manager, every thing starts working perfectly.

A: Does the same app work correctly when self-hosted outside IIS? This behavior could occur if you end up blocking the event loop in the node.exe processes. The processes using up 200MB each sounds makes me think you are doing something out of the ordinary.


text:
Q: How to retrieve another user's info like email and displayName in Firebase? I have a users node in Firebase storing each user's information, but excluding displayName andemail`, which is in firebase auth DB.
One day, I realise that I also need user's displayName and email info.
For example, in a page created by another user, I want to display that user's displayName and email.
By given that

*

*displayName and email are not stored under the users node,

*the user's uniqueId is known

Is it possible to retrieve the user's displayName and email from firebase auth DB (by either normal user or admin)?
or what shall I do for users that were already created in firebase?
Thanks,
D

A: With the AdminSDK it is possible like explained here.
In the doc there is examples for every method, but in your case I guess that you searched for this
admin.auth().getUser(uid)
    .then(function(userRecord) {
        // See the UserRecord reference doc for the contents of userRecord.
        console.log("Successfully fetched user data:", userRecord.toJSON());
    })
    .catch(function(error) {
        console.log("Error fetching user data:", error);
    });

You can do things like userRecord.displayName. The full interface is here.


text:
Q: KendoUI Grid with DatePicker column doesnot return correct Data I am facing issue with grid inline editing with one of the Date type column. Following are the corresponding code
cshtml

id: "ItemId",
fields: {
ItemId: { editable: false, nullable: true },
Name: { validation: { required: true } },
FromDate: { validation: { required: true }, type: "date"},

columns: [
{ field: "Name", width: "150px" },
{ field: "FromDate", title:"Active From", width: "150px", format: "{0:dd MMM yyyy}"},

All works fine till loading data in to the grid and then when I choose to edit the row FromDate field does have DatePicker. Change the date correct date is displayed and datepicker closed. But then when I try to update this edited data to DB The date available to
public DateTime FromDate { get; set; }

is {01-01-0001 00:00:00} and not the new date I have selected.


text: Q: Geodesic multiple ring buffer in ArcGIS The Buffer tool in ArcGIS 10.5 allows for the creation of geodesic buffers, however, I am unable to find that option for the Multiple Ring Buffer. I have 10 areas around which I need to create 6 geodesic ring buffers (huge areas so quite a difference regarding area) and I'd like to use the multiple ring buffer tool to avoid having to clip each ring. Any ideas how to best achieve this?


text:
Q: VS2010 don't publish particular folders/files I saw this question but it's related to VS2008 so I thought maybe things have changed:
Don't publish particular folder in ASP.NET
Anyway the question is, when I publish my ASP.net website it creates the publish folder and publishes files such as web.configand the images/ directory.  The web.config on the live server has different configuration, and the images don't need to be uploaded again.
Can I make it not publish specific files/folders as it would make my upload process a lot faster and safer.

A: Yes. Simply change Build Action property of your file to None

A: The solution must contain a project file (.csproj). You get this if you work with Web Application projects instead of Web Site projects. You can also convert you Web Site project to the Web Application project. Personally I never work with Web Site projects, they have management issues (like the one we are discussing about) and offer little support for additional projects, like Console App project or Class Library projects.

A: In my case, since I use a web site project, I simply cut & paste the massive images folder to a parent folder outside of the project before publishing. Then, I cut & paste the folder back into the project folder after publishing completes. It only takes a few seconds to do this.