text:
Q: Computing kernels of a matrix in distinct cases I have the following matrix:
{{c1 d1 - e1 f1, c1 d2 - e1 f2, c1 d3 - e1 f3, c1 d4 - e1 f4},
 {c2 d1 - e2 f1, c2 d2 - e2 f2, c2 d3 - e2 f3, c2 d4 - e2 f4},
 {c3 d1 - e3 f1, c3 d2 - e3 f2, c3 d3 - e3 f3, c3 d4 - e3 f4},
 {c4 d1 - e4 f1, c4 d2 - e4 f2, c4 d3 - e4 f3, c4 d4 - e4 f4},
 {c5 d1 - e5 f1, c5 d2 - e5 f2, c5 d3 - e5 f3, c5 d4 - e5 f4},
 {c6 d1 - e6 f1, c6 d2 - e6 f2, c6 d3 - e6 f3, c6 d4 - e6 f4}}

From the way it's constructed, I know that the rank can be at most two. If I ask Mathematica to row reduce the matrix, I end up with the following:
{{1, 0, (d3 f2 - d2 f3)/(-d2 f1 + d1 f2), (d4 f2 - d2 f4)/(-d2 f1 + d1 f2)},
 {0, 1, (d3 f1 - d1 f3)/(d2 f1 - d1 f2), (d4 f1 - d1 f4)/(d2 f1 - d1 f2)},
 {0, 0, 0, 0},
 {0, 0, 0, 0},
 {0, 0, 0, 0},
 {0, 0, 0, 0}}

As can be seen, this is only valid when $d_1f_2\neq d_2f_1$. Furthermore, if I look at the left kernel, then Mathematica gives me the following basis:
{{-((-c6 e2 + c2 e6)/(c2 e1 - c1 e2)), -((c6 e1 - c1 e6)/(c2 e1 - c1 e2)), 0, 0, 0, 1},
 {-((-c5 e2 + c2 e5)/(c2 e1 - c1 e2)), -((c5 e1 - c1 e5)/(c2 e1 - c1 e2)), 0, 0, 1, 0},
 {-((-c4 e2 + c2 e4)/(c2 e1 - c1 e2)), -((c4 e1 - c1 e4)/(c2 e1 - c1 e2)), 0, 1, 0, 0},
 {-((-c3 e2 + c2 e3)/(c2 e1 - c1 e2)), -((c3 e1 - c1 e3)/(c2 e1 - c1 e2)), 1, 0, 0, 0}}

Again, this basis is only valid when $c_1e_2\neq c_2e_1$. I need to find a basis in the case that $c_1e_2=c_2e_1$ and a row reduction when $d_1f_2=d_2f_1$. How can this be done?

A: You can use the option ZeroTest as follows:
mat = {{c1 d1 - e1 f1, c1 d2 - e1 f2, c1 d3 - e1 f3, c1 d4 - e1 f4},
       {c2 d1 - e2 f1, c2 d2 - e2 f2, c2 d3 - e2 f3, c2 d4 - e2 f4},
       {c3 d1 - e3 f1, c3 d2 - e3 f2, c3 d3 - e3 f3, c3 d4 - e3 f4},
       {c4 d1 - e4 f1, c4 d2 - e4 f2, c4 d3 - e4 f3, c4 d4 - e4 f4},
       {c5 d1 - e5 f1, c5 d2 - e5 f2, c5 d3 - e5 f3, c5 d4 - e5 f4},
       {c6 d1 - e6 f1, c6 d2 - e6 f2, c6 d3 - e6 f3, c6 d4 - e6 f4}};

RowReduce[mat, ZeroTest ->
    (PossibleZeroQ[Simplify[#, Assumptions -> {-d2 f1 + d1 f2 == 0}]] &)]//Short[#, 5] &

Similarly,
RowReduce[Transpose@mat, ZeroTest ->
         (PossibleZeroQ[Simplify[#, Assumptions->{c2 e1 - c1 e2 == 0}]] &)]//Short[#, 5] &


text:
Q: This database cannot be imported when using |DataDirectory| I try to add my value in local database (created by Add -> Service-based database).
My code:
//string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\VS_MyProjects\DBAppliaction\DBAppliaction\Database1.mdf;Integrated Security=True";
            string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;";

            string query = "INSERT INTO [dbo].[Table] (Test) " +
                   "VALUES (@Test) ";

            // create connection and command
            using (SqlConnection cn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(query, cn))
            {
                // define parameters and their values
                cmd.Parameters.Add("@Test", SqlDbType.NChar, 10).Value = "test";

                // open connection, execute INSERT, close connection
                cn.Open();
                cmd.ExecuteNonQuery();
                cn.Close();
            }

When I use full path to my db it's all okay. In "Show Data Table" appear my added value. But when I use in path |DataDirectory| and press button "Update" in "Show Data Table" for verify added my value or no I have seen the error: "This database cannot be imported. It is either an unsupported SQL Server verison or an unsopported database compatibility". Why?

A: In your connection string the Initial Catalog key/value pair is missing. This means that when the database file MDF is attached by LocalDB its full path name is used and in subsequent runs of your program the attach fails. Instead if you provide an Initial Catalog value the subsequent runs simply use that catalog
So change your connection string to
string connectionString = @"Data Source=(LocalDB)\v11.0;
                            AttachDbFilename=|DataDirectory|\Database1.mdf;
                            Initial Catalog=LogicalNameOfYourDatabase
                            Integrated Security=True;";

Of course the first problem (data apparently not saved) is caused by the behavior of DataDirectory substitution string coupled with the way in which Visual Studio handles the MDF files attached to your project (as explained in another answer here)

A: I ran into a similar problem with VS2012 and SQL2014. Essentially, your SQL tools in VS are not current with the SQL server. The fix was to install SQL2014 management tools locally on my development PC.

A: Try this:
string connectionString = @"Data Source=(LocalDB)\v11.0;
                        AttachDbFilename="+System.IO.Path.GetFullPath("Database1.mdf")+";
                        Initial Catalog=LogicalNameOfYourDatabase
                        Integrated Security=True;";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse Marketplace option not available in Help menu Eclipse Marketplace option not available in Help menu.
If link is available to install Marketplace client in STS 3.8.4 would be useful,
so that i can install marketplace via Install new software.

A: Open the Spring Dashboard, go to IDE Extensions and install Spring IDE(Tool support for the Spring Framework), restart the IDE and the option will appear. That works for me in STS 3.8.4

A: Use this link to install market place as new software.
https://www.l3harrisgeospatial.com/docs/installnewsoftware.html
URL for market place install is : http://download.eclipse.org/releases/2019-12
2019-12 represent eclipse version you are using for me it was 2020-06 {version :4.16}
hence URL for me changed to  http://download.eclipse.org/releases/2020-06
then restart the IDE.
search for Spring ide in market place after reopening it will show version 3 tool.


text:
Q: How to determine the reason for Windows spontaneous shutdown? Update 2: Tracking the reasons for a few shutdowns in the past couple of weeks, using the Event Viewer without filtering events, to get to the approximate time of shutdown, it seems like the last few shutdowns were caused by system overheating, and not by some malicious script or process.
I will continue to monitor that and update this question if new findings are observed.

Update 1: I used Sysinteranls Autoruns utility as suggested by @Mark, and listed all the (non-Microsoft) startup objects, to look for a script that supposedly calls Shutdown. After exporting and cleaning the list of the known binary file types (.exe, .sys, .dll) I saw two proprietary binary files belonging to a specific application which I installed some time ago. The computer was problematic long before I installed that app, so I do not think those are related to the problem, but I uninstalled it anyway. Other than the binaries and a few File not found entries, there are no other entries in the list.
Is there a way to log what application called the shutdown.exe utility?

Original question: My Dell E7450 Win10 laptop regularly shuts itself down spontaneously. Looking online, I found a couple of resources pointing to the Event Viewer application.
Following the instructions, I am able to see the list of shutdown events (codes 1074, 6006, 6008). It seems like no 6006 and 6008 events are recorded. Of the multiple 1074 events, I see a few that are related to the software updates, but many that are related to the spontaneous shutdowns.
Examining the event(s), they all look like the following. The reason code is 0x800000ff and no reason nor comment are provided.
I can normally immediately turn the computer on again, and log into Windows.
Upon these shutdowns, the work is not properly saved, if not by the auto-save features of the various running apps (if they have ones). With Chrome, I sometimes get the "Restore previous session" popup, and sometimes have to go through the History menu to reopen the previous Chrome windows.
How can I determine the reason for those shutdowns?

A: Tracking the reasons for a few shutdowns in the past couple of weeks, using the Event Viewer without filtering events, to get to the approximate time of shutdown, it seems like the last few shutdowns were caused by system overheating, and not by some malicious script or process.
I will continue to monitor that and update this question if new findings are observed.

A: The symptoms I witnessed in my Dell E7450, Windows 10:

*

*Spontaneous shutdowns.

*In the "Reliability Monitor" (easier UI compared to "Event Viewer") I saw not only the shutdowns, but many warnings by Google Updater. I blamed Chrome for that.

*The battery icon (at the taskbar) sometimes showed an icon of a battery crossed out, as if the battery is not recognized. I almost bought a new battery just because of that.

The changes I made about 5 days ago, that seem to have stopped the all symptoms (for now... crossing my fingers):

*

*Uninstalled Chrome browser, because of the warnings in the "Reliability Monitor". Computer kept crashing, though, but I'm still with Chrome uninstalled.

*Uninstalled the "Intel Dynamic Platform and Thermal Framework Driver" that I once got from Dell's site (support.dell.com, where this driver was marked with their blue THIS PC badge, i.e. believed to be most suitable for my PC, I guess). See "p.s." below for more details on the driver.

*Following some voodoo suggestion from somewhere (I forgot where), I modified the Battery plan settings from "100%" to "98%" in two places as follows: in the computer's power options  (Control Panel\Hardware and Sound\Power Options), "Change plan settings", "Change advanced power setting". Then scroll down to "Processor power management > Maximum processor state" and change 100% to 98% for both "> On battery" and "> Plugged in".
I hope that some of this makes sense / will help!

p.s. More details on the driver:
Intel Dynamic Platform and Thermal Framework Driver
Version: 8.3.10209.6897, A12
Last Updated Date: 18 Mar 2020
File Name: Intel-Dynamic-Platform-and-Thermal-Framework_74P16_WIN_8.3.10209.6897_A12.EXE
File size: 14.65 MB

Reason for uninstalling it: I suspected that a software might cause the flukes in not recognizing the battery or deal inappropriately (shutdown) with an alleged heating etc.; also, in the "View full driver details" for this driver, it says that it's an "Update Package for MS Windows 32-Bit" while mine is 64-bit (sure, they also say "...designed to run on Microsoft Windows 64bit Operating Systems", but I don't trust programmers).

A: A while ago I made this long PowerShell one-liner using custom code. It's looking for events in the log around the time of the reboot. It downloads the code for my Get-RebootReport function and executes a few commands. It will give you an idea of what was happening around that time.
The code source is behind the URI if you want to verify it doesn't do anything other than what I claim.
$csvPath="$($env:temp)\temp.csv";$LogNames=@('System','Application');[Net.ServicePointManager]::SecurityProtocol=[enum]::GetNames([Net.SecurityProtocolType])|Foreach-Object{[Net.SecurityProtocolType]::$_};(New-Object Net.WebClient).DownloadString( 'https://raw.githubusercontent.com/tonypags/PsWinAdmin/master/Public/Get-RebootReport.ps1' )| iex;$LastRebootTime = (Get-RebootReport)[0].Date;$Events=@();$LogNames|%{$FilterHashtable = @{LogName=$_;EndTime=($LastRebootTime.AddMinutes(1));StartTime=($LastRebootTime.AddMinutes(-5));};Get-WinEvent -FilterHashtable $FilterHashtable|%{$Events += $_}};$Events| sort TimeCreated |select LogName, TimeCreated, ProviderName, Message | export-csv $csvPath -notype; ii $csvPath


text:
Q: Encryption and Decryption Rijndael algorithm C# and WPF I have 1 TextBox in which the encryption key is entered, 2 ButtonEnc and ButtonDec buttons. When using saveFileDialog, nothing happens, an empty file is saved, and the Encrypt method error Encryption failed!", "Error.
I can't save encryption/Decryption file.
How can I change the code so that everything works as it should?
    private void ButtonEnc_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        Microsoft.Win32.SaveFileDialog dlg1 = new Microsoft.Win32.SaveFileDialog();

        Nullable<bool> result = dlg.ShowDialog();
        Nullable<bool> result1 = dlg1.ShowDialog();

        sKey = TextBox1.Text;
        if (result == true)
        {
            string inputFile = dlg.FileName;
            dlg1.Filter = "aes documents (.aes)|*.aes";
            if (result1 == true)
            {
                sKey = TextBox1.Text;
                string outputFile = dlg1.FileName;
                EncryptFile(inputFile, outputFile);
            }
        }
    }

    private void EncryptFile(string inputFile, string outputFile)
    {
        try
        {
            sKey = TextBox1.Text;
            string password = sKey;
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
            RijndaelManaged RMCrypto = new RijndaelManaged();
            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, key),
                CryptoStreamMode.Write);
            FileStream fsIn = new FileStream(inputFile, FileMode.Open);
            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch
        {
            MessageBox.Show("Encryption failed!", "Error");
        }
    }

    private void DecryptFile(string inputFile, string outputFile)
    {
        {
            sKey = TextBox1.Text;
            string password = sKey;
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);
            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
            RijndaelManaged RMCrypto = new RijndaelManaged();
            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateDecryptor(key, key),
                CryptoStreamMode.Read);
            FileStream fsOut = new FileStream(outputFile, FileMode.Create);
            int data;
            while ((data = cs.ReadByte()) != -1)
                fsOut.WriteByte((byte)data);
            fsOut.Close();
            cs.Close();
            fsCrypt.Close();
        }
    }

    private void ButtonDec_Click_1(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.SaveFileDialog dlg1 = new Microsoft.Win32.SaveFileDialog();
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

        Nullable<bool> result = dlg.ShowDialog();
        Nullable<bool> result1 = dlg1.ShowDialog();

        sKey = TextBox1.Text;
        dlg.Filter = "aes files |*.aes";

        dlg.Multiselect = false;
        if (result == true)
        {
            string inputFile = dlg.FileName;

            if (result1 == true)
            {
                string outputFile = dlg1.FileName;
                DecryptFile(inputFile, outputFile);
            }
        }
    }
}


text:
Q: Multiprocessing for calculation on one array This question following this one [1]. I have a big 3D array and i have to do some heavy calculations on it.
I would like to split a slice of my array in 4 parts and do calculations for each part with each 4 cores of my computer...
And do that for each slices of my 3D array...what is the best way to do that?
import numpy

size = 8.
Y=(arange(2000))
X=(arange(2000))
(xx,yy)=meshgrid(X,Y)

array=zeros((Y.shape[0],X.shape[0],size))

array[:,:,0] = 0
array[:,:,1] = X+Y
array[:,:,2] = X*cos(X)+Y*sin(Y)
array[:,:,3] = X**3+sin(X)+X**2+Y**2+sin(Y)

A: You can use Pool from the multiprocessing module:
from multiprocessing import Pool

def f(num):
  return num * 2 # replace with heavy computation

lst = [1,2,3,4,5,6,7,8,9,10,11]
p = Pool(4)
print p.map(f, lst)

It will work equally well with a 3-dimensional numpy array:
from multiprocessing import Pool
import numpy

def f(num):
  return num * 2 # replace with heavy computation

arr = numpy.array(
  [numpy.array([
    numpy.array([1,2,3]),
    numpy.array([4,5,6]),
    numpy.array([7,8,9])]),
   numpy.array([
     numpy.array([1,2,3]),
     numpy.array([4,5,6]),
     numpy.array([7,8,9])])])
p = Pool(4)
print p.map(f, arr)

A: As an alternative to multiprocessing, you can use the concurrent.futures module:
import concurrent.futures

def f(num):
    return num * 2
arr = […]

with concurrent.futures.ProcessPoolExecutor() as exc:
    print(list(exc.map(f, arr)))


text:
Q: diseño de botones flotantes con css El problema radica en el efecto de salida de los botones:

.padre {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 45px;
  height: 45px;
  background:#73AD20;
  border-radius:50%;
  border: 1px solid #73AD21;
  z-index:3;
  text-align: center;
  cursor:pointer;
}
.padre:hover .hijo1{
top:-60px;
display:block;
}
.padre:hover .hijo2{
top:-120px;
display:block;
}
.padre:hover .hijo3{
top:-180px;
display:block;
}
.hijo1{
position: absolute;
top:0;
background:red;
  border-radius:50%;
  border: 1px solid red;
  width: 45px;
  height: 45px;
  display:none;
  -webkit-transition: all 1s;
}
.hijo2{
position: absolute;
top:0;
background:blue;
  border-radius:50%;
  border: 1px solid blue;
  width: 45px;
  height: 45px;
  display:none;
  -webkit-transition: all 2s;
}
.hijo3{
  position: absolute;
  top:0;
  background:orange;
  border-radius:50%;
  border: 1px solid orange;
  width: 45px;
  height: 45px;
  display:none;
  -webkit-transition: all 3s;
}
<!DOCTYPE html>

Posicion fixed;

Los botones deben de salir con un  efecto de uno por uno:

+

2

3

4

Los botones deben de salir 1x1 ademas de poder quedarse ahi para poderlos clickear.
Gracias por su tiempo, quizas sea facil pero es que apenas estoy incursionando en esto de css.

A: lo consegui:

  .cajaf{
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    z-index: 100000;
  }
  .cajaf:hover{
    height: 180px;
  }
  .cajaf:hover .caja1{
    visibility: visible;
    bottom: 60px;
  }
  .cajaf:hover .caja2{
    visibility: visible;
    bottom: 120px;
  }
  .caja2:hover:before{
    visibility: visible;
    color:#000;
  }
  .caja1:hover:before{
    visibility: visible;
    color:#000;
  }
  .btn_roundf{
    position: absolute;
    bottom:0 ;
    right: 0;
    border:1px solid #330000;
    background: #330000;
    color:#ffff00;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    z-index: 90090;
    display: flex;
    align-content: center;
    justify-content: center;
    text-align: center;
    align-items: center;

  }
  .caja1::before{
    content: "Imprimir Comprobante";
    background: #ffd600;
    border:1px solid #ffd600;
    position: absolute;
    left: -140px;
    padding: .5em;
    visibility: hidden;
  }
  .caja2::before{
    content: "Imprimir Contrato";
    background: #283593;
    border:1px solid #283593;
    position: absolute;
    left: -110px;
    padding: .5em;
    visibility: hidden;
  }
  .caja1{
    position: absolute;
    bottom: 0;
    right: 0;
    border:1px solid #ffd600;
    background: #ffd600;
    color: #fff;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    z-index: 90080;
    display: flex;
    align-content: center;
    justify-content: center;
    text-align: center;
    align-items: center;
    -webkit-transition: all .5s;
    visibility: hidden;
  }
  .caja2{
    position: absolute;
    bottom: 0;
    right: 0;
    border:1px solid #283593;
    background: #283593;
    color:#fff;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    z-index: 9070;
    display: flex;
    align-content: center;
    justify-content: center;
    text-align: center;
    align-items: center;
    visibility: hidden;
    -webkit-transition: all 1s;
  }
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">


text:
Q: Is "go to school in" correct? I have read a passage as following:

Most buildings are built for people to live in, work in, or go to school in. But some buildings are built just to hang pictures in. These buildings are called art museums. In all parts of the world, cities and towns have art museums to hang pictures in.
You may think of a picture as a decoration for your house, your school, or your father's office. But sometimes pictures are not just decorations. Sometimes they are famous works of art. And, art museums are places where you can go to see works of art that have been painted by famous artists - some who lived long ago and some who are living today.

I think the sentence should be :
Most buildings are built for people to live in, work in, or study in.
How could "go to school in a building" be right? It's so weird.

A: I suspect that what is confusing you is that you have encountered the phrase go to school only in contexts where go has its ordinary sense of "move from one place to another", such as

I go to school by bicycle.

But American schoolchildren* rarely have occasion to use go to school in this sense. For most Americans going to school has a much broader sense.
The author contrasts go to school with live and work, which have similar senses here. Obviously you work at many places, including (I hope) at school and at home. Work here means "perform an economic role". Equally obviously, you do not restrict your biological existence to your home; you live at work and at school, too, even if those don't seem like much of a life. Live here means "perform a domestic role"—there is an enormous popular literature on achieving "work/life balance".
Similarly, go to school designates one of the major social roles: attending school, performing the role of student.

What is your occupation? ... I go to school.

Consequently, "a building to go to school in" is perfectly ordinary: it means a building where one performs school activities.
Study would not work at all in this context. Aside from the fact that American schools include many activities which have nothing to do with academics, the term is too narrow.  For American schoolchildren intransitive study does not mean to engage in academic activities; it means to cease all other activities and concentrate, by yourself, on your schoolwork. In fact most US secondary schools designate distinct periods during the school day for just such studying; for historical reasons these periods are called study hall.

* The passage was clearly originally written for children: note the reference to "your father's office". The hypercorrective comma after And suggests a US origin to me.

A: It seems fine to me, I've certainly seen "go to school in" in many contexts and I don't see any reason why it is not grammatical.

A: 'Go to school' is equivalent to saying 'go to say and study.'
Over the time, we tend to remove the obvious part. There are many other examples as well.
'Pick up the phone' implies that 'pick up the phone and answer.'
'Go to the bed' means 'go to the bed and sleep.'


text:
Q: how to loop over zillow/realtor using rvest to pull links I am currently using Rvest to try and pull all links from the following url: https://www.zillow.com/browse/homes/fl/miami-dade-county/  The below code satisfies what I am looking to do for one url.
#dl packages
library(tidyverse)
library(rvest)
library(xml2)
library(stringi)
library(dplyr)
library(purrr)
library(stringr)

webpage <- "https://www.zillow.com/browse/homes/fl/miami-dade-county/"
webpage <- read_html(webpage)
url_ <- webpage %>%
html_nodes("a") %>%
html_attr("href")

I am attempting to duplicate this (either a for loop or lapply) for a dataframe (called newurl) full of the same url (zillow.com/browse/homes/fl/ but each ending in a different county).  I have tried both looping and lapplying but receive a different error each time.  I have included my most recent error and code attempt below.  Looking for advice on code to use to satisfy my need or how to edit existing.  Thank you.
I have attempted many different codes but my most recent is below.
bind_rows(lapply(newurl, function(x) {
data.frame(newurl=x, toc_entry=toc <- read_html(newurl[1]) %>%
           html_nodes("a") %>%
           html_attr("href"))
})) -> toc_entries

this produces the following error:
Error in UseMethod("read_xml") :
no applicable method for 'read_xml' applied to an object of class "data.frame"

A: You can try this:
require(tidyverse)
require(rvest)
require(xml2)

start_page <- "https://www.zillow.com/browse/homes/fl/miami-dade-county/"
fl_urls <- start_page %>%
  read_html %>%
  html_nodes("section a") %>%
  html_attr("href") %>% #gives you the link to all ZIP codes
  xml2::url_absolute(start_page) # convert to full URL

name_url <- function(x, base = start_page){
  data_frame(
    name = html_text(x, trim = FALSE),
    url = html_attr(x, "href") %>%
      xml2::url_absolute(base)
  )
}

fl_urls %>%
  head(2) %>% # Only loop the first two entries of fl_urls - remove to loop all
  map(read_html) %>%
  map(html_nodes, "section a") %>%
  map_df(name_url)

What results in
# A tibble: 51 x 2
   name                                 url
   <chr>                                <chr>
 1 1000 Hardee Rd - 1191 S Alhambra Cir https://www.zillow.com/browse/homes/fl/miami-d…
 2 1195 S Alhambra Cir - 1250 S Alhamb… https://www.zillow.com/browse/homes/fl/miami-d…
 3 1250 S Alhambra Cir APT 17 - 1410 C… https://www.zillow.com/browse/homes/fl/miami-d…
 4 1410 Mantua Ave - 1508 Zoreta Ave    https://www.zillow.com/browse/homes/fl/miami-d…
 5 1509 Delgado Ave - 1540 Zuleta Ave   https://www.zillow.com/browse/homes/fl/miami-d…
 6 1541 Cecilia Ave - 3760 Bird Rd UNI… https://www.zillow.com/browse/homes/fl/miami-d…
 7 3760 Bird Rd UNIT 513 - 4100 Salzed… https://www.zillow.com/browse/homes/fl/miami-d…
 8 4100 Salzedo St APT 604 - 420 Vitto… https://www.zillow.com/browse/homes/fl/miami-d…
 9 4210 Anderson Rd - 4420 Anderson Rd  https://www.zillow.com/browse/homes/fl/miami-d…
10 4420 Monserrate St - 4900 Suarez St  https://www.zillow.com/browse/homes/fl/miami-d…
# … with 41 more rows

Hope this helps to understand the logic of looping.


text:
Q: How do I create a form that uploads a file and sets its name to a concatenated string with a variable? I am learning some PHP and am trying to create a form to update an image and set its name to "img".$_POST['something']."jpg", but the result is always img.jpg.
I know $_POST['something'] has a value because I am using it to run a query in the same page.
I spent the whole day (today) trying to figure this out, but I had ran out of ideas by now. Please help.
There might be something wrong with the way I am using msqli_fetch_array (I say that because of the warnings), I have tried to change it but am not sure how.
After a lot of echos through the code, it LOOKS TO ME that when I click submit, part of the page is reloaded with a new $_POST variable, and that is why my postedId vanishes at this point.. Does that make sense? How can I fix it?
<?php
  /* Displays user information and some useful messages */
  require 'db.php';
  session_start();

  // Check if user is logged in using the session variable
  if ($_SESSION['logged_in'] != 1) {
    $_SESSION['message'] = "You must log in before viewing your profile page!";
    header("location: error.php");
  }

  $postedId = $_POST['stid'];

  $result = mysqli_query($mysqli, "SELECT stcontents.id, `st_id`, `name` FROM `students`, `stcontents` WHERE stcontents.tc_id = ".$_SESSION['tcid']." AND students.id = st_id AND st_id = ".$postedId." GROUP BY st_id");

  $row = mysqli_fetch_array($result);
?>

<!doctype html>

      <form action="" method="post" enctype="multipart/form-data">

Image:

        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload Image" name="submit">
      </form>
      <?php
        $target_dir = "resources/images/";
        $target_file = $target_dir."img".$postedId.".jpg";
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        // Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
          $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
          if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
          } else {
            echo "File is not an image.";
            $uploadOk = 0;
          }
        }
        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 500000) {
          echo "Sorry, your file is too large.";
          $uploadOk = 0;
        }
        // Allow certain file formats
        if($imageFileType != "jpg") {
          echo "Sorry, only JPG files are allowed.";
          $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
          echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
        } else {
          if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
          echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
          } else {
            echo "Sorry, there was an error uploading your file.";
          }
        }
      ?>

I was expecting the resulting file name to be something like img6.jpg, not img.jpg as it is. Here are the log I am getting

[19-Jul-2019 23:41:27 UTC] PHP Notice:  Undefined index: fileToUpload
  in /home/[...]/myfolder/myfile.php on line 46 [19-Jul-2019 23:41:27
  UTC] PHP Notice:  Undefined index: fileToUpload in
  /home/[...]/myfolder/myfile.php on line 60 [19-Jul-2019 23:41:33 UTC]
  PHP Notice:  Undefined index: stid in /home/[...]/myfolder/myfile.php
  on line 12 [19-Jul-2019 23:41:33 UTC] PHP Warning:
  mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool
  given in /home/[...]/myfolder/myfile.php on line 16

A: First, I'd like to thank everyone who sent me tips and spent their time reading my code. I have made changes but I still can't make it work as I expect it to.
As I said, with the tips from ArendE, I have changed a lot of things in my code and I think it makes a lot more sense now (I think I can understand it much better too).
One thing I though of changing was to make it more complete and not only giving the option to upload an image but also adding/changing a text and seeing the image if it has already been uploaded.
Unfortunately, something still is not working as I would expect. I will try to explain as I post my code.
Every id variable is a int and the initial $_POST comes from a button in another page.
Top php, here I make the connection and declare some variables:
<?php
/* Displays user information and some useful messages */
session_start();
require 'db.php';

// Check if user is logged in using the session variable
if (empty($_SESSION['logged_in'] != 1) {
    $_SESSION['message'] = "You must log in before viewing your profile page!";
    header("location: error.php");
    exit();
}
else {
    // Makes it easier to read
    $name = $_SESSION['name'];
}

if (isset($_POST['stid'])) {
    $pstid = $_POST['stid'];
    $result = mysqli_query($link, "SELECT `id`, `tc_id`, `name`, `essay`, `image` FROM `students` WHERE tc_id = ".$tcid." AND id = ".$pstid.";");
    $row = mysqli_fetch_array($result);

    $stname = $row['name'];
    $cessay = $row['essay'];
    $cimage = $row['image'];
}
?>

Some html, here I am creating the text field (which already contais text if there are text in the database), show the image if it still exists and give a upload image option to change/add it. If the user changes the text or the image, it will click a save button.
<form method="post" enctype="multipart/form-data">

        Text:
        <textarea type="text" class="form-control" id="TextToUpload" rows="5" name="stessay"><?php echo $cessay; ?></textarea>

Imagem do(a) aluno(a):

    <?php
        if (isset($row['image'])) {
            echo "";
        }

        echo "<input type=\"hidden\" name=\"stid\" value=".$pstid.">";
    ?>
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input formmethod="post" type="submit" value="savechanges" name="submit">
</form>

And bottom php. Here I check if there is text and/or if there is a file selected to update. There are some checking as if the file is corrupt and them I try to send both the information.
<?php
    if(isset($_POST["submit"])) {
        $essayOk = 0;
        $imageOk = 0;

        if(isset($_POST['stessay'])) {
            $essayOk = 1;
            $pessayc = mysqli_real_escape_string($link, $_POST['stessay']);
        }

        if (isset($_POST['fileToUpload'])) {
            $target_dir = "resources/images/";
            $target_file = $target_dir."img".$pstid.".jpg";

            $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
            // Check if image file is a actual image or fake image
            if($mime = finfo_file($finfo, $target_dir . $_FILES["fileToUpload"]["tmp_name"])) {
                if($mime == 'image/jpg' || $mime == 'image/jpeg') {
                    if(getimagesize($target_dir . $_FILES["fileToUpload"]["tmp_name"]) === false) {
                        echo "File is corrupt";
                        $uploadOk = 0;
                    } else {
                        echo "File is an image - " . $mime . ".";
                        $uploadOk = 1;
                    }
                } else {
                    echo $mime . " is not supported.";
                    $uploadOk = 0;
                }
            } else {
                echo "Invalid file";
                $uploadOk = 0;
            }
            // Check file size
            if ($_FILES["fileToUpload"]["size"] > 500000) {
                echo "The file is too big.";
                $imageOk = 0;
            }
            // Check if $imageOk is set to 0 by an error
            if ($imageOk == 0) {
                echo "Erros sending image, try again later.";
            // if everything is ok, try to upload file
            }
        }

        if ($essayOk == 1) {
            $query = "UPDATE students SET essay = '".$pessayc."' WHERE id = '".$pstid."';";
            if (mysqli_query($link, $query)) {
                echo "
Essay updated!
";
            } else {
                printf("Errormessage: %s\n", mysqli_error($link));
                echo "
There was an error updating the ssay, try again later.
";
            }
        }

        if ($imageOk == 1) {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo "The file ".basename($_FILES["fileToUpload"]["name"])." was updated.";
            } else {
                echo "Your image was not updated, try again later.";
            }
        }
    }
?>

I think that the problem is with the bottom php part of the code, for some reason (which I couldn't figure out), it looks like isset($_POST['fileToUpload']) are returning false every time, even when a file is selected. Shouldn't ir come with stessay, stid and submit? This time there is absolutely nothing on the error_log. A print_r of $_POST returns just Array ( [stessay] => Test [stid] => 1 [submit] => savechanges )
Why isn't fileToUpload in there too?

A: As you've spend the whole day on this, let me give you a bunch of pointers. I hope you can learn something from it and understand why those "Undefined" and "Notices" are there. I've not tested the code, but if you go thru all the comments I hope you'll understand and will be able to make it getting to work.
<?php
    // Always start sessions first:
    // if your db.php throws an error, the session can't start anymore
    // and throws a warning
    session_start();

    require('db.php');

    // Do check if a variable exists. PHP should throw you a warning otherwise.

    if(empty($_SESSION['logged_in']) || $_SESSION['logged_in'] != 1) {
        $_SESSION['message'] = "You must log in before viewing your profile page!";
        header("Location: error.php");

        // Stop running the script after a redirect!
        // A header is an instruction, a client
        // might simple ignore it and show the page content anyway
        exit();
    }

    // Check if the variable exists!
    // Long way:
    // if(isset($_POST['stid'])) { $postedId = $_POST['stid'] } else { $postedId = false; }
    // Medium way:
    // $postedId = (isset($_POST['stid']) ? $_POST['stid'] : false;
    // Short way:
    $postedId = $_POST['stid']?:false;

    // Make your query look nice, makes your life easy and debugging too
    // Query questions:
    // 1. What if $_SESSION['tcid'] doesn't exist?
    // 2. What if $postedId doesn't exist?
    // 3. What if $postedId is 0; DROP TABLE students; ?
    // Remember, a client can send anything via $_POST['stid']
    //
    //$qry = "SELECT stcontents.id, `st_id`, `name`
    //      FROM `students`, `stcontents`
    //      WHERE stcontents.tc_id = " . $_SESSION['tcid'] . "
    //      AND students.id = st_id
    //      AND st_id = " . $postedId . " GROUP BY st_id";
    //
    // Read about mysqli_real_escape_string
    // https://www.php.net/manual/en/mysqli.real-escape-string.php
    // Want to do it really right? Use prepared statements
    // https://www.php.net/manual/en/mysqli.prepare.php

    $qry = "SELECT stcontents.id, `st_id`, `name`
            FROM `students`, `stcontents`
            WHERE stcontents.tc_id = " . mysqli_real_escape_string($mysqli, $_SESSION['tcid']) . "
            AND students.id = st_id
            AND st_id = " . mysqli_real_escape_string($mysqli, $postedId) . " GROUP BY st_id";

    $result = mysqli_query($mysqli, $qry);
    $row = mysqli_fetch_array($result);

    // But what if no result was found?
    if(empty($postedId) || empty($row)) {
        exit('Something above went wrong!');
    }
?>
<!doctype html>

            <form method="post" enctype="multipart/form-data">

Image:

                <input type="file" name="fileToUpload" id="fileToUpload">
                <input type="submit" value="Upload Image" name="submit">
            </form>

            <?php
                $target_dir = "resources/images/"; // Better use the full path

                // $target_file = $target_dir."img".$postedId.".jpg";
                // What if $postedId is /../../logo ?
                // Is resources/images/img/../../logo.jpg a valid path?
                //
                // I'll assume $postedId will be an integer (number)
                // using https://www.php.net/manual/en/function.settype.php

                settype($postedId, 'int');

                // Another approach: basename()
                // https://www.php.net/manual/en/function.basename.php
                // https://www.php.net/manual/en/features.file-upload.post-method.php

                $target_file = $target_dir . basename("img" . $postedId . ".jpg");
                $uploadOk = 1;

                // $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
                // You have just made a string $target_file.. so
                // nothing is there, or it would be jpg anyway, since you've said ".jpg"

                if(isset($_POST["submit"])) {

                    // So $_POST['submit'] might be there, but was the fileToUpload too?

                    if(empty($_FILES["fileToUpload"])) {
                        exit('no file!');
                    }

                    // $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
                    //
                    // Well although getimagesize indeed does return false on failure,
                    // read the caution "Do not use to check that a given file is a valid image."
                    // here https://www.php.net/manual/en/function.getimagesize.php
                    // the path it also incomplete ($target_dir is missing)

                    $finfo = finfo_open(FILEINFO_MIME_TYPE);

                    if($mime = finfo_file($finfo, $_FILES["fileToUpload"]["tmp_name"])) {
                        if($mime == 'image/jpg' || $mime == 'image/jpeg') {

                            // Now you could use getimagesize as extra check
                            // But there might be better alternatives
                            if(getimagesize($_FILES["fileToUpload"]["tmp_name"]) === false) {
                                echo "File is corrupt";
                                $uploadOk = 0;
                            } else {
                                echo "File is an image - " . $mime . ".";
                                $uploadOk = 1;
                            }
                        } else {
                            echo $mime . " is not supported.";
                            $uploadOk = 0;
                        }
                    } else {
                        echo "Invalid file";
                        $uploadOk = 0;
                    }

                    if($_FILES["fileToUpload"]["size"] > 500000) {
                        echo "Sorry, your file is too large.";
                        $uploadOk = 0;
                    }

                    // if($imageFileType != "jpg") {
                    //  echo "Sorry, only JPG files are allowed.";
                    //  $uploadOk = 0;
                    // }
                    //
                    // Done this above.
                    // If the idea is some pre-flight check, consider $_FILES['fileToUpload']['type']

                    if($uploadOk == 0) {
                        echo "Sorry, your file was not uploaded.";
                    } else {
                        if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                            echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded.";
                        } else {
                            echo "Sorry, there was an error uploading your file.";
                        }
                    }
                }
            ?>

There can still be a lot of optimization, but this should get you going. Best of luck with it! If you have some questions, feel free to comment.

After your comments, let's do a new round!
Here is the code again:
<?php
session_start();
require 'db.php';

// So empty($var) returns true/false based on if a variable exists (isset()) and it's value
// Read: https://www.php.net/empty what is considered FALSE is it exists
// I'm guessing this will do:
if (empty($_SESSION['logged_in'])) {
    $_SESSION['message'] = "You must log in before viewing your profile page!";
    header("location: error.php");
    exit();
} else {

    // If you are sure $_SESSION['name'] exists if a user is logged in, this is fine.
    // Otherwise consider  $name = $_SESSION['name']?:'unknown';
    $name = $_SESSION['name'];
}

if (isset($_POST['stid'])) {

    // So you still allow a raw POST variable in your database query..
    // Don't do that or you might find someone messed around with your database.
    // https://www.w3schools.com/sql/sql_injection.asp
    // $pstid = $_POST['stid'];

    $pstid = mysqli_real_escape_string($link, $_POST['stid']);
    $tcid = mysqli_real_escape_string($link, $tcid); // Where does $tcid come from? Does it exist?

    // Check if the query is succesful and if there are results..
    // In the function documentation always peek at the Parameters and Return Values
    // https://php.net/manual/en/mysqli.query.php : Returns FALSE on failure.
    // https://www.php.net/manual/en/mysqli-result.fetch-array.php : Returns NULL if there are no more rows

    if($result = mysqli_query($link, "SELECT `id`, `tc_id`, `name`, `essay`, `image` FROM `students` WHERE tc_id = ".$tcid." AND id = ".$pstid.";")) {
        if($row = mysqli_fetch_array($result)) {
            $stname = $row['name'];
            $cessay = $row['essay'];
            $cimage = $row['image'];
        } else {
            $_SESSION['message'] = "No essay was found, please create one first.";
            header("location: error.php");
            exit();
        }
    } else {
        $_SESSION['message'] = "Something went wrong..";
        header("location: error.php");
        exit();
    }

    // What if $_POST['stid'] does not exist though?
    // You use it as hidden input for your form, so let's throw an error.
} else {
    $_SESSION['message'] = "Student id not found.";
    header("location: error.php");
    exit();
}
?>

<form method="post" enctype="multipart/form-data">

        Text:

        <textarea type="text" class="form-control" id="TextToUpload" rows="5" name="stessay"><?php echo $cessay; ?></textarea>

Imagem do(a) aluno(a):

    <?php
        if (isset($row['image'])) {
            // Same applies here, although cimage might be under your control, so less critical
            // Just make it a habbit to escape and you'll never have trouble :)

            $cimage = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
            echo "";
        }

        // So I've used it before in mysqli_real_escape_string, so it now could be something like '123' instead of 123
        // Since we now need to escape it not for SQL but HTML, just use the original value again:

        echo "<input type=\"hidden\" name=\"stid\" value=".htmlspecialchars($_POST['stid'], ENT_QUOTES, 'UTF-8').">";
    ?>
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input formmethod="post" type="submit" value="savechanges" name="submit">
</form>

<?php
    if(isset($_POST["submit"])) {
        $essayOk = 0;
        $imageOk = 0;

        if(isset($_POST['stessay'])) {
            $essayOk = 1;
            $pessayc = mysqli_real_escape_string($link, $_POST['stessay']);
            // Very good! :)
        }

        // Uploaded files should be in the $_FILES array! So don't use $_POST
        if (isset($_FILES['fileToUpload'])) {
            $target_dir = "resources/images/";
            $target_file = $target_dir."img".$pstid.".jpg";

            // $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Not needed, fails anyway
            // But where is $finfo ? The code below will always fail without it..
            // Adding it back:
            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            if($mime = finfo_file($finfo, $_FILES["fileToUpload"]["tmp_name"])) {
                if($mime == 'image/jpg' || $mime == 'image/jpeg') {
                    if(getimagesize($_FILES["fileToUpload"]["tmp_name"]) === false) {
                        echo "File is corrupt";
                        $uploadOk = 0;
                    } else {
                        echo "File is an image - " . $mime . ".";
                        $uploadOk = 1;
                    }
                } else {
                    echo $mime . " is not supported.";
                    $uploadOk = 0;
                }
            } else {
                echo "Invalid file";
                $uploadOk = 0;
            }

            if ($_FILES["fileToUpload"]["size"] > 500000) {
                echo "The file is too big.";
                $imageOk = 0;
            }

            if ($imageOk == 0) {
                echo "Erros sending image, try again later.";
            }
        }

        if ($essayOk == 1) {
            $query = "UPDATE students SET essay = '".$pessayc."' WHERE id = '".$pstid."';";
            if (mysqli_query($link, $query)) {
                echo "
Essay updated!
";
            } else {
                printf("Errormessage: %s\n", mysqli_error($link));
                echo "
There was an error updating the ssay, try again later.
";
            }
        }

        if ($imageOk == 1) {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo "The file ".basename($_FILES["fileToUpload"]["name"])." was updated.";
            } else {
                echo "Your image was not updated, try again later.";
            }
        }
    }
?>

As for your final question, check if it exists in the $_FILES array, but also I believe the filename should still be in the $_POST array. Not sure though. Add this on top of your code to see what variables are found:
print_r($_POST);
print_r($_FILES);

It will give you a nice list of POST fields and uploaded files.


text:
Q: cxfreeze error: script or a list of modules must be specified I am a python noob, so this may be a stupid question, but when I tried to use cxfreeze to export a python script to exe (using python 3.3) I get this:
cxfreeze.py: error: script or a list of modules must be specified
This is the command I was using:
cxfreeze.py script.py --target-dir dist
The script had been copied into the C:\Python33\Scripts directory. What am I doing wrong here?

A: I had a similar command working... then it stopped.  Turns out that adding C:\Cygwin64\bin to my path causes that message to come up and without cx_Freeze works fine.  Note that I do have both Windows and Cygwin Python installs so I assume that my issue is related to conflicting libraries being found.
Note that I am actually calling MinGW Make from a cmd.exe prompt in Windows 7 against a makefile which calls cx_Freeze using Python 3.4.


text:
Q: finding cycles in decimal expansion of rational numbers I need to write a program that prints 0.(03) for input 1 and 33.
(1/33 = 0.03030303.... We use the notation 0.(03) to denote that 03 repeats indefinitely.)
As another example,
8639/70000 = 0.1234(142857)
I understand, I need to use an algorithm like floyds. But how do I get 0.0.030303030303 instead of 0.03030303030304 in java.

A: You can try the following which more robust.
The theory is that all repeating sequences have to be a multiple of
1/9 or 0.(1),
1/99 or 0.(01)
1/999 or 0.(001)
1/9999 or 0.(0001)
etc.

So to find how a fraction is a factor of 9, 99, 999, 9999 etc. Once you know which "nines" your denominator is a factor of, you know how it repeats.
/*
8639/70000 : 0.1234(142857)
1/1: 1.
1/2: 0.5
1/3: 0.(3)
1/4: 0.25
1/5: 0.2
1/6: 0.1(6)
1/7: 0.(142857)
1/8: 0.125
1/9: 0.(1)
1/10: 0.1
1/11: 0.(09)
1/12: 0.08(3)
1/13: 0.(076923)
1/14: 0.0(714285)
 etc
 */
public static final BigInteger NINE = BigInteger.valueOf(9);

public static void main(String... args) {
    System.out.println("8639/70000 : " + repeatingFraction(8639, 70000));
    for (int i = 1; ; i++)
        System.out.println("1/" + i + ": " + repeatingFraction(1, i));
}

private static String repeatingFraction(long num, long den) {
    StringBuilder sb = new StringBuilder();
    sb.append(num / den);
    sb.append('.');
    num %= den;
    for (int i = 3, lim = (int) Math.sqrt(num); i <= lim; i++) {
        while (num % i == 0 && den % i == 0) {
            num /= i;
            den /= i;
        }
    }

    while (num > 0) {
        while (den % 2 == 0 && num % 2 == 0) {
            num /= 2;
            den /= 2;
        }
        while (den % 5 == 0 && num % 5 == 0) {
            num /= 5;
            den /= 5;
        }
        // simplify.
        BigInteger nine = NINE;
        BigInteger denBI = BigInteger.valueOf(den);
        long lim = den;
        while (lim % 2 == 0) lim /= 2;
        while (lim % 5 == 0) lim /= 5;
        for (int j = 1; j <= lim; j++, nine = nine.multiply(BigInteger.TEN).add(NINE)) {
            if (nine.mod(denBI).equals(BigInteger.ZERO)) {
                BigInteger repeat = BigInteger.valueOf(num).multiply(nine).divide(denBI);
                sb.append('(').append(String.format("%0" + j + "d", repeat)).append(')');
                return sb.toString();
            }
        }
        num *= 10;
        sb.append(num / den);
        num %= den;
    }
    return sb.toString();
}

A: To properly detect cycles in the decimal expansion, you ought to avoid floating-point math altogether.
Here is a way to do it using integer arithmetic alone: Algorithm for detecting repeating decimals?

A: With this code, I think you'll find what you're looking for:
BigDecimal one = new BigDecimal(1);

BigDecimal thirtyThree = new BigDecimal(33);

//Fix the decimals you want, i.e. 21
MathContext context = new MathContext(21, RoundingMode.DOWN);

BigDecimal result = one.divide(thirtyThree, context);

System.out.println(result);

This yields the next result:
0.0303030303030303030303

A: By using a BigDecimal with the ROUND_DOWN rounding mode.


text:
Q: Pull to refresh Listview and load in Blackberry I need to implement pull to refresh and load in listview. How could i implement pull to refresh and load in listview in Blackberry using java.
Could anybody help me?

A: override navigationMovement() of Manager of ListField. Then
Field ff = getLeafFieldWithFocus();
        if( ff instanceof ListField ){
            ListField compo = (ListField)ff;
            int index = compo.getSelectedIndex();
            if( index == compo.getSize() - 1 ){
                // POST YOUR LOGIC HERE !!!
            }
        }

EDIT ::
OR
public void drawListRow(ListField lf, Graphics g, int index, int y, int x) {

        if (lf.isFocus() && lf.getSelectedIndex() == index) {
            if(index == (lf.getSize() - 1)){
                //The last row is being focused. Load NEW data here !!!
            }
        }

    }


text:
Q: sending a private message to your friends via Facebook IOS SDK I saw your post about sending messages to your Facebook friends via the IOS Facebook sdk,
I was wondering if there is a way to send a private message as well to these friends.
If not, is sending messages to your Facebook friends still supported from your previous post at:
iOS Development: How can I get a Facebook wall post to show in the friend's news feed?
If so let me know, thank you in advance

A: It is possible to send a private message via facebook- just not with the SDK. You can get the user's 'username' (ie. http://www.facebook.com/username) and you can send them an email via your app to 'username@facebook.com'.
Shapow!
Major bonus: attach a file and it will be included in the facebook message.
One caveat: the email will not reach the recipient's message inbox unless the sender's email address is affiliated with a valid facebook user account. I would imagine this is in place to thwart spam.

A: No, it is not possible to send private messages using the Graph API.
Yes, it is still possible to post to a friend's wall. I just checked it out just now using the graph API Explorer tool:  http://developers.facebook.com/tools/explorer.  I used /friendId/feed with an HTTP post of "message" = "testing" and my friend confirmed they saw it on their stream.

A: let messageDialouge = MessageDialog.init(content: <ShareContent>, delegate: nil)
   if messageDialouge.canShow {
        messageDialouge.show()
    }

And do add fb-messenger-share-api inside the LSApplicationQueriesSchemes in info.plist


text:
Q: "Error setting operation panel" jconsole in a When I connect to JConsole I get the following error message in a pop op box.
Error setting operation panel: and here is one of my class which is a POJO.
I do not know how this POJO can cause this error, and what should I do to get rid of it.

A: If possible, switch to VisualVM (jvisualvm) being part of Java since 1.6 (correct if wrong). In addition, install plugin "MBeans" to get "jconsole" functionality.
Faced same problem as you with plain Pojo classes exposed as MBeans via Spring.
After having switched to VisualVM/MBeans I have not seen this problem any longer. Besides, VisualVM provides you further insights of your running JVM and appears to be extensible via plugins.


text:
Q: In SoftLayer how can i use the API to get a detailed list of all the times a monitoring alarm was triggered? When I use this REST request I only get back the first time the alarm fired. https://api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/{GUEST_ID}/MonitoringActiveAlarms.json with body: {"parameters":["2017-10-31T18:14:00-04:00","2017-11-08T12:54:34-05:00"]}
However in the console UI, I see the alarm with a timestamp similar to the one I get back, but when i drill down into it, I can see all the subsequent times the monitoring alarm reported being beyond the threshold. How can I acquire this info using an API?

A: What you require to do is to use another method, but previously you need to save the "alarmId" value obtained in your REST request posted above, this alarmId property will let you obtain the subsequent alarms, this is obtained trough SoftLayer_Virtual_Guest::getAlarmHistory.
To do what you require just as in the portal UI, use the following REST request:
https://api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/{GUEST_ID}/getAlarmHistory
method POST
 {"parameters":[
                "2000-01-01T18:14:00-04:00",
                 "2017-11-08T12:54:34-05:00",
                 "UH37931229-00012"
                ]
  }


text: Q: change username and password of sql server 2008 default instance I'm not able to use sql server authentication on the default instance.I have seen a lot of web pages and tried adding a new logins by right clicking on logins in security.Secondly changed the password of sa user but i have observed that in status the "SQl Server login is locked out".I have tried all this with admin rights and still not able to login.


text:
Q: Specify default hosts for a task if no roles/hosts were provided I would like to define default host(s) for a specific task in case no roles or hosts were explicitly provided from the command line.
I can use env.all_hosts to check the lists of current hosts is empty, but I don't know how to set it to some host.
I also considered using @hosts(), but it seems to override the input from the command line, which is undesirable.

A: You can override the @hosts decorator from the command line, using the command-line host lists, as described in the first point of Fabric's Order of Precedence:

Order of precedence
We've been pointing out which methods of setting host lists trump the others, as we've gone along. However, to make things clearer, here's a quick breakdown:

*

*Per-task, command-line host lists (fab mytask:host=host1) override absolutely everything else.

*Per-task, decorator-specified host lists (@hosts('host1')) override the env variables.

*Globally specified host lists set in the fabfile (env.hosts = ['host1']) can override such lists set on the command-line, but only if you're not careful (or want them to.)

*Globally specified host lists set on the command-line (--hosts=host1) will initialize the env variables, but that's it.

Give that first option a try, and let us know if you have any other questions.


text:
Q: Windows 7 Start Menu Search is not indexing? I upgraded my Vista Ultimate to Win 7 Professional.
I have configured all the search indexing settings, however search box in the start menu does not bring any result at all in the indexed folders. It says a few thousands of files are indexed but nothing appears in start menu search.
Any ideas?


text:
Q: how can I fix "RuntimeError: generator raised StopIteration" I am trying to run the following code:
def load_scan(path):
    slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
    slices.sort(key = lambda x: int(x.InstanceNumber))
    try:
        slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
    except StopIteration:
        slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)

    for s in slices:
        s.SliceThickness = slice_thickness

    return slices

id=0
patient = load_scan(data_path)

but I'm getting error:

RuntimeError: generator raised StopIteration

I use python 3.7

A: The error is because of a perhaps incompatible version of (py)dicom with python3, in the kaggle kernel, fix is simple:
just switch from dicom, to pydicom e.g
def load_scan(path):
    slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)]
    slices.sort(key = lambda x: float(x.ImagePositionPatient[2]))
    try:
        slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
    except:
        slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
    for s in slices:
        s.SliceThickness = slice_thickness
    return slices

and the following code will work:
train_patient_ids = os.listdir(os.path.join(MAIN_DIR,'train'))
test_patient_ids = os.listdir(os.path.join(MAIN_DIR,'test'))
first_patient = load_scan(os.path.join(MAIN_DIR,'train',train_patient_ids[0]))
first_patient_pixels = get_pixels_hu(first_patient)
plt.hist(first_patient_pixels.flatten(), bins=80, color='c')
plt.xlabel("Hounsfield Units (HU)")
plt.ylabel("Frequency")
plt.show()

plt.imshow(first_patient_pixels[80], cmap=plt.cm.gray)
plt.show()


text:
Q: Screen manager AttributeError: 'super' object has no attribute '__getattr__' I use ScreenManager in project. When I return "Home" class in Main.py it works correctly but ı return "ScreenManager" it get AttributeError.How can ı fix it.
Main.py
from kivy.app import App
from kivy.lang.builder import Builder
from Components.Home.HomeScreen import Home,EachTask
from Components.SM.SM import SM
Builder.load_file("Components/SM/SM.kv")
Builder.load_file("Components/Home/HomeScreen.kv")
class Main(App):
    def build(self):
        return SM()

if  __name__ == "__main__":
    Main().run()

when I return Home() it works but I return SM is not work
HomeScreen.py
class Home(Screen):

def __init__(self,**kwargs):
    super(Home,self).__init__(**kwargs)
    EachTask.Remove_widget = self.remove_widget
    MyPopup.Remove_widget = self.remove_widget_pop
    EachTask.Do_Popup_Task = self.do_popup_task

    for row in database:

        if (row[3]) == True:
            newListItem = EachTask(rgba=[0, .7, .3, 1],
                                   text= row[0] + "    time:    " + row[1],
                                   id=row[2])
            self.ids.add_field.add_widget(newListItem)

        else:

                newListItem = EachTask(text=row[0] + "    time:    " + row[1],
                                       id=row[2])

                self.ids.add_field.add_widget(newListItem)

Error
   self.ids.add_field.add_widget(newListItem)
   File "kivy\properties.pyx", line 863, in
   kivy.properties.ObservableDict.__getattr__
   AttributeError: 'super' object has no attribute '__getattr__'

A: There's nothing much to say without looking at the kv file and the py file.
But, just to check
self.ids.add_field.add_widget(newListItem)

this line would add the newListItem to the Layout which is defined in .kv file.
the id: of the this layout needs to be add_field as well
for example (kv file):
<Home>:
  GridLayout:
     id:add_field
     cols:2


text:
Q: Are there any Chrome extensions that support Google Bookmarks "lists" Are there any Chrome extensions that support Google Bookmarks "lists"? There are plenty of extensions that support regular Google bookmarks such as YAGBE

A: Though jimmy's google bookmakrs does support lists, your YAGBE suggestion seems much cooler (at least today) so I'm not sure what you're looking for.
Anyways, I prefer the much simpler Easy Marks.

A: I guess this may be useful for you,
https://chrome.google.com/webstore/detail/ffmdedmghpoipeldijkdlcckdpempkdi?utm_source=chrome-ntp-icon


text:
Q: Filtering rows on a csv with values that I have on a txt file So I have a csv file where I need to filter the rows based on the values that I have on a txt file. Is there an easy way to do this on pandas? The csv will have about 2000 rows and the txt file has about 400 data points. I need to generate a csv with rows that match the data on the txt file.
The CSV file looks like this:
Chromosome Gene Start End
1 PERM1 5 6
2 AGRN 7 10
3 MIB2 9 12

The Text file looks like
PERM1
NADK
GNB1

Thank you

A: First read Text file into a list or tuple:
lines = tuple(open(filename, 'r'))

Then filter the lines exist in the text file:
df = read_csv('csvfile')
result = df[df['Chromosome Gene'].isin(lines)]

A: easy enough using pandas read and filter functionality. I'm assuming you have an input .csv file called input_csv_file and a filter file called filter.csv. Input file has a column "filter_locatitons" and input_file has a column called "locations":
input_df = pd.read_csv('input_csv_file.csv')
filter_df = pd.read_csv('filter.csv')

filtered_df = input_df[[input_df['location'].isin(filter_df['filter_locations']]

A: This can be achieved using mask and loading both the files in dataframes. Below code assumes your test file does not have a header and your csv file is space delimited
import pandas as pd

df1 = pd.read_csv('csvfile.csv', delimiter=' ')
df2 = pd.read_csv('textfile.txt', header=None)
df2.columns = ['Gene']

m = df1.Gene.isin(df2.Gene)
df3 = df1[m]
print(df3)


text:
Q: Trace class norms of special integral operators Let $\mu$ be a finite compactly supported Borel measure on the real line. On the space $L^2(\mu)$ consider the integral operators
$$
(K_a f)(x)=\int k_a(x, y)f(y)d\mu(y)
$$
with
$$
k_a(x, y)=\frac{a\cdot(x-y)}{|x-y|^2+a^2}, \qquad a>0.
$$
From the representation
$$
k_a(x, y)=\int_{-\infty}^\infty e^{\frac{itx}a}e^{-\frac{ity}a}\ te^{-|t|}\ dt
$$
it follows that the trace class norms of the operators $K_a$ are uniformly bounded. This is a consequence of the fact that the integral operators with kernels $e^{\frac{itx}a}e^{-\frac{ity}a}$ are rank-one operators whose norm is equal to the full mass of $\mu$.
Question. Describe the class of measures $\mu$ for which the trace class norms of the operators $K_a$ tend to 0 as $a\searrow 0$.
Of special interest is the question if this is possible for measures containing a continuous component.


text:
Q: Intelligently scale sprites for different screensizes in Andengine Is there a smart way to scale sprites for different screensizes?
Im testing my game on a 1280*800 screen, however, when i try testing on a 800*480 i would like to scale the sprites so its the same experience but with worse gfx.

A: I haven't worked with AndEngine, but to scale your sprite I think you got 2 options.
One is to scale your resources and have 2 sets of sprites, one for 1280x800 and one for 800x480.
Another way is to draw your sprites relative to the base resolution 800x480 and use a scale factor or 1.6 or somthing like that when you have a bigger resolution. Also set the scale for the sprite accordingly.


text:
Q: How to get data local storage data in json object in emberjs? I am new to emberjs and currently in learning phase.
I have saved form data in localstorage using ember data and localstorage-adapter.
Now I want that data in json object.
Can anyone explain me how to get localstorage data in json object?
I am creating record using following code:
Grid.ModalModel.createRecord({
  fname: fname, lname: lname, email: email,
  contactno: contactno, gendertype: gendertype, contactype: contactype
});
this.get('store').commit();

Data is saved in the browser's localstorage. Now I want that data in a json object in the controller for further use in application.


text:
Q: Gettext will always use system default locale I need to localise a Windows-only PHP web application and I'm evaluating the gettext extension but I'm having the hardest time trying to make it work in my Windows 7 development box. I've used trial and error together with Process Monitor to overcome the poor and inaccurate documentation and I've managed to make _() display strings from the *.po catalogue that corresponds to the computer's default locale (Modern Spanish in my case). All my attempts to set a different locale are silently ignored.
I've written a test script with lots of redundant stuff:

<?php

define('DIR_LOCALE', __DIR__ . DIRECTORY_SEPARATOR . 'locale');
bindtextdomain('general', DIR_LOCALE);
bind_textdomain_codeset('general', 'UTF-8');
textdomain('general');

if(!defined('LC_MESSAGES')){
    define('LC_MESSAGES', 5);
}

$pruebas = array(
    'enu',
    'es_ES',
    'en_GB',
    'english-uk',
    'Spanish_Spain.1252',
    'esn',
    'spanish',
    'spanish-modern',
);
foreach($pruebas as $locale){
    putenv("LC_ALL=$locale");
    setlocale(LC_ALL, $locale);

    putenv("LC_MESSAGES=$locale");
    setlocale(LC_MESSAGES, $locale);

    putenv("LANGUAGE=$locale");
    putenv("LANG=$locale");
?>

<?=htmlspecialchars($locale)?>

<?=_('codigo_idioma')?>

<?php } ?>

In my case, <?=_('codigo_idioma')?> always prints es_ES@modern.
I have PHP/5.4.5 but I'm expecting to get it working in any reasonably up-to-date server our customers own.
I've read lots of vague references about the need to install locales even on Windows but no exact details. What can the problem be?
(I'm aware that the common advice is to dump gettext and use any other library.)

Further testing:
My code run flawlessly as-is in another two computers: 32-bit Windows Vista and 32-bit Windows 7 32-bit. It fails in my computer (64-bit Windows 7) and another one (32-bit Windows Server 2003)

*

*Apache version seems irrelevant (it also happens with the command-line interpreter).

*PHP version seems irrelevant (also tried latest 32-bit PHP/5.5.5 in my PC).

*My [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls] registry tree is identical to the other Seven box.

Edit: While testing on the command-line, I've discovered that setting the LANG environment variable before running the PHP script finally changes the language:
C:\>set LANG=en_GB
C:\>php C:\test\gettext.php

This definitively proves that my computer has the correct assets but also makes me wonder why PHP claims that putenv() works and then ignores it:
var_dump( getenv('LANG'), putenv('LANG=en_GB'), getenv('LANG') );

bool(false)
bool(true)
string(5) "en_GB"

Even this doesn't have any effect:
$_ENV['LANG'] = 'en_GB';
$_SERVER['LANG'] = 'en_GB';

A: It's an issue that's been acknowledged and partially fixed by the PHP team.
It's a fairly technical thing, apparently related to the way environment variables (on which gettext heavily depends) are handled by the underlying platform. Also, something has changed in the Visual C Runtime libraries from VC9 to VC11 that affects all this.
To sum up:

*

*Non thread-safe builds have been fixed in the source tree on 21st Nov. 2014.

*Thread-safe builds (e.g. Apache module) haven't and there isn't a clear solution in sight.

A: The key is to use a Non Thread Safe (=NTS) version of PHP.
Unfortunatelly Windows and PHP does not handle well the environments for threaded processes, so the putenv('LC_ALL='.$locale); command does not work.
Finally I end up with Apache 2.4 + FCGID + PHP 7.1 NTS, which works well now on Windows 7, and it is a non thread safe installation.
A step by step instruction on how to install a such system is here: https://www.youtube.com/watch?v=UXrJPrGaPB0
I have used the VC14 and x64 version for all components (VC is abbreviation for "Microsoft Visual C++ Redistributable"). For this I first installed VC14, downloaded from here: https://www.microsoft.com/en-us/download/details.aspx?id=48145

A: I had same problem with PHP 5.6.30 VC11 Theard Safe on Windows 10. Workaround found and fix this issue here by sirio3mil.
Apparently PHP with TS can access only Locale language folder. So when setlocale and putenv function is call with another language than system's one, folder with .mo and .po cannot be read.
Workaround is to have only one language folder with system language and multiple pairs of .mo/.po files for each translated languages. Domain will be set with wanted language.
Example with Swiss French, German and Italian:
Folder structure

\Locale\fr_CH\LC_MESSAGES

*

*fr_CH.mo + fr_CH.po // system language

*de_CH.mo + de_CH.po

*it_CH.mo + it_CH.po

Code
$lang = 'fr_CH' or 'de_CH' or 'it_CH'

bindtextdomain($lang, '.\Locale');
textdomain($lang);
bind_textdomain_codeset($lang, 'UTF-8');
setlocale (LC_ALL, $lang);
putenv('LC_ALL=' . $lang);

A: On Ubuntu it works if you set your default LC_ALL and leave the LANG and LANGUAGE empty, like so:
LANG=
LANGUAGE=
LC_ALL= "en_US.utf8"

A: First problem: setlocale()
To make this work, you need to set a valid locale. On windows, setlocale() won't work as expected. You need to set an environment variable, like this:
// putenv("LANG=$lang");  <- WRONG!
putenv('LC_ALL='.$locale);

Second problem: locale names.
Windows locale names are different from Linux. Try with 'ita', 'eng', 'deu', 'ger', 'esp'.
You can get a complete list here: http://www.microsoft.com/resources/msdn/goglobal/default.mspx
Example:
//putenv("LANG=esp");  <- WRONG!
putenv('LC_ALL=esp');

Third problem, the big one: gettext extension on windows is not thread safe. Each time you change language, the change is process wide. If you run php as fast-cgi you're ok. If you run php as apache module (for example) it's a total mess because language changes for every php instance. The problem is that gettext() relies on locale setting. This setting is process wide on windows PHP. You cannot change locale for a PHP thread but only for PHP process.
Said this, here is some working code:
// $MAINPATH is your document root

$locales=array(
  'it'=>'ita',
  'en'=>'eng',
  'de'=>'deu',
  'fr'=>'fra',
  'es'=>'esp',
  'ru'=>'rus'
);

$locale = $locales[$lang];
$res=putenv('LC_ALL='.$locale);
$rres=bindtextdomain('default', $MAINPATH.'locale');
$dres=textdomain('default');

locale directory structure must be the following:
deu
  LC_MESSAGES
    default.mo
esp
  LC_MESSAGES
    default.mo
fra
  LC_MESSAGES
    default.mo
ita
  LC_MESSAGES
    default.mo
rus
  LC_MESSAGES
    default.mo

A: Add a system variable 'LANG' with the desired locale for the value (for example 'en_US' or 'nl_NL'), restart apache and translations corresponding to that locale are shown.
Environment variables
This works for XAMPP with php 7.1 (thread safe) on windows 10 and locale directories structured as follows:
    // Directory structure
    <locale_dir>\en_US\LC_MESSAGES\bundle.po
    <locale_dir>\nl_NL\LC_MESSAGES\bundle.po
    ...

A: You must upgrade to PHP 5.6.6 for Windows, it works!


text:
Q: error deserialization dynamic json I have the following Json , which has a dynamic set of values

[   {
      "Type": "Animal"   },   {
       "Profession": "Dog"   } ]

I want to read it into an object
List<List<KeyValuePair<String,String>>>

this works :
var objectList = JsonConvert.DeserializeObject<List<dynamic>>(rawStringJsonData);

but when I try
var objectList = JsonConvert.DeserializeObject<List<List<KeyValuePair<String,String>>>(rawStringJsonData);

I get an error

Additional information: Cannot deserialize the current JSON object
  (e.g. {"name":"value"}) into type

A: You can read it as a List<Dictionary<string,string>> and then cast it to
List<List<KeyValuePair<String,String>>>
Try this:
var rawStringJsonData = "[ { \"Type\": \"Animal\" }, { \"Profession\": \"Dog\" } ]";
var dictList = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(rawStringJsonData);

List<List<KeyValuePair<string,string>>> objectList =
     dictList.Select(i => i.ToList()).ToList();

A: If you use the debugger to inspect the type of your first try, its just deserializing to a list of JTokens, and seeing as that you want a list of key value pairs I'd say that not really anything useful.
The List<List<KeyValuePair<String,String>>> datatype does not match your data.  That would maybe look something like this
[ {"Key": "Type", "Value": "Animal" }, {"Key": "Profession", "Value": "Dog" } ]

In this case I'd probably deserialize to a dictionary instead:
var objectList = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(rawStringJsonData);


text:
Q: Pandas merger multiple rows and columns Hi I have a data frame which goes like this:
index event  action   date
0     event1 action1  date1
1     event2 action2  date1
2     event3 action3  date2
3     event4 action4  date2

I want to merge both columns and row. I have already merged the rows using groupby and lambda function by cannot merge both the rows and columns to get a output to something similar
index  final_actions               date
0      for event1 do action1 and   date1
       for event2 do action2
1      for event3 do action3 and   date2
       for event4 do action4

Thanks for the help in advance

A: try this, groupby + zip
(
    df.groupby('date')['event', 'action']
        .apply(lambda x:
               " and ".join([f"for {x} do {y}"
                             for x, y in zip(x['event'], x['action'])]))
)


text:
Q: Is it possible to always ask user even if already connected using Facebook Javascript SDK I have MVC5 project written in C# and I use Facebook Javascript SDK, I'm wondering if it's possible to always ask user when login using Facebook.
Example scenario:
User A login to my site using Facebook, and he doesn't logout. His session expired from my site but his Facebook will still logged in. User B using same computer to login using Facebook, since user A didn't logout his Facebook, user B will automatically logged in with User A Facebook account, I need something like "Is this your Facebook account?" prompt before letting user login. Is this provided by Facebook? I'm looking around but no luck so far, and 'FB.login' can't be call after 'response.status' is already 'connected'.
my code :
FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                $('#btnFBlogin').click(function () {
                    FB.api('/me', function (response) {

                    location.href = BASE_URL + 'Membership/LogInWithFacebook';
                });
            })
        } else {
            $('#btnFBlogin').click(function () {
                FB.login(function (response) {
                    if (response.status === 'connected') {
                        FB.api('/me', function (response) {
                            location.href = BASE_URL + 'Membership/LogInWithFacebook';
                        });
                    }
                }, { scope: 'email,user_birthday' });
            })
        }
    });

Any help will be appreciated.

A: The flow should be like this:

*

*You should have a customized login button (not the default fb-login button), not sure but I guess you are using the customised button only.

*On its click, check if the user is already connected using FB.getLoginStatus().

*If yes, logout the user from facebook using FB.logout() and then login the user using FB.login()

*If not, login the user using FB.login().

Code
$('#btnFBlogin').click(function () {
     FB.getLoginStatus(function (response) {
          if (response.status === 'connected') {
              FB.logout(function(response) {
                 Login();
              });
          }else{
              Login();
          }
     });
});

function Login(){
    FB.login(function (response) {
       if (response.status === 'connected') {
          FB.api('/me', function (response) {
             location.href = BASE_URL + 'Membership/LogInWithFacebook';
          });
       }
    }, { scope: 'email,user_birthday' });
}


text:
Q: SQL Error: ORA-00933: SQL command not properly ended. When using a simple insert When trying to execute the following command through my ASP.NET application, I get an error

SQL Error: ORA-00933: SQL command not properly ended

The statement is:
INSERT INTO SOMETABLE (GROUPID, USERID, REMOVED)
VALUES ('00000000000000000000000000000000', '00000000000000000000000000000000', 0);

However, if I run the exact same statement directly against the DB using SQL Developer, it works.
All of the articles I've read about this involve statements using additional criteria like order by, join, etc.
My connection strings are correct, and other statements are executing fine.
I'm feeding the statement to the database using this code:
string command = "insert into SOMETABLE (GROUPID, USERID, REMOVED) values ('00000000000000000000000000000000', '00000000000000000000000000000000', 0);";

int result = context.Database.ExecuteSqlCommand(command);

Why is this happening, and how can I fix it?

A: Remove semi-colon, here:
string command = "insert into SOMETABLE (GROUPID, USERID, REMOVED) values
('00000000000000000000000000000000', '00000000000000000000000000000000', 0);";
                                                                           ^
                                                                           |
                                                                        here


text:
Q: How to set Google Voice to show my GV number for incoming calls? I have a Google Voice number linked to my cell phone.  When someone calls my GV number, the caller ID shows as that person's number. I would like to know that the call is coming from Google Voice, and I thought that I could set it so that GV calls show my GV number in the caller ID.
I followed the instructions here, but I wasn't able to find the Caller ID (Incoming) option in either current Call tab or the legacy Phone tab.  Has this option been removed entirely from both the current version and the legacy version?

A: Try the following:

*

*From the "new" Google Voice interface at https://voice.google.com/, open the Settings hamburger menu in the upper left, then choose "Legacy Google Voice" in the sidebar.

*In the legacy interface, choose the settings gear near the upper right, then click Settings.

*Navigate to the Calls tab.

*In the second item down, called "Caller ID (incoming)," change the option to "Display my Google Voice number."

I also couldn't find this setting in the new interface, so I hope they are not removing this toggle!


text:
Q: who to set JAXWS 2.2 client timeout i have simple JAXWS client with dynamic url.
i want to add timeout . but all the eamples i found here , dosn't look like my client.
here is my code :
QName qname = new QName(responseUrl,"sendMessage");
        MyApiService myApiService = new myApiService(newEndpoint,qname);
        myApi port = myApiService.getmyApiPort();

        NPACK nPACK = port.sendMessage(nPMESSAGE);

how do i implement this or this in my client ?

A: ((BindingProvider)port).getRequestContext()...


text:
Q: Keep receiving error: expected primary-expression before ' , ' token I'm kinda new to C++ however, this was a code that was provided to me and I was told to do some edits but very few. I Keep getting the error for two lines of code:
MyFrame() : wxFrame((wxFrame *)NULL, -1,  wxT("wxTimerDemo " + wxDataTime::Now().Format("%c"))
                       , wxPoint(50,50), wxSize(500,300))

and
dc.DrawText(wxT("Testing"), 40, y);

The top one is the only code edited which was followed exactly as it should've.
Full code:

// Render timer - use of a timer
//  http://wiki.wxwidgets.org/Making_a_render_loop
#include <wx/sizer.h>
#include <wx/wx.h>
#include <wx/timer.h>

// prototypes
class BasicDrawPane;
class MyFrame;

// class definitions
class RenderTimer : public wxTimer
{
    BasicDrawPane* pane;
public:
    RenderTimer(BasicDrawPane* pane);
    void Notify();
    void start();
};

#define wxT(x)

class BasicDrawPane : public wxPanel
{

public:
    BasicDrawPane(wxFrame* parent);

    void paintEvent(wxPaintEvent& evt);
    void render( wxDC& dc );

    DECLARE_EVENT_TABLE()
};

class MyApp: public wxApp
{
    bool OnInit();

    MyFrame* frame;
public:

};

RenderTimer::RenderTimer(BasicDrawPane* pane) : wxTimer()
{
    RenderTimer::pane = pane;
}

void RenderTimer::Notify()
{
    pane->Refresh();
}

void RenderTimer::start()
{
    wxTimer::Start(10);
}

IMPLEMENT_APP(MyApp)

class MyFrame : public wxFrame
{
    RenderTimer* timer;
    BasicDrawPane* drawPane;

public:
    MyFrame() : wxFrame((wxFrame *)NULL, -1,  wxT("wxTimerDemo " + wxDataTime::Now().Format("%c"))
                        , wxPoint(50,50), wxSize(500,300))
    {

        drawPane = new BasicDrawPane( this );

        timer = new RenderTimer(drawPane);
        Show();
        timer->start();
    }
    ~MyFrame()
    {
        delete timer;
    }
    void onClose(wxCloseEvent& evt)
    {
        timer->Stop();
        evt.Skip();
    }
    DECLARE_EVENT_TABLE()
};

// event table for MyFrame
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_CLOSE(MyFrame::onClose)
END_EVENT_TABLE()

bool MyApp::OnInit()
{
    frame = new MyFrame();
    frame->Show();

    return true;
}

// event table for BasicDrawPane
BEGIN_EVENT_TABLE(BasicDrawPane, wxPanel)
EVT_PAINT(BasicDrawPane::paintEvent)
END_EVENT_TABLE()

BasicDrawPane::BasicDrawPane(wxFrame* parent) :
wxPanel(parent)
{
}

void BasicDrawPane::paintEvent(wxPaintEvent& evt)
{
    wxPaintDC dc(this);
    render(dc);
}

void BasicDrawPane::render( wxDC& dc )
{
    static int y = 0;
    static int y_speed = 2;

    y += y_speed;
    if(y<0) y_speed = 2;
    if(y>200) y_speed = -2;

    dc.SetBackground( *wxWHITE_BRUSH );
    dc.Clear();
    dc.DrawText(wxT("Testing"), 40, y);
}

Thanks for any help.

A: #define wxT(x) transforms any x to blank.
dc.DrawText(wxT("Testing"), 40, y);  becomes dc.DrawText( , 40, y); and now the error is obvious.
You should define the macro like
#define wxT(x) x

or
#define wxT(x) (x)

Defining the macro wxT is not a good use case, it should be defined when you #include <wx/string.h>, thus #define wxT(x) should be removed from your code. For more information visit #define wxT  ( string ). Note that since wxWidgets 2.9.0 you shouldn't use wxT() anymore in your program sources (it was previously required if you wanted to support Unicode).


text:
Q: How can I use a projection expression for single (non-collection) entities? Using .net-6 and EF Core 6, I want to define reusable projections using expressions so that I can centralize DTO mappings in one place.
Given an entity with relationships:
class Property {
  public int Id {get; set;}
  public List<Amenity> Amenities {get; set;}
  public Address Address {get; set;}
}

class Amenity {
  public int Id {get; set;}
  public string Name {get; set;}
  public string Value {get; set;}
}

class Address {
  public int Id {get; set;}
  public string Country {get; set;}
  public string City {get; set;}
  public string Street {get; set;}
}

And their DTOs:
class PropertyDto {
  public int Id {get; set;}
  public List<AmenityDto> Amenities {get; set;}
  public AddressDto Address {get; set;}
}

class AmenityDto{
  public int Id {get; set;}
  public string Name {get; set;}
  public string Value {get; set;}
}

class AddressDto{
  public int Id {get; set;}
  public string Country {get; set;}
  public string City {get; set;}
  public string Street {get; set;}
}

I can create a reusable projection expression:
public class PropertyDto {
  ...
  public static Expression<Func<Property, PropertyDto>> Projection =
    property => new PropertyDto{
      Id = property.Id,
    };
  ...
}

That I can use in any query's Select() call as the projection expression, which EF will "visit" and translate into SQL to fetch only those columns I need:
DbContext.Set<Property>()
  .Select(Property.Projection)
  .ToListAsync();

If I want to reuse projections for Amenities I can create a Projection expression for AmenityDto and do the following:
public static Expression<Func<Property, PropertyDto>> Projection =
    property => new PropertyDto{
      Id = property.Id,
      Amenities = property.Amenities.AsQueryable().Select(Amenity.Dto).ToList(),
    };

But if I want to do the same for Address I can't use .Select() to project it because it's not a collection.
public static Expression<Func<Property, PropertyDto>> Projection =
    property => new PropertyDto{
      Id = property.Id,
      Amenities = property.Amenities.AsQueryable().Select(Amenity.Dto).ToList(),
      Address = // how can I use AddressDto.Projection here?
    };

The Address field expects an AddressDto. If I use a callback e.g. AddressDto.Projection(address) EF will load the whole entity because it can't translate the method to SQL. After a lot of google I have only come across some articles discussing the use of .AsExpandable() or [ReplaceWithExpression] attribute to instruct EF to replace a method with an expression. As far as I can tell, none of these longer work in EF Core 6.0
Is there any way I can reuse projection expressions when projecting a single entity?

A: Just to answer my own question, and thanks to the comment by @SvyatoslavDanyliv, here is what I did to solve my issue:

*

*I installed LinqKit.Microsoft.EntityFrameworkCore

*I created a method that returns the expression for projecting my domain model to the Dto equivalent:

public static Expression<Func<Address, AddressDto>> Projection() =>
   address => new AddressDto
   {
       Id = address .Id,
       Country = address.Country,
       City = address.City,
       Street = address.Street,
   };

*I created the method that will be called from within other projections, and which LinqKit will replace with the projection expression above.

[Expandable(nameof(Projection))]
public static AddressDto FromEntity(Address address)
{
    // If you want to use this method outside of projections
    // return Projection().Compile().Invoke(address);
    throw new NotImplementedException();
}

I decided to throw new NotImplementedException() because I will only be calling this method from within projections, but if you wish to reuse this method to create DTOs elsewhere in your codebase you can compile & invoke your projection.

*I used the replaceable Dto projection method in my parent EF projections:

...
.Select(property => new PropertyDto{
   Id = property.Id,
   Address = AddressDto.FromEntity(property.Address),
   ...
})
...

The resulting EF SQL properly selects only those columns used by the child Dto.


text:
Q: melt to two variable columns I have the following variables in a data frame:
[1] "Type"   "I.alt"  "idx06"  "idx07"  "idx08" "farve1" "farve2"

If I do:
dm <- melt(d, id=c("Type","I.alt"))

I get these variables:
"Type"     "I.alt"    "variable" "value"

Where "idx06", "idx07",  "idx08", "farve1", "farve2" are represented in "variable".
But what I really want is something like this:
"Type"     "I.alt"    "variable" "value" "variable2" "value2"

Where "farve1" and "farve2" are represented in variable2 and value2.
The reason I want to do this, is that I'd like something where the line color is green if the value is falling and red if rising.
EDIT: Shane has shown how to reshape the data via two melts merged. But my strategy seams to be ill conceived from the beginning - WRONG in one word. See my comment to Shane's solution.
ggplot(dm, aes(x=variable,y=value,group=Type,col=variable2, label=Type,size=I.alt))+
geom_line()+
geom_text(data=subset(dm, variable=="idx08"),hjust=-0.2, size=2.5)+
theme_bw()+
scale_x_discrete(expand=c(0,1))+
opts(legend.position="none")

I assume I need to cast the molten frame - but I can't figure it out.
The data:
d <- structure(list(Type = structure(c(8L, 21L, 23L, 20L, 6L, 14L,
3L, 24L, 2L, 28L, 32L, 22L, 15L, 29L, 1L, 17L, 18L, 33L, 25L,
13L, 30L, 11L, 26L, 9L, 12L, 4L, 5L, 27L, 16L, 19L, 10L, 31L,
7L), .Label = c("Alvorligere vold", "Andre strafferetlige særlove",
"Andre tyverier", "Bedrageri", "Brandstiftelse", "Butikstyverier m.v.",
"Dokumentfalsk", "Færdselslovovertræd. i øvrigt", "Færdselsuheld med spiritus",
"Falsk forklaring i øvrigt", "Forbr. mod off. myndighed m.v.",
"Freds- og ærekrænkelser", "Hæleri", "Hærværk", "Indbrud i bank, forretn. m.v.",
"Indbrud i fritidshuse, garager mv", "Indbrud i villaer, lejligheder mv",
"Love vedr. forsvaret og lign.", "Love vedr. spil, bev., næring",
"Lov om euforiserende stoffer", "Mangler ved køretøj", "Røveri",
"Simpel vold", "Spiritus- og promillekørsel", "Trusler", "Tyv./brugstyv. af andet",
"Tyv./brugstyv. af cykel", "Tyv./brugstyv. af indr. køretøj",
"Tyv/brugstyv. af knallert", "Tyveri fra bil, båd m.v.", "Ulovlig omgang med hittegods",
"Våbenloven", "Vold o.l. mod off. myndighed"), class = "factor"),
I.alt = c(16137L, 9519L, 5930L, 5502L, 4887L, 3582L, 3101L,
1738L, 1660L, 1649L, 1551L, 1412L, 1338L, 1164L, 1154L, 1057L,
931L, 907L, 857L, 724L, 681L, 644L, 641L, 505L, 450L, 419L,
405L, 328L, 324L, 324L, 320L, 281L, 262L), idx06 = c(1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), idx07 = c(0.972675591417568,
0.766866371450899, 0.931743805516597, 0.813047711781889,
0.88728323699422, 0.96420233463035, 0.855743544078362, 1.03710247349823,
0.751470588235294, 0.90443686006826, 0.808403361344538, 0.902834008097166,
0.718181818181818, 0.904555314533623, 1.02717391304348, 0.68957345971564,
1.10324483775811, 0.93030303030303, 0.805309734513274, 0.843003412969283,
0.74914089347079, 0.824786324786325, 1.04060913705584, 1.09150326797386,
0.977941176470588, 0.892405063291139, 0.966666666666667,
0.828125, 0.696, 0.813559322033898, 0.697841726618705, 0.88235294117647,
0.62280701754386), idx08 = c(0.986612873647533, 0.712685595207085,
0.840579710144927, 0.865628042843233, 0.93757225433526, 0.823346303501945,
0.905609973285841, 1.03356890459364, 0.689705882352941, 0.909556313993174,
0.798319327731092, 0.955465587044534, 0.714545454545455,
0.620390455531453, 1.10869565217391, 0.815165876777251, 0.64306784660767,
0.818181818181818, 0.722713864306785, 0.627986348122867,
0.59106529209622, 0.927350427350427, 1.21319796954315, 1.20915032679739,
1.33088235294118, 0.759493670886076, 1.40833333333333, 0.734375,
0.896, 0.932203389830508, 0.60431654676259, 0.872549019607843,
0.675438596491228), farve1 = c("green", "green", "green",
"green", "green", "green", "green", "red", "green", "green",
"green", "green", "green", "green", "red", "green", "red",
"green", "green", "green", "green", "green", "red", "red",
"green", "green", "green", "green", "green", "green", "green",
"green", "green"), farve2 = c("red", "green", "green", "red",
"red", "green", "red", "green", "green", "red", "green",
"red", "green", "green", "red", "red", "green", "green",
"green", "green", "green", "red", "red", "red", "red", "green",
"red", "green", "red", "red", "green", "green", "red")), .Names = c("Type",
"I.alt", "idx06", "idx07", "idx08", "farve1", "farve2"), class = "data.frame", row.names = c(NA, -33L))

A: This doesn't answer your question about cast, but you could certainly subset and do two melts, followed by a merge:
dm1 <- melt(d[,c("Type","I.alt","idx06","idx07","idx08")], id=c("Type","I.alt"))
dm2 <- melt(d[,c("Type","I.alt","farve1","farve2")], id=c("Type","I.alt"))
colnames(dm2) <- c("Type", "I.alt", "variable2", "value2")
dm <- merge(dm1, dm2)

Or, equivalently, do one melt (like you're currently doing) then subset the melted dataframe twice (idx <- variable %in% c("idx06","idx07","idx08") as one and !idx as the other) and merge that output.
Either way you get what you want:
> head(dm)
              Type I.alt variable    value variable2 value2
1 Alvorligere vold  1154    idx08 1.108696    farve1    red
2 Alvorligere vold  1154    idx08 1.108696    farve2    red
3 Alvorligere vold  1154    idx07 1.027174    farve1    red
4 Alvorligere vold  1154    idx07 1.027174    farve2    red
5 Alvorligere vold  1154    idx06 1.000000    farve1    red
6 Alvorligere vold  1154    idx06 1.000000    farve2    red

A: Improvements the melt() function from data.table now makes it possible to perform this operation with a single command by passing a list of variable names to the "measure" argument.
> library(data.table)
>
> a1 = rnorm(4)
> a2 = rnorm(4)
> b1 = rnorm(4)
> b2 = rnorm(4)
> id = 1:4
> dt = data.table(id, a1, a2, b1, b2)
> dt
   id         a1         a2         b1         b2
1:  1 -0.1651639 -0.5361429 -1.0862833  1.0398071
2:  2  0.7829436  0.2047839 -1.1182770  1.3766769
3:  3 -0.7818662 -0.6914946  0.7974077 -0.6887851
4:  4  0.3685140 -0.8519147  0.4316098 -1.4756943
>
> melt(dt, id.vars = 'id', measure.vars = list(c('a1', 'a2'), c('b1', 'b2')),
+      value.name = c('a', 'b'))
   id variable          a          b
1:  1        1 -0.1651639 -1.0862833
2:  2        1  0.7829436 -1.1182770
3:  3        1 -0.7818662  0.7974077
4:  4        1  0.3685140  0.4316098
5:  1        2 -0.5361429  1.0398071
6:  2        2  0.2047839  1.3766769
7:  3        2 -0.6914946 -0.6887851
8:  4        2 -0.8519147 -1.4756943


text:
Q: thrift java server - how to configure threads I've got a following code that starts a thrift java server:
public class Server {

    public static void StartsimpleServer(GameService.Processor<GameServiceHandler> processor) {
        try {
            TServerTransport serverTransport = new TServerSocket(9090);
            TServer server = new TThreadPoolServer(new
              TThreadPoolServer.Args(serverTransport).processor(processor));

            System.out.println("Starting the multi thread server...");
            server.serve();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        StartsimpleServer(new GameService.Processor<>( new GameServiceHandler()));
    }
}

I would like to set the number of maximum threads and other thread-related settings. How can I do that? I couldn't find any documentation concerning that.

A: Is this what you are looking for:
TThreadPoolServer.Args a = new TThreadPoolServer.Args(serverTransport).processor(processor);
a.maxWorkerThreads(5);


text:
Q: Magento2 grid action popup How to popup an action on click of button in adminhtml grid instead of redirecting the page?
I am using custom class (class EmailLogActions extends \Magento\Ui\Component\Listing\Columns\Column)