text:
Q: Error while running flutter app This is the error message which I am getting:
Please do look at it below is my code:
  void main(){
  runApp(HomePage());
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/dotbg.jpg"),
              fit: BoxFit.cover,
            ),
          ),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      'Welcome!',
                      style: TextStyle(
                          fontSize: 30.0,
                          color: Colors.black,
                          fontWeight: FontWeight.bold),
                    ),
                    Container(height: 10.0),
                    RaisedButton(
                        padding: EdgeInsets.symmetric(
                            horizontal: 50.0, vertical: 15.0),
                        textColor: Colors.black,
                        child: Text(
                          'Play Online',
                          style: TextStyle(
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        onPressed: () {
                    },
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50.0))),
                    Container(
                      height: 30.0,
                    ),
                    RaisedButton(
                        padding: EdgeInsets.symmetric(
                            horizontal: 50.0, vertical: 15.0),
                        textColor: Colors.black,
                        child: Text(
                          'Play Offline',
                          style: TextStyle(
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        onPressed: () {
                          Navigator.push(context, MaterialPageRoute(builder:(context)=> OfflinePage()),);
                        },
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50.0))),
                    Container(height: 70.0),
                    Text(
                      'Copyright@2019 DotsNBoxes',
                      style: TextStyle(fontSize: 20.0),
                    ),
                  ],
                ),
              )
            ],
          )),
    );
  }
}

A: This problem is solved by adding MaterialApp :

void main()
runApp(
  MaterialApp(home: HomePage()),
);
}


text:
Q: After ArrayList.add() in a loop, all elements are identical. Why? If I do this [quasi-java-code]:
while (loop)
{
    localObject = getDataForObject();
    globalPublicStaticArrayList<Object>.add(localObject);
}

All the elements in globalPublicStaticArrayList are identical, equal to the last copy of localObject added. I stepped thru the loop in the debugger and saw that as soon as an Object is added, it is copied in to all the elements of the globalPublicStaticArrayList.
The workaround I found is:
while (loop)
{
    localObject = getDataForObject();
    globalPublicStaticArrayList<Object>.add(new Object(localObject.member1, localObject.member2,...));
}

Has it something to do with pass-by-reference in Java? How come the elements are identical in the first case? Thanks.

A: Java uses call by value, but here those values are references to objects.
What you are adding to the list is not a copy of the object, but a copy of the reference. Your method returned the same object each time you called it. It probably should return a new object each time, then you wouldn't need this workaround.

A: globalPublicStaticArrayList<Object>.add(localObject);

here you are passing the localObject reference. You you want a copy of every objects you should create a new object at every iteration

A: In getDataForObject() may be you are not creating "new" object of return type.
Because of that all objects are pointing to same address.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import Access database into SQL Express (Visual Studio) I'm trying to understand how visual studio works with databases but cannot get it figured out.
I have a visual studio project with a built in(.mdf) database that is located in the APP_DATA folder.  I also have an access .accdb file elsewhere on my computer.  What I am trying to do is import it into the mdf database.
I know that mdf file in the APP_DATA corresponds to SQL Express.  However, I am completely confused because it looks like my computer has it's own seperate version of SQL Exprses because there is a separate folder located at
C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA
with its own mdf/ldf files.  Furthermore, when I connect with Navicat, I can connect but see no databases.
How do I interface with the SQL Express instance that runs with my visual studio projects and import data that way?  Thanks!

A: You can use the Upsize to SQL Server option from inside of Access or download the Sql Server Migration Assistant for Access (http://www.microsoft.com/sqlserver/en/us/product-info/migration-tool.aspx#Access) tool.
The final option would be to open up the MDF in Sql Management Studio, and import the data through the TASKS->Import data tool.


text:
Q: Equivalent of End / Response.End in razor? I'm trying to stop the rest of a page loading based on some parameters; but am not sure of the correct syntax.
@if(dayRes + dayTri == 2){<text>Sorry, etc</text> @Response.End}

The above throws this error: CS1502:
The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
Any ideas?

A: Your code tries to print Response.End to the page.
You can just write (in your code block)
return;

to stop running the generated Execute() method.
You can also call End as a method inside of your code block:
Response.End();

A: @if (@Model.Container == null)
{
    <span style="font-weight: bold; ">Container Not Found </span style="font-weight: bold; ">
    return;
}


text:
Q: Using liquibase in java gradle project I added liquibase plugin and consumed liquibase-core,redshift-ext dependencies. I created liquibase.properties.
url="jdbc url" //redshift
username=xxxxx
password=xxxxx
driver=com.amazon.redshift.jdbc.Driver

In my main class I calling the update method like this,
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(
                new JdbcConnection(redShiftConnection));
        Liquibase liquibase = new liquibase.Liquibase("create_table.xml",
                new ClassLoaderResourceAccessor(), database);
        liquibase.update(new Contexts());

this is giving me the following error:
Error getting default schema liquibase.exception.DatabaseException: Error executing SQL select current_schema(): [Amazon][JDBC](11340) Not all output parameters are registered.
What else should I configure ?


text:
Q: How to find the IP address of a specific device from a multicast LAN address? I am trying to program an android app dashboard(latest Java android 5.1 lollipop) that would be able to control my govee lamp which has a LAN control api which connects to a multicast address on my LAN(239.255.255.250) but I need a way to find the IP of the specific lamp so that I can send it commands after user interaction on my app.
Pinged the multicast IP and got no response(operation timed out). Looked around google for a way but couldn't find anything so wondering if someone here could help me out. TY for your time :)

A: Assuming you know the mac address you can send a reverse ARP packet (Reverse Address Resolution Protocol) to obtain the IP address.  ARP itself is normally used to map an IP address to the mac address so the local router can properly forward the packet. RARP does the opposite.
Another way is to interrogate the local ARP cache from within the program on any attached device and see if that has it.  So on a windows OS within the program you can initiate an arp -a in the console window to see the current arp cache.  The only caveat is that the particular value may have time out and been removed.
Here is an example of the latter.
String mac = "1c-7e-81-9e-48-e8";
try {
    Runtime rt = Runtime.getRuntime();
    // send broadcast address
    rt.exec(new String[]{
            "ping","-n 1 -w 200 192.255.255.255"
    });
    // interrogate arp cache
    Process p = rt.exec(new String[]{
            "cmd.exe","/c","arp","-a"
    });

    BufferedReader in = new BufferedReader(
            new java.io.InputStreamReader(p.getInputStream()));
    String line1;
    while ((line1 = in.readLine()) != null) {
        if (line1.contains(mac)) {
            System.out.println(line1);
        }

    }

} catch (Exception e) {
    e.printStackTrace();
}

prints something like
192.168.1.107         1c-7e-81-9e-48-e8     dynamic

The above may need to be adjusted to fulfill your exact requirements.
Of course the easiest way might be to force the issue and assign a static address of your choosing.


text:
Q: What do the PowerPC instructions mtctr and dcbst mean? Can someone please explain to me what the instructions mtctr and dcbst mean Because i have been trying to reverse this mtctr     r4 and dcbst     r0, r3 Please Help.

A: mtctr is the move to count register instruction. It's moving the value in r4 to the count register. Regarding the count register, the PowerPC User Instruction Set Architecture Book 1 says:

The Count Register (CTR) is a 64-bit register. It can be used to hold
  a loop count that can be decremented dur- ing execution of Branch
  instructions that contain an appropriately coded BO field.

So, if you are trying to translate from assembly to C/C++ this instruction could be associated with a for loop or other looping mechanism with a count.
dcbst is the data cache block store instruction. This instruction is used to manage the data cache (versus the instruction cache) of the processor. If the effective address calculated with r0 and r3 specified is in a local data cache of any processor, then it will be written out to storage. It could be part of services provided by an operating system. For more detail, see the PowerPC User Instruction Set Architecture Book 2.


text:
Q: Automate loading data from S3 to Redshift
I want too load data from S3 to Redshift. The data coming to S3 in around 5MB{approximate size} per sec.

I need to automate the loading of data from S3 to Redshift.
The data to S3 is dumping from the kafka-stream consumer application.
The folder S3 data is in folder structure.
Example folder :
bucketName/abc-event/2020/9/15/10
files in this folder :
abc-event-2020-9-15-10-00-01-abxwdhf.  5MB
abc-event-2020-9-15-10-00-02-aasdljc.  5MB
abc-event-2020-9-15-10-00-03-thntsfv.  5MB

the files in S3 have json objects separated with next line.

This data need to be loaded to abc-event table in redshift.

I know few options like AWS Data pipeline, AWS Glue, AWS Lambda Redshift loader (https://aws.amazon.com/blogs/big-data/a-zero-administration-amazon-redshift-database-loader/).
What would be the best way to do it.
Really appreciate if someone will guide me.
Thanks you
=============================================

Thanks Prabhakar for the answer. Need some help in continuation on this.

Created a table in Data Catalog by crawler and
then running a ETLL job in glue does the job of loading the data from S3 to redshift.
I am using approach 1. Predicate pushdown
New files get loaded in S3 in different partition say (new hour started.)
I am adding new partition using a AWS Glue python script job.
Adding new partition in the table using Athena API. (using ALTER TABLE ADD PARTITION).
I have checked in the console that the new partition gets added by the python script job. I checked new partion gets added in Data catalog table.
When I run the same job with pushdown predicate giving same partition added by the python script glue job.
The job did not load the new files from S3 in this new partition to Redshift.
I cant figure out what I am doing wrong ???

A: In your use case you can leverage AWS Glue to load the data periodically into redshift.You can schedule your Glue job using trigger to run every 60 minutes which will calculate to be around 1.8 GB in your case.
This interval can be changed according to your needs and depending on how much data that you want to process each run.
There are couple of approaches you can follow in reading this data :

*

*Predicate pushdown :

This will only load the partitions that mentioned in the job. You can calculate the partition values every run on the fly and pass them to the filter. For this you need to run Glue crawler each run so that the table partitions are updated in the table metadata.
If you don't want to use crawler then you can either use boto3 create_partition or Athena add partition which will be a free operation.

*Job bookmark :

This will load only the latest s3 data that is accumulated from the time that your Glue job completed it's previous run.This approach might not be effective if there is no data generated in S3 in some runs.
Once you calculate the data that is to be read you can simply write it to redshift table every run.
In your case you have files present in sub directories for which you need to enable recurse as shown in below statement.
datasource0 = glueContext.create_dynamic_frame.from_catalog(database =<name>, table_name = <name>, push_down_predicate = "(year=='<2019>' and month=='<06>')", transformation_ctx = "datasource0", additional_options = {"recurse": True})


text:
Q: element cant have z-index maximum when drag in jQuery i have a dragable item but it is under other html element when i drag it, even i set .item_dragable {
    cursor: move;
    z-index: 2147483646;
}
and on event dragable:
jQuerydragable.draggable({
    cancel: "a.ui-icon", // clicking an icon won't initiate dragging
    revert: "invalid", // when not dropped, the item will revert back to its initial position
    containment: "document",
    helper: "clone",
    cursor: "move",
    zIndex: 2147483647
});

what wrong is it? i use the lastest jQuery and jQuery ui
thanks

A: The best way to have your draggable item going over everything else is to use the option appendTo (see jQuery UI doc) and set it to "body" like this :
jQuerydragable.draggable({
    cancel: "a.ui-icon", // clicking an icon won't initiate dragging
    revert: "invalid", // when not dropped, the item will revert back to its initial position
    containment: "document",
    helper: "clone",
    cursor: "move",
    zIndex: 100000,
    appendTo: "body"
});

and of course set a z-index big enough to be higher than all others.


text:
Q: ASP.NET Webforms Module, context user is null When a video request is handled by the HTTP Module (code below) such as /website/uploads/Video/M2U00001_2.mp4 the _context.User is null.
When I run this in VS2010 on my local machine using the Visual Studio Development server _context.User is set. After I deploy to IIS 7 (.net 4.0) _context.User is Null.
'_context.User' is not Null when the http module processes an aspx page but it is Null when processing javascript, images, videos or CSS.
Can anyone explain why _context.User is null and possible solutions that will ensure _context.User is not null.
public Class VideoSecurityModule
    Implements IHttpModule

    Private WithEvents _context As HttpApplication

    Public Sub Dispose() Implements IHttpModule.Dispose

    End Sub

    Dim myUserManager As UserManager

    Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
        _context = context
        myUserManager = New UserManager
    End Sub

    Public Sub OnAuthorizeRequest(ByVal source As Object, ByVal e As EventArgs) Handles _context.PostAuthenticateRequest
        Const networkAuthenticationRequiredStatusCode As Integer = 511
        Try

            If IsVideoUrl() Then

                If _context.User Is Nothing Then
                    LogManager.WriteMessage("_context.User is nothing:", "")
                End If
                Dim userId As Integer = myUserManager.GetUserIdByUserName(_context.User.Identity.Name)
                If (UserRequiresAuthorization(userId)) Then

                    If Not UserIsAssignedToCourseContainingVideo(userId) Then
                        LogAccessDeniedMessage()
                        _context.Response.StatusCode = networkAuthenticationRequiredStatusCode
                        _context.Response.ClearContent()
                        _context.Response.Write("UnAuthorized User")
                        _context.Response.End()
                    End If
                End If
            End If
        Catch ex As Exception
          LogManager.WriteException(ex, "")
        End Try
    End Sub
End Class

A: To ensure that _context.User is set add the runAllManagedModulesForAllRequests="true" to the modules section of the web.config like below.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
  <remove name="ScriptModule" />
  <remove name="RadUploadModule" />
  <remove name="RadCompression" />
  <remove name="VideoSecurityModule" />
  <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode,runtimeVersionv2.0" />
  <add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode,runtimeVersionv2.0" />
  <add name="VideoSecurityModule" type="LMS.VideoSecurityModule"/>
</modules>


text:
Q: open a text file via windows double click with ruby I'm fairly new to Ruby, so please excuse me if my question is too basic...
I wrote a program that searches a text file for certain values.
The way it works is that when I run the program from command line it asks for the file to search through. So I drag the file over to the command window and press Enter. The program takes over and does what it's supposed to... I also created an exe file using Ocra just so I don't have to run it from command line.
It works great, but I want to take it a step further. How can I modify my program to be able to double click the text file in Windows and have my program automatically open and do it's search?


text:
Q: How to use following-sibling xpath query with php? XML:
<Routes>
  <Route type="source" >
   <Table>
     <Tablename>incoming</Tablename>
     <Fields>
       <Fieldsname ref="dest">truegoto</Fieldsname>
     </Fields>
   </Table>
  </Route>
</Routes>

PHP:
$doc    = new SimpleXMLElement('routingConfig.xml', null, true);
$foo = $doc->xpath('/Routes/Route[@type="source"]/Table/Tablename[incoming]/following-sibling::Fields/Fieldsname[@ref="dest"]');
print_r($foo);

Trying  to get truegoto by way of knowing <Tablename>incoming</Tablename>. My current code just returns an empty array : /

A: The problem isn't with the following-sibling part. By that point, you already have no nodes selected. This is because Tablename[incoming] means "Tablename elements that have a child element called incoming". You need Tablename[.="incoming"] instead, which tests the content of the element:
/Routes/Route[@type="source"]/Table/Tablename[.="incoming"]/following-sibling::Fields/Fieldsname[@ref="dest"]

A: Though I'll accept @lonesomeday's answer, here is perhaps an easier to read alternative:
$foo = $doc->xpath('/Routes/Route[@type="source"]/Table[Tablename="incoming"]/Fields/Fieldsname[@ref="dest"]');


text:
Q: Send HEX through visual basic to TCP/IP Port Good day to all, continuing with my frustration, y need a way to send hex values through tcp/ip so i can comunicate with my OBD2 interface. for the explanation i used wire shark, Hercules SETUP utility and obviously my code.
i need to send $B0 to the OBD2 box and the box is connected to the LAN and has specific IP & port for it. so it can answer me back with the Firmware Version $92 04 15 and here are the two scenarios.

Hercules Setup utility
Send B0
Receive 92 04 15
WireShark
PC sent 1 byte = b0
box responded 3 byte = 920415

Visual Basic code
Send B0
Receive     <-- I do not receive nothing
WireShark
PC Sent 2 bytes = 4230
box responded 3 byte = 223442     <-- $22 34 xx means do not understand command so box responds "I do not understand your 42 command

This is the code i'm using
Public Class CLIENT 'client is the forms name

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click 'button1 is the connect button to connect to box
    On Error Resume Next
    Winsock1.Close()
    Winsock1.Connect(TextBox1.Text, 10001) 'I enter the IP of the box here using textbox1 in the form
End Sub

Private Sub Winsock1_ConnectEvent(ByVal sender As Object, ByVal e As System.EventArgs) Handles Winsock1.ConnectEvent
    Me.Text = "Connected to server!"
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click ' this is the send button
    On Error Resume Next
    Me.Winsock1.SendData(TextBox2.Text)      'I send what's in textbox2
    Me.RichTextBox1.Text = "me : " & TextBox2.Text & vbCrLf & Me.RichTextBox1.Text      'on textbox1 i display the commands i send
    Me.TextBox2.Text = ""      'I clear textbox2 after sending the message
End Sub

I still havent figured out how to receive the data and display it on textbox1, im new on visual basic, i only have a day learning to program, so i ask you to be patient if i don't understand the first time you answer something
Thanks

A: Fianlly i could decipher this, remy lebeau you really helped me out, what i did was simply sending like he told me a Byte so a the end this is how it looked like
Me.Winsock1.SendData(&HB0)
and the box responded me back correctly according to the sniffer.. but now im not being able to get the response back displayed
this is the code i implemented.
  Private Sub winsock1_DataArrival(ByVal sender As System.Object, ByVal e As AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent) Handles winsock1.DataArrival
    Dim dat(e.bytesTotal - 1) As Byte '<<< declare a byte array to store the arriving bytes
    winsock1.GetData(dat, vbByte, dat.Length) ' get the data
    'add the new message to our chat buffer
    Dim msg As String = System.Text.Encoding.UTF8.GetString(dat)
    TextBox2.Text = TextBox2.Text & vbNewLine & "OBD2 : " & msg & vbCrLf

A: The WinSock control has a DataArrival event, which you can use to call the control's GetData() method.


text:
Q: Bounds for $a(n)=a(n-1)+a(\lfloor n/2 \rfloor)$ This is related to problem in graph theory.
OEIS defines A033485 as
$a(1)=1$ and $a(n)=a(n-1)+a(\lfloor n/2 \rfloor)$.

Q1 what are upper bounds and asymptotics for $a(n)$, can we get $\exp(o(n))$?

For real $A,0 < A < 1$ define:
$b(0)=b(1)=1$ and $b(n)=b(n-1)+b(\lfloor A n\rfloor)$
If  $A \le \frac12$ then $b(n) \le a(n)$.

Q2 what are upper bounds and asymptotics for $b(n)$?

A: This recurrence was the subject of one of Donald Knuth's earliest papers!   See
https://tensen.net/research/static/logos/number-theory/partitions-restricted/knuth.pdf .

A: Sure, for each fixed $k$ both of them are (up to a constant) eventually dominated by $c(n)=c(n-1)+c(n-k)$ and this sequence is $O(t^n)$ for $t=t(k)\to 1$ as $k\to \infty$ (one has to prove a simple estimate for the roots of $t^k=t^{k-1}+1$).

A: Set $a_k(1)=r_k$ and $a_k(n)=a_k(n-1)+2^k a_k(\lfloor n/2\rfloor)$ for $n\geq 2$
where $r_0=1$ and $r_k=a_{k-1}(2)=(1+2^{k-1})r_{k-1}\leq 2^kr_{k-1}$.
We have $a_0(n)=a(n)$ for $a(n)$ defined by the OP.
An easy induction shows $a_k(2n),a_k(2n+1)\leq a_{k+1}(n)$.
We get thus $$a(n)=a_0(n)\leq a_1(\lfloor n/2\rfloor)\leq a_2(\lfloor n/4\rfloor)\leq \ldots\leq a_{\lfloor \log_2 n\rfloor}(1)=r_{\lfloor \log_2(n)\rfloor}\ .$$
Using $r_k\leq 2^k r_{k-1}\leq 2^{k+(k-1)}r_{k-2}\leq\ldots$, we get finally
$$a(n)\leq 2^{1+2+\ldots+\lfloor\log_2(n)\rfloor}\sim \sqrt{2}^{(\log_2 n)^2}$$
as observed by the OP.

A: Confirming the numerical evidence, the $b(n)$ sequences have rate of growth
$$b(n)=n^{\Theta(\log n)}.$$
On the one hand, since $b(n)$ is nondecreasing, we have
$$\begin{align}b(n)&=b(\lfloor An\rfloor)+b(n-1)\\
&\le2b(\lfloor An\rfloor)+b(n-2)\\
&\le\cdots\\
&\le(n-1)b(\lfloor An\rfloor)+b(1)\\
&\le nb(\lfloor An\rfloor).
\end{align}$$
Since it takes at most $(\log n)/\log A^{-1}$ iterations of $n\mapsto\lfloor An\rfloor$ to get from $n$ down to $1$, we obtain
$$b(n)\le n^{C\log n},\qquad C=(\log A^{-1})^{-1}.$$
On the other hand, we have, say,
$$b(n)\ge\frac n2b(\lfloor An/2\rfloor)$$
by the same argument, which easily yields
$$b(n)=\Omega(n^{c\log n})$$
for any $c<\frac12\log\frac2A$.

A: Philippe Dumas has work deriving very precise asymptotic results for 'divide-and-conquor' sequences such as this. For instance, see 'Asymptotic expansions for linear homogeneous divide-and-conquer recurrences: Algebraic and analytic approaches collated' from 2014 (https://specfun.inria.fr/dumas/Publications/Dumas14.pdf).


text:
Q: How to decide the best form of BMI used in cox regression, categorical or continuous? BMI is always analysed in the form of a categorical variable in medical research. In my Cox regression model, I kept BMI in its original form, i.e., a continuous variable. But the reviewer asked how I can be sure that continuous BMI fits better than categorical BMI. Therefore, I need to test the linearity of BMI. I divided BMI into four sections, but the HRs of BMI in four categories were not significant anymore, while the continuous BMI was statistically significant. Am I in the wrong direction? Are there any better methods to test the linearity of BMI?

A: BMI might be associated continuously with outcome but not necessarily linearly. The best way to test that is to fit BMI as a continuous predictor flexibly, for example with restricted cubic splines as in the rms package in R. If you use the tools in that package, then you can use its anova() function to test the significance of the continuous fit overall and of the non-linear terms in particular.
There is almost never anything to be gained by categorizing a continuous variable. If someone insists that you do it anyway, compare the Akaike Information Criteria (AIC) of the models fit continuously and with categorization. I suspect that the fit will be better with a flexibly fit continuous variable.
One question to consider is whether BMI, itself a derived variable, is useful. It's quite possible that fitting both its components, height and weight, would work better.


text:
Q: Three.js - ply files - why colorless? I am using Three.js's example in the directory:
three.js/examples/webgl_loader_ply.html

And I just swapped their .ply file with mine (made with Blender).
In Blender, I went Vertex Paint > and painted vertices. Before exporting to .ply, I made sure that all checkboxes where checked. And scale is 100.
But the .ply model renders as blue in the three.js's example. (just like the default example). And apparently it is blue because of this code in the example html file:
var geometry = event.content;
var material = new THREE.MeshPhongMaterial( { color: 0x0055ff, specular: 0x111111, shininess: 200 } );
var mesh = new THREE.Mesh( geometry, material );

I was 100% sure that ply files have color values saves as well. But, what am I supposed to do now if that code makes my model blue? Or did I do something wrong in Blender?
I am totally not familiar with Three.js and webGL because I started to learn it just yesterday. Can anyone enlighten me on what is going on and what to do next?

A: i was missing this property vertexColors: THREE.VertexColors.
All was fine with Blender and the code apart from the property. It works as expected now.
Here is how the line of code should look like:
var material = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, shininess: 200, vertexColors: THREE.VertexColors} );


text:
Q: Why is angular motion special? I'm a biochemist, and not a physicist so bear with me if I say something stupid. I do like to read about physics, though and this is one thing I can't wrap my head around.
I was recently reading about Mach's principle, and I realized that I don't understand what is so special about angular motion, and why it can't be considered a sum of a lot (infinite number) of smaller linear motions. If you consider a rotating ball as a whole, it is clearly rotating. But if I zoom in on any infinitesimal particle in the ball, it is not rotating but instead orbiting around the center of the ball. Orbits are well described as linear motion, with acceleration to the center in this case from whatever forces/chemical bonds are holding the ball together. The only particles that you might say are "rotating" are the ones lying exactly on the axis of rotation, but you could also say that these particles are just not moving.
Looking at rotations as an infinite number of orbits, I don't understand why we need to consider angular reference frames. Could a system of physical laws not be written that doesn't consider angular motion as a distinct thing from linear motion? This would seem to be a "simpler" system. Angular motion would be a tool to simplify complex problems rather than a true thing distinct from linear motion.
The only explanation I can think of is that you can't consider infinitesimal particles because they are quantized. Eventually you get to the smallest particle, which may be rotating around its center of mass. Maybe you could call this a "true rotation" but this is an unsatisfying answer to me. It is hard to believe that a large-scale physical concept (like the use of an absolute angular reference frame despite linear reference frames being relative) is dependent on the presence of quantized matter. Maybe its true, though.
Again, I might be horribly misinterpreting something, but it would be great to get an explanation for why we need angular motion to be something special and different from linear motion.


text:
Q: Resizable style left and right arrows I am trying to add 2 circles, left & right, to the resizable div and style them. I added them and it seems ok, but when I try to resize left of right the circles remain unchanged at the same position. The idea was to move circles with the resizable div. Can you help me please?

$("#resizable").resizable({
  containment: "#image-container-step2",
  handles: "e,w"
});
#resizable {
  background: red;
  position: absolute;
  height: 10px;
  width: 200px;
  top: 100px;
  /*left: 100px;*/
}

#resizable .resizers {
  width: 100%;
  height: 100%;
  border: 3px solid #4286f4;
  box-sizing: border-box;
}

#resizable .resizers .resizer {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: white;
  border: 3px solid #4286f4;
  position: absolute;
}

#resizable .resizers .resizer.left {
  left: -5px;
  top: -7px;
  cursor: w-resize;
  /*resizer cursor*/
}

#resizable .resizers .resizer.right {
  left: 190px;
  top: -7px;
  cursor: e-resize;
  /*resizer cursor*/
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" />

A: Instead of giving .resizer.right left: 190px just give it right: -5px. Now if you resize it will be with the line. Hope it helps
Code updated and now it is re-sizable with circles as well

$("#resizable").resizable({
  containment: "#resizable",
  handles: "e,w"
});
#resizable {
  background: red;
  position: absolute;
  height: 10px;
  width: 200px;
  top: 100px;
  /*left: 100px;*/
}

#resizable .resizers {
  width: 100%;
  height: 100%;
  border: 3px solid #4286f4;
  box-sizing: border-box;
}

#resizable .resizers .resizer {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: white;
  border: 3px solid #4286f4;
  position: absolute;
}
#resizable .ui-resizable-handle{
    width: 31px;
    height: 31px;
    top: 50%;
    transform: translateY(-50%);
}
#resizable .resizers .resizer.left,#resizable .resizers .resizer.right{
top:50%;
transform:translateY(-50%);
}
#resizable .resizers .resizer.left {
  left: -5px;
  cursor: w-resize;
  /*resizer cursor*/
}

#resizable .resizers .resizer.right {
  right: -5px;
  cursor: e-resize;
  /*resizer cursor*/
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" />


text:
Q: How do I get a variable in a URL, but when the URL is saved in a PHP variable? $url= "justfwalk.it?uid=12";

How can I get the variable "uid" from this string?
Is there is an easier method than looking for it's position and trimming the string?

A: How about parse_url and parse_str?
<?php
$params = array();
$url= "justfwalk.it?uid=12";
$url_parts = parse_url( $url);
parse_str( $url_parts['query'], $params);
echo $params['uid']; // Outputs 12

See it in action

A: Sure, use parseurl
<?php
$url = 'http://localhost/'.$url;
print_r(parse_url($url));
?>

A: list($html, $get) = explode('?', $url);
$get = explode('=', $get);
print_r($get);

A: $parts = explode("=", $url);
$uid = $parts[1];


text:
Q: Using @Factory and @DataProvider in TestNG with a map to iterator
I want to iterate through the excel sheet and get data using @dataprovider
  Then want the methods to executed in the following pattern using @Factory and @dataProvider the data type the @dataProvider returns is

This is the execution pattern I am looking for
Before Test : 1
testMethod0 : Method 0 data set 1
testMethod1 : Method 1 data set 1
testMethod2 : Method 0 data set 1
After Test : 1

Before Test : 2
testMethod0 : Method 0 data set 2
testMethod1 : Method 1 data set 2
testMethod2 : Method 0 data set 2
After Test : 2
.
.
and so on

Please help me out
This is how my excel sheet looks
+--------------------+--------------------+--------------------+
| Method0Data        | Method0Data        | Method0Data        |
+--------------------+--------------------+--------------------+
|Method 0 data set 1 |Method 1 data set 1 |Method 0 data set 1 |
|Method 0 data set 1 |Method 1 data set 1 |Method 0 data set 1 |
|Method 0 data set 1 |Method 1 data set 1 |Method 0 data set 1 |
+--------------------+--------------------+--------------------+

This is the code that I am working on please have a look into it
package ExecutionPackage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

public class MapPoweredDataProviderSample {

    private static final String FILE = "D:\\Users\\sshafee\\DataSheet\\EnviromentDataSheet.xlsx";
    private static final DataFormatter dataFormatter = new DataFormatter();
    private static final String SHEET_NAME = "Credentials";

    private Map<String, String> iteration;
    private int count=1;

    @Factory(dataProvider = "dp")
    public void getFactoryData(Map<String, String> iteration) {
        this.iteration = iteration;
        System.out.println("New :" + this.iteration);
        System.out.println("Count :" + count++);
    }

    @BeforeTest
    public void beforetest() {
        System.out.println("Before Test : " + count);
    }

    @Test
    public void testMethod0() {
        System.out.println("testMethod0 : " + iteration.get("Method0Data"));
    }

    @Test
    public void testMethod1() {
        System.out.println("testMethod1 : " + iteration.get("Method1Data"));
    }

    @Test
    public void testMethod2() {
        System.out.println("testMethod2 : " + iteration.get("Method2Data"));
    }

    @AfterTest
    public void tearDown() {
        System.out.println("After Test : " + count);
        iteration.clear();
    }

    @DataProvider(name = "dp")
    public Object[][] getData() throws IOException, InvalidFormatException {
        Workbook workbook = WorkbookFactory.create(new File(FILE));
        Sheet sheet = workbook.getSheet(SHEET_NAME);
        Iterable<Row> rows = sheet::rowIterator;
        List<Map<String, String>> results = new ArrayList<>();
        boolean header = true;
        List<String> keys = null;
        for (Row row : rows) {
            List<String> values = getValuesInEachRow(row);
            if (header) {
                header = false;
                keys = values;
                continue;
            }
            results.add(transform(keys, values));
        }
        return asTwoDimensionalArray(results);
    }

    private static Object[][] asTwoDimensionalArray(List<Map<String, String>> interimResults) {
        Object[][] results = new Object[interimResults.size()][1];
        int index = 0;
        for (Map<String, String> interimResult : interimResults) {
            results[index++] = new Object[] { interimResult };
        }
        return results;
    }

    private static Map<String, String> transform(List<String> names, List<String> values) {
        Map<String, String> results = new HashMap<>();
        for (int i = 0; i < names.size(); i++) {
            String key = names.get(i);
            String value = values.get(i);
            results.put(key, value);
        }
        return results;
    }

    private static List<String> getValuesInEachRow(Row row) {
        List<String> data = new ArrayList<>();
        Iterable<Cell> columns = row::cellIterator;
        for (Cell column : columns) {
            data.add(dataFormatter.formatCellValue(column));
        }
        return data;
    }
}

When I execute the above code I get the following error not sure why
[RemoteTestNG] detected TestNG version 7.0.0
org.testng.TestNGException:
ExecutionPackage.MapPoweredDataProviderSample.getFactoryData MUST return [ java.lang.Object[] or org.testng.IInstanceInfo[] ] but returns void
    at org.testng.internal.Utils.checkReturnType(Utils.java:547)
    at org.testng.internal.FactoryMethod.<init>(FactoryMethod.java:89)
    at org.testng.internal.TestNGClassFinder.processFactory(TestNGClassFinder.java:169)
    at org.testng.internal.TestNGClassFinder.processMethod(TestNGClassFinder.java:145)
    at org.testng.internal.TestNGClassFinder.processClass(TestNGClassFinder.java:136)
    at org.testng.internal.TestNGClassFinder.<init>(TestNGClassFinder.java:74)
    at org.testng.TestRunner.initMethods(TestRunner.java:443)
    at org.testng.TestRunner.init(TestRunner.java:342)
    at org.testng.TestRunner.init(TestRunner.java:295)
    at org.testng.TestRunner.<init>(TestRunner.java:226)
    at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
    at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
    at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:679)
    at org.testng.SuiteRunner.init(SuiteRunner.java:196)
    at org.testng.SuiteRunner.<init>(SuiteRunner.java:127)
    at org.testng.TestNG.createSuiteRunner(TestNG.java:1265)
    at org.testng.TestNG.createSuiteRunners(TestNG.java:1244)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1093)
    at org.testng.TestNG.runSuites(TestNG.java:1032)
    at org.testng.TestNG.run(TestNG.java:1000)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

This is my POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>AncestryDNA</groupId>
    <artifactId>testAutomation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>testAutomation</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <build>
        <plugins>
            <plugin>
                <inherited>true</inherited>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>TestNG.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.11.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>[4.1.1,)</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>[4.1.0,)</version>
        </dependency>
    </dependencies>
</project>


text:
Q: Plesk 11 / Cents5, how do IP's on multiple ranges work I have a plesk 11 setup running centos5 and i'm a little confused by something.
On the server I have 2 ips from 2 different ranges. They are public IP's pingable from the outside world and working fine.
To not give out the IP's lets say they were 192.168.1.2 and 192.168.2.2.
On a normal linux setup you would define the ifcfg:ethX file as including both the ranges gateways and broadcast address to make it work.
On a plesk environment in /etc/sysscripts/network-scripts/ I see 2 files:
File: ifcfg-etho0

DEVICE="eth0"
BOOTPROTO="static"
BROADCAST="192.168.1.255"
DNS1="8.8.8.8"
GATEWAY="129.168.1.1"
HWADDR="XXXXXXXXXXXX"
IPADDR="192.168.1.2"
NETMASK="255.255.255.0"
NM_CONTROLLED="yes"
ONBOOT="yes"

and the second file:
ifcfg-eth0:1

DEVICE="eth0:1"
IPADDR="192.168.2.2"
NETMASK="255.255.255.0"

my question is how is traffic getting to the 192.168.2.2 address, no where can i find gateways or broadcasts from that range and yet it's working absolutely fine - any ideas?

A: I suppose that IP address and subnet mask is enough to determine broadcast and discovery gateway, check this article


text:
Q: Using Google Maps: a custom javascript function returning undefined I'm trying to return the variable coord from GetLocation, but it only returns undefined.
Any help appreciated!
var coord = "";
function GetLocation(address) {

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { "address": address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            coord = ParseLocation(results[0].geometry.location);

            // This alert shows the proper coordinates
            alert(coord);
        }
        else{ }

    });

    // this alert is undefined
    alert(coord);
    return coord;
}

function ParseLocation(location) {

    var lat = location.lat().toString().substr(0, 12);
    var lng = location.lng().toString().substr(0, 12);

    return lat+","+lng;
}

A: When you are returning coords from the outer function it is still in fact undefined. The inner function executes later when the asynchronous operation (if it wasn't asynchronous, the API would just give the result to you normally) is done.
Try passing a callback:
function GetLocation(address, cb) {

    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { "address": address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            cb(ParseLocation(results[0].geometry.location));
        }
        else{ }

    });
}

You can then use it like so:
GetLocation( "asd", function(coord){
    alert(coord);
});


text:
Q: AWS CFT Glue add sampling in DynamoDB Target I have so far Glue Crawler defined in Cloud Formation Template as:
Type: AWS::Glue::Crawler
Properties:
  Name: CrawlerName
  DatabaseName: DBName
  Targets:
    DynamoDBTargets:
      - Path: DynamoDBTableName

How I can turn on enable sampling option available in UI Console, but I do not see it in AWS Documentation of CFT

A: I haven't tried this myself, but this might work based on how the aws api for glue is structured
Type: AWS::Glue::Crawler
Properties:
  Name: CrawlerName
  DatabaseName: DBName
  Targets:
    DynamoDBTargets:
      - Path: DynamoDBTableName
      - ScanAll: False

A: Given that the default is to enable sampling you shouldn't have to add anything to the CFN template. I did try "ScanAll: True" to try and disable sampling but the command doesn't seem to be supported.
Property validation failure: [Encountered unsupported properties in {/Targets/DynamoDBTargets/1}: [ScanAll]]


text:
Q: What is the Correct way to pass parameters in function I'm using the following code and calling the function from the page. It is not responding.
add_shortcode('my_ttcode', 'create_my_shortcode');
function create_my_shortcode($key1, $key2){
global $wpdb;
$result = $wpdb -> get_results ( "
    SELECT *
    FROM wp_villageleaderdb
    WHERE VillageID = $key1 AND VillageLeaderPosition = $key2 LIMIT 0, 100
    ", 'ARRAY_N' );
var_dump($result);
//return $result[0][1] . "
";  $data = '';
$i = 0;
foreach( $result as $single_result ){
$data .= $result[$i][1] . "
";
$i++;
}

Instead of $key1 and $key2 if the values are given, it is working ok.
The calling from the wordpress page is
[my_ttcode (V001, Sarpanch)]

What is the correct way?
I have tried but the parameter is not getting passed. here is the code.
 add_shortcode('vill_problems', 'get_villageproblems');
 function get_villageproblems($atts){
 extract(shortcode_atts( array( 'villid' => "V000", ), $atts ));
 global $wpdb;
 $result = $wpdb -> get_results ( "
 SELECT *
 FROM wp_villageleaderdb
 WHERE VillageID = $villid LIMIT 0, 100
 ", 'ARRAY_N' );

 $i = 0;
 foreach( $result as $single_result ){
 $data .= $result[$i][1] . "
"; $i++;
 }
 return $data . "
";
 }

A: The following is problematic in the OP's code snippet:

*

*Missing shortcode_atts() for default attribute handling.

*Incorrectly defining the shortcode's input argument, use instead function create_my_shortcode( $attr = [], $content = null ){ ... }

*Not escaping user input, check e.g. wpdb::prepare(). We want to avoid possible SQL injections.

*Uses hardcoded table prefix, wp_, instead of $wpdb->prefix.

*Fetches all fields with SELECT *. Better to fetch only what's needed.

*Not returning the output from the shortcode's callback.

*Incorrectly setting the shortcode's attributes, should be called from the content with e.g. [my_ttcode  key1="V001" key2="Sarpanch"] but use better descriptive attributes instead of key1 and key2.

*Maybe not using WP_DEBUG, when developing, as there would be PHP notices from eg. not initializing the $data string before appending to it.

*Not indenting the code properly, makes it harder to maintain and understand code projects.

Check e.g. the Codex for more general info on shortcodes.
Hope it helps!


text:
Q: rhel: dnf upgrade at a different location, upgrading a thin client I want to upgrade a running rhel thin client that lives on the server under /opt/posterm/x86_64.  Under here you have all your typical unix files that make up a running linux OS.  For example:
[root@zzxxx repo]# cat /opt/posterm/x86_64/etc/redhat-release
Red Hat Enterprise Linux release 8.4 (Ootpa)

The command I run on the server to upgrade the client is
dnf --installroot=/opt/posterm/x86_64/ --setopt=reposdir=/repo/BaseOS upgrade
Error: There are no enabled repositories in "/repo/BaseOS".

How do I upgrade the client?
my local repos are enabled but this error keeps looking at me.
[root@zzxxx repo]# dnf repolist
repo id                                                                     repo name
repository                                                                  localrepo
rhel_appstream                                                              rhel appstream
[root@zzxxx repo]# ll /repo
total 3722
dr-xr-xr-x. 4 root root    2048 Nov 11 16:23 AppStream
dr-xr-xr-x. 4 root root    2048 Nov 11 16:23 BaseOS
dr-xr-xr-x. 3 root root    2048 Nov 11 16:40 EFI
-r--r--r--. 1 root root    8806 Nov 11 16:16 EULA
-r--r--r--. 1 root root    1437 Nov 11 16:16 extra_files.json
-r--r--r--. 1 root root   18390 Nov 11 16:16 GPL
dr-xr-xr-x. 3 root root    2048 Nov 11 16:41 images
dr-xr-xr-x. 2 root root    2048 Nov 11 16:40 isolinux
-r--r--r--. 1 root root      91 Nov 11 16:16 media.repo
-r--r--r--. 1 root root 3760458 Nov 11 16:16 OL8-RELNOTES8-7.zip
-r--r--r--. 1 root root    3169 Nov 11 16:16 RPM-GPG-KEY
-r--r--r--. 1 root root    3169 Nov 11 16:16 RPM-GPG-KEY-oracle
-r--r--r--. 1 root root    3099 Nov 11 16:48 TRANS.TBL

Thank you!

A: Answer:  once I copied the servers local.repo file to the clients /opt/posterm/x*/etc/yum.repos.d then ran
dnf --installroot=/opt/posterm/x86_64/ upgrade

it upgraded successfully. I did try the --setopt again after I copied the local.repo file into place, but it gave me a similar error so I just removed that option as you can see above.


text:
Q: URL 'encoding' bug with urls containing multiple parens I was trying to comment to Marc Gravel, but the URL I pasted kept getting corrupted.
The URL is http://eval.ironscheme.net/?id=(number->string+(char->integer+%23%5C)+16)
Interestingly, Twitter explodes when given the above URL, thinking it is longer than 140 chars.
As you can see it already goes ape shit...
Another try with encoded URL: http://eval.ironscheme.net/?id=(number-%3Estring+(char-%3Einteger+%23%5C%EE%93%BB)+16)
In comments, the trailing ) gets truncated. (See 3rd comment)
Cheers
Edit:
As Nick Craver noted, the Unicode char is in the PAU, but the bug happens regardless of that.
Example:
http://eval.ironscheme.net/?id=(number-%3Estring+(char-%3Einteger+%23%5Cb)+16)

A: Assuming the only part left here is the part with the parenthesis:
A closing parenthesis at the end is never considered to be part of the link when auto-hyperlinking URLs, because this pattern is way too common:

@Joe Turtles should be allowed to move freely (see http://freedom-of-MOVETO.com).

There may be ways to make that a little smarter, and I'm considering some, but the bottom line is:
Auto-detection of links in free text can only ever work in the 99% case.*
And since it's way more common for a link to be in parentheses than for a link to end with a parenthesis, that's what happens.
By the way, when creating manual links, we allow one level of nested parens to work with the standard case, e.g. Wikipedia or MSDN:

Check [Wikipedia](http://en.wikipedia.org/wiki/Turtle_(disambiguation)) for the different meanings.

Since your example has two levels of parentheses, this wouldn't have worked either, so you'd actually have to URL-encode. Links to URLs containing parentheses has some more on that (note though that that's in the context of full Markdown, not comments).
*We could do worse, though.

A: For posterity, one way that you can fix this by changing the closing paren to be %29.  For example, the following URL will not be detected correctly and will drop the closing paren:

http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/dao/Dao.html#countOf()

Versus this one with %29 instead of the closing paren does work and finds the correct anchor

http://ormlite.com/javadoc/ormlite-core/com/j256/ormlite/dao/Dao.html#countOf(%29


text:
Q: How to call stored procedure from OSB without using JDeveloper JCA adapter I need help on OSB 11g. I want to call stored procedure from OSB. I got so many answers which guide to develop JCA adopter through JDeveloper and configure in OSB. But I dont want to depend on JDeveloper every time. Can anybody suggest me is there any way we can call stored procedure without using JDeveloper JCA adopter.
Please note that its not executing simple sql query, its calling stored procedure.

A: You Can use  fn-bea:execute-sql function in Xquery. within it execute your procedure and assign in variable.

A: If you want to call Stored Procedure and don't want to use JCA, your best bet would be a Java Callout. Write a POJO to execute Stored Procedure.

A: Using java callout is the best option , where you don't have to use jca files, for that matter , J-dev. Bea-execute-sql only works for select queries.


text:
Q: Create and fill an xml document with xmlbeans Some time ago, I was using XmlBeans at work and had to create programmatically an xml from a schema.
Back then, I compiled the schema using XmlBeans and then used some XmlBeans functionality (I cannot recall its name right now) to create a valid xml which had all the optional and required tags and attributes.
I am leaving this question here so maybe someone could help me recall how to do this...
(I also remember using Axis 2 so I am beginning to think that it was probably an Axis2 functionality?)
Thanks a lot, if I remember it I will post it...

A: I found it, it's part of the XmlSampleUtil class in org.apache.xmlbeans.impl.xsd2inst:
// for some xmldocument doc
String s = SampleXmlUtil.createSampleForType(doc.schemaType());


text:
Q: Flutter how to turn off device light programmatically Is there any way of turning device light ON/OFF programmatically in Flutter, any plugin or anything else?

A: You can do with smart switch, which can be made by using Sonoff device Sonoff. then you need to map mqtt server with RestAPI. then you can control the smart switched remotely.


text:
Q: How to process Observable I have one local spring boot application which is hitting another PCF deployed application. The PCF application is giving me list of Student.
I am hitting the same using:
Observable<Response> result = RxObservable.newClient()
  .target(url)
  .request()
  .rx()
  .get();

Now I am not able to get my List<Student> back from result Observable.
Tried lots of approaches but nothing really working i.e. subscribing to result etc etc.

A: So after struggling for few hours below is the solution for now.
Observable observable =  result.map(response -> response.readEntity(List.class));
DeferredResult<ResponseEntity<Response>> deferredResult = new DeferredResult(Duration.ofMillis(10000L).toMillis());
    observable.subscribe((response) -> {
        ResponseEntity<Response> responseData = new ResonseEntity(response, HttpStatus.OK);
        deferredResult.setResult(responseData);
    },  deferredResult::setErrorResult);

Please suggest, if it can be improved.
Thanks


text:
Q: reading stdin in shell #!/bin/sh
#myVar=`date`#case 1
#myVar=`cat /dev/stdin`#case 2
myVar=($(< /dev/stdin)) #case 3
echo $myVar
exit 2

case 1 works
case 2 and 3 don't work.
When I test with either 2 or 3; there is no output and the script never exits
What I eventually require is to read from the stdin written to by the postfix pipe

A: #!/bin/bash
read fred
echo $fred


text:
Q: How to play a song from a specified playlist (Spotify API) I want to play all the songs of a given playlist using the spotify API in python. I have got the access token and the required stuff, but am getting a response of 403, the first method find_songs returns my playlist and it returns a response of 200, but not the second method
class SaveSongs:
def __init__(self):
    self.user_id = spotify_user_id
    self.spotify_token = ""
    self.playlist_id = playlist_id
    self.tracks = ""
    self.new_playlist_id = ""
    self.device_id = "DESKTOP-9UBFPPN"

def find_songs(self):
    print("Finding songs in your playlist...")
    query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
        playlist_id)
    response = requests.get(query,
                            headers={"Content-Type": "application/json",
                                     "Authorization": "Bearer {}".format(self.spotify_token)})
    response_json = response.json()
    print(response)

def call_refresh(self):
    print("Refreshing token")
    refreshCaller = Refresh()
    self.spotify_token = refreshCaller.refresh()
    self.find_songs()

def playSong(self): #issue here
    query = "https://api.spotify.com/v1/me/player/play"
    response = requests.put(query,
                            headers={"Content-Type": "application/json",
                                    "Authorization": "Bearer {}".format(self.spotify_token)}, data={
        "context_uri": "spotify:playlist:7mnkglhHfzZRYFRG72zCMd"
    })

    print(response)

a = SaveSongs()
a.call_refresh()
a.playSong()

Refresh.py:
class Refresh:

def __init__(self):
    self.refresh_token = refresh_token
    self.base_64 = base_64

def refresh(self):

    query = "https://accounts.spotify.com/api/token"

    response = requests.post(query,
                             data={"grant_type": "refresh_token",
                                   "refresh_token": refresh_token},
                             headers={"Authorization": "Basic " + base_64})

    response_json = response.json()
    print(response_json)

    return response_json["access_token"]

a = Refresh()
a.refresh()

cURL command
curl -H "Authorization: Basic " -d grant_type=authorization_code -d code= -d redirect_uri=https%3A%2F%2Fgithub.com%2FRohith-JN https://accounts.spotify.com/api/token

get request to get the code for curl command:
https://accounts.spotify.com/authorize?client_id=&response_type=code&redirect_uri=https%3A%2F%2Fgithub.com%2FRohith-JN&scope=playlist-modify-public%20playlist-modify-private%20user-modify-playback-state

expired access token:
BQDbYxNY8h2Crof2_aE1-Tzgk0fnQ5EHBjenqM1dmExNpmbEaw5Ra548kEM86vSLeZ9XTuHLgRXRxxgLQF1aXcqcpUivuaEBjQSmjRFfeBGazCdVxSZQgCMDR_XRa5PhhrVebE2gYfDQl468BkSEGSGWV5LJ2EOYbWS5fsCTHWt-XtM7TFEDQJw3J43yiYf98pBWggp7CQM_yv31XLjoNe93A-j-rwQEJQ0

A: I believe you are trying to hit this API.
If you check the Authorization Scopes Guide, it states that you need to include the required "scope" while you are requesting the access token.
This is how most Oauth systems work. To access a protected resource, you first get an access token. But you also state that you want to do say, read on a resource XYZ. The access token that you get will have restricted permissions to do just what you wanted to do ( even though you as a user have permissions to a lot of other things ).
Scroll down to the scope that you need, and include this scope while requesting the access token. I believe this can solve your issue.
Well, how did I know how to search for this scope? I looked up the URI you are trying to hit, and looked up the scopes for that URI.

A: I figured out that the problem was not with my code, For some calls such as play/pause, increase or decrease volume require a Spotify premium account.


text:
Q: remove .pdb from the end of a string I have a string which can be any name followed by .pdbor PDB. Is there anyway can I remove the pdb or PDB in the same line of code?

A: Without knowing what you tried to solve your problem, I can only give you some hints :
You should take a look to :

*

*the replace() method

*the os.path.splitext() method

A: Another way that could provide more flexibility is to use a regular expression substitution, e.g:
re.sub(r'\.(pdb|PDB)',
       r'',
       filename);

Or alternatively the (?i) syntax makes the whole regular expression case-insensitive:
re.sub(r'(?i)\.pdb',
       r'',
       filename);


text:
Q: Multiple template files with autoscaling groups and launch configurations with Terraform I have 3 autoscaling groups all using slightly different template files. The difference in the 3 template files I have is, each template file is attaching a different EBS volume upon startup of an instance in the autoscaling group. I am trying to figure out how I can pass in these different template files to each autoscaling group using count. Currently the Terraform code is setup to where one template file resource is using 1 file, but I need it to determine how to select the 2nd and 3rd template files. I've done some research on this Cloudinit Config resource that Terraform has integration with, but am not sure if something like this will help me. Any advice would be appreciated. Below is how my current Terraform code is setup.
Template File
data "template_file" "user_data" {
  count    = "${(var.enable ? 1 : 0) * var.number_of_zones}"
  template = "${file("userdata.sh")}"

  vars {
    node                   = "Node${count.index + 1}"
  }
}

Launch Configuration
resource "aws_launch_configuration" "launch_configuration" {
count = "${(var.enable ? 1 : 0) * var.number_of_zones}"

  name      = "${var.cluster_name}-launch_node_${count.index}"
  key_name  = "${var.key_name2}"
  image_id  = "${lookup(var.amis, "${var.aws_region}.${var.licensee_key == "" && var.licensee == "" ? "enterprise" : "byol"}")}"
  user_data = "${element(data.template_file.user_data.*.rendered, count.index)}"

  security_groups = [
    "${aws_security_group.instance_security_group.id}",
  ]

  instance_type        = "${var.instance_type}"
  iam_instance_profile = "${aws_iam_instance_profile.instance_host_profile.name}"

  ebs_block_device {
    device_name = "/dev/sdf"
    no_device   = true
  }

    lifecycle {
    create_before_destroy = true
  }
}

Userdata script
#!/bin/bash

# Attach the right EBS volume
aws ec2 attach-volume --volume-id vol-xxxxxxxxxxxxxxxxx --instance_id `curl http://169.254.169.254/latest/meta-data/instance-id` --device /dev/sdf

Each userdata script I have mounts a different volume on startup of an instance. Any advice on how I can pass in a different value without creating multiple template_file resource blocks would be helpful. Version of Terraform being used is 0.11.10.

A: You are passing node variable to your user_data template. You can reference it inside the template using interpolation:
#!/bin/bash

# Attach the right EBS volume
aws ec2 attach-volume --volume-id ${node} --instance_id `curl http://169.254.169.254/latest/meta-data/instance-id` --device /dev/sdf


text:
Q: Drawing a dataflow using tikz I'm trying to draw the following dataflow diagram in tikz:

Here is what I got so far:
\documentclass[10pt,a4paper]{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}

\usepackage{tikz}
\usetikzlibrary{decorations.markings,positioning,petri}

\begin{document}
\begin{tikzpicture}[thick,
    node distance=2cm,
    on grid,
    every transition/.style={fill=black,minimum width=.1cm, minimum height=0.9cm},
    every label/.style={black!75}]
    node distance=2cm,
    on grid,
    every transition/.style={fill=black,minimum width=.1cm, minimum height=0.9cm},
    every label/.style={black!75}]
  \node[place, label=above:$n_1$] (n1) {+};
  \node[place, right=of n1, label=above:$n_2$] (n2) {$\times 2$};
  \node[place, right=of n2, label=above:$n_3$] (n3) {+};
  \node[place, below=of n2, label=above:$n_4$] (n4) {+1};
  \node[place, right=of n3, label=above:$n_5$] (n5) {$\Delta(0)$};
  \node[right of=n5] (x) {X};
  \node[below of=n5] (y) {Y};
  \node[left of=n1] (i) {Input};

  \draw[->] (n1) edge (n2.west);
  \draw[->] (n2) edge (n3.west);
  \draw[->, to path={-| (\tikztotarget)}] (n4) edge (n3.south);
  \draw[->] (n3) edge (n5.west);
  \draw[->] (n5) edge (x);
  \draw[->] (n4) edge (y);
  \draw[->] (i) edge (n1.west);
  \draw[->, to path={|- (\tikztotarget)}] (i) edge (n4.west);
\end{tikzpicture}
\end{document}

As you can see, drawing the nodes work fine but I'm having trouble getting the edges right. I want the edges to be angled and also there to be dots so it's clear where the flow branches.
I updated my code with edge drawing commands. I still cannot get the feedback edge right nor do I get dots where the edges branches.

A: Try the following:
%\documentclass[10pt,a4paper]{article}
\documentclass[border=3.141592mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,
                chains,
                decorations.markings,
                positioning,
                shadows, }

\begin{document}
    \begin{tikzpicture}[
node distance = 7mm and 11mm,
  start chain = A going right,
     C/.style = {circle, minimum size=11mm, inner sep=1pt, outer sep=0pt,
                 draw, semithick, fill=gray!30},
   dot/.style = {circle, fill, inner sep=2pt, outer sep = 0pt,
                 node contents={}},
every label/.style = {font=\small\sffamily},
 every path/.style = {-Straight Barb}
                        ]
\coordinate[label=above right:input] (in);
\node (d1) [dot, right=of in];
    \begin{scope}[nodes = {C, on chain=A, join=by ->}]
\node (n1) [C, right=of d1]   {+};  % A-1
\node (n2) [C]   {$\times 2$};
\node (n3) [C]   {+};
\node (n4) [C]   {$\Delta(0)$};     % A-4
    \end{scope}
\node (d2) [dot, right=of A-4];
\coordinate[right=of d2, label=above left:X] (x);
%
\node (A-5) [C, below=of A-2] {+1};
\node (d3)  [dot, at={(A-5 -| A-3)}];
\coordinate[right=of d3, label=above left:Y] (y);
%
\draw   (d2) |- ([yshift=7mm] A-1.north) edge (A-1)
        (in) to (A-1) (d3) edge (A-3)   (A-4) edge (x)
        (A-5) edge (y);
\draw   (d1) |- (A-5);
\end{tikzpicture}
\end{document}

Edit:
Ar adding labels the chain had to be handled different as above: it should be add to C nodes style. Doing this, macro join had to be interrupted because it should not connect last Cnode in code with others. In this case thescope` is not needed anymore.
\documentclass[border=3.141592mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows.meta,
                backgrounds,
                chains,
                positioning}
\makeatletter
\tikzset{suspend join/.code={\def\tikz@after@path{}}}
\makeatother

\begin{document}
    \begin{tikzpicture}[
node distance = 7mm and 11mm,
  start chain = going right,
     C/.style = {circle, minimum size=11mm, inner sep=1pt, outer sep=0pt,
                 draw, semithick, fill=gray!30, drop shadow,
                 on chain, join= by ->},
   dot/.style = {circle, fill, inner sep=2pt, outer sep = 0pt,
                 node contents={}},
every label/.style = {label distance=5pt, inner sep=1pt,
                      font=\small\sffamily, fill=white},
 every path/.style = {-Straight Barb}
                        ]
\coordinate[label=above right:input] (in);
\node (d1) [dot, right=of in];
\node (n1) [C,label=$n_1$,
            right=of d1]    {+};
\node (n2) [C,label=$n_2$]  {$\times 2$};
\node (n3) [C,label=$n_3$]  {+};
\node (n4) [C,label=$n_4$]  {$\Delta(0)$};
\node (d2) [dot, on chain];
\coordinate[on chain,
            label=above left:X] (x);
\node (n5) [C, suspend join,
            below=of n2,
            label=$n_5$]   {+1};
\node (d3) [dot, at={(n5 -| n3)}];
\coordinate[right=of d3, label=above left:Y] (y);
%
\scoped[on background layer]
\draw   (d2) |- ([yshift=7mm] n1.north) edge (n1)
        (in) to (n1) (d3) edge (n3)   (n4) edge (x)
        (n5) edge (y);
\draw   (d1) |- (n5);
    \end{tikzpicture}
\end{document}


text:
Q: Code works with while loop but not with for loop This is leetcode question 502 LEETCODE 502.
I have written similar for loop, inside the main while loop.
The commented for loop generates wrong output and is executed only once, but the while loop below it executes perfectly.
What am i doing wrong ?
class Solution {
public:
    int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital){
        vector<pair<int,int>> v;

        for(int i=0 ; i<profits.size(); i++){
            v.push_back({capital[i],profits[i]});
        }
        sort(v.begin(),v.end());
        priority_queue<int> pq;
        int i=0;

        while(k>=1){
            // for(;i<v.size();i++) {
            //     if(w>=v[i].first)
            //         pq.push(v[i].second);
            // }

            while(i < profits.size() && v[i].first <= w){
                pq.push(v[i].second);
                i++;
            }

            if(! pq.empty()){
                w+=pq.top();
                pq.pop();
            } else
                break;

            k--;
        }

        return w;
    }
};


text:
Q: Understanding result of LEFT OUTER JOIN I have a two tables, table X and table Y
Table X:
A B C
6 8 7
6 6 7
7 8 6

Table Y:
A B D
5 8 7
6 6 7
6 8 6

And when running the code
SELECT * FROM X LEFT OUTER JOIN Y on X.B=Y.B;

It returns a table that has 5 rows.
How does this happen?
EDIT: I understand that this is the answer but I'd just like an explanation. Should have worded better :)

A: First of all LEFT OUTER JOIN is equivalent to LEFT JOIN
As you know,
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.

So in your case,

*

*First row in X matches with 2 rows in Y

*Second row in X matches with 1 row in Y

*Third row in X matches with 2 rows in Y
Thus total 5 rows . Since there is no non matching rows in X , there won't be rows in results with null values.
More here


text:
Q: c# jagged array changes itself I've run into a problem. I created a jagged array (input), then I go through some functions and expected to create another jagged array from it (output). But somehow original array was also changed in that process.
How can I avoid changes in the original array?
double[][] input;
    double[][] output;
    private void button1_Click(object sender, EventArgs e)
    {
        input = new double[][]
        {
            new double[] {0,1,2,3 },
            new double[] {9,8 },
            new double[] {14,5,0 },
            new double[] {2.0,2.3,2.5 }
        };
        output = function(input);
    }
    static double[][] function (double[][] ins)
    {
        double[][] ous = ins;
        int leng = ins.GetLength(0);
        for (int i = 0; i < leng; i++)
        {
            int lung = ins[i].GetLength(0);
            for (int j = 0; j < lung; j++)
                ous[i][j] += 14.4;
        }
        return ous;
    }

A: The problem is that ous variable points to the same array as ins (reference). You should copy it to new array. For example using linq:
static T[][] CopyArray<T>(T[][] source)
{
    return source.Select(s => s.ToArray()).ToArray();
}

And use it:
double[][] ous = CopyArray(ins);


text:
Q: Can't get Algolia Autocomplete to load in Rails 7 app I'm trying to set up my app to have autocomplete options in text fields for my forms. So far, I've been able to successfully seed db and index through the Algolia dashboard. I can see my records are syncing correctly, so I know everything is good on the backend.
I'm now trying to implement the easiest possible way to get autocomplete on the homepage of my app. The page itself is a simple, static page with a basic page controller.
I've followed the setup instructions for autocomplete on github but haven't been able to get it to work. Here's what I currently have set up.
home.html.erb

As far as I'm aware, this should work with no issue. But nothing displays, except the border class. I also tried the yarn install method but it also didn't seem to work.
In application.js,
import "@hotwired/turbo-rails"
import "./controllers"
import { autocomplete } from '@algolia/autocomplete-js';

const autocomplete = autocomplete({
    container: '#autocomplete',
    // ...
  });
//= require jquery
//= require jquery_ujs

But when I keep that in there, as well as the can script on my home page, I get the error: Uncaught SyntaxError: Identifier 'autocomplete' has already been declared so as far as I can tell I've implemented it all correctly. I'm completely stuck here - if anyone has any insight, please let me know!


text:
Q: Searching and manipulating Excel data using JavaScript I have a HTML web form with 5 text inputs and a button calling a JavaScript function. The function as it stands, will open an existing Excel file, find the last populated row, insert a new row below it and put the form values in, one value to each cell. It then saves and exits.
The spreadsheet however has many more than 5 columns, so the function only ever places the data into columns A - E.
function createData(){

    var first = document.getElementById('A').value;
    var second = document.getElementById('B').value;
    var third = document.getElementById('C').value;
    var fourth = document.getElementById('D').value;
    var fifth = document.getElementById('E').value;

    var xlDown = -4121

    var w =new ActiveXObject("Excel.Application");
    w.Visible=true;

    w.Workbooks.Open("file:\\Form.xls");
    objWorksheet = w.Worksheets(1);

    objRange = w.Range("A1");
    objRange.End(xlDown).Activate;
    intNewRow = w.ActiveCell.Row + 1;

    for (i=1; i<10000; i++){
        objWorksheet.Cells(intNewRow, 1) = first;
        objWorksheet.Cells(intNewRow, 2) = second;
        objWorksheet.Cells(intNewRow, 3) = third;
        objWorksheet.Cells(intNewRow, 4) = fourth;
        objWorksheet.Cells(intNewRow, 5) = fifth;
    }
    w.ActiveWorkbook.SaveAs("file:\\Form.xls");
    w.Quit();
              alert("The data has been added to the spreadsheet");
}

What I actually want to do is this:
The spreadsheet may or may not already have data in columns A - G on each row.
I want the function to search column B of the existing sheet for the text value of "first" (as defined above). If found, insert the other 4 values in corresponding cells in columns H-K. If not found then insert all 5 values into a new row "first" in Column B and the rest in column H-K.
I've been messing with this for a long time and can't seem to crack it, though I know it can be done.
Any help would be greatly appreciated!

A: Well it seems I found an answer by trial and error. She aint pretty, but it works. I'll look at optimizing the code as time allows.
function createData(){

var Name = document.getElementById('txtName').value;

var first = document.getElementById('A').value;
var second = document.getElementById('B').value;
var third = document.getElementById('C').value;
var fourth = document.getElementById('D').value;
var fifth = document.getElementById('E').value;
var xlDown = -4121

var w =new ActiveXObject("Excel.Application");
w.Visible=true;
w.Workbooks.Open("file:\\Form.xls");

objWorksheet = w.Worksheets(1);
objRange = w.Range("H3");
objRange.End(xlDown).Activate;
intNewRow = w.ActiveCell.Row + 1;

for (i=4; i<10; i++){
    var a = objWorksheet.Cells(i,2);
    var b = a.Value;
    if(b == Name){
        a.Activate;
        b = w.ActiveCell.Offset(0,6);
        intNew = w.ActiveCell.Row;
        objWorksheet.Cells(intNew, 8) = first
        objWorksheet.Cells(intNew, 9) = second
        objWorksheet.Cells(intNew, 10) = third
        objWorksheet.Cells(intNew, 11) = fourth
        objWorksheet.Cells(intNew, 12) = fifth
    }
    else{
        objWorksheet.Cells(intNewRow, 8) = first
        objWorksheet.Cells(intNewRow, 9) = second
        objWorksheet.Cells(intNewRow, 10) = third
        objWorksheet.Cells(intNewRow, 11) = fourth
        objWorksheet.Cells(intNewRow, 12) = fifth
    }
}
w.ActiveWorkbook.SaveAs("file:\\\\Test.xls");
w.Quit();
}


text:
Q: inputs getting hidden behind image So I had to create this splash page in a very short amount of time.  Its done will all images.. etc. (its crap, i know. but needed to go up and seo isnt important)
Problem is the inputs are placed "absolute" over top of the images and in IE (of course IE!!) the form inputs arent realy clickable.
link: savemoneytampa.com
html:

    <form name="form" method="post" action="#">
        Total Card Sales <input id="total_card_sales" type="text" value="0" />
        Total Deposits Received <input id="total_deposits_received" type="text" value="0" />
        Total Processing Cost <input id="total_processing_cost" type="text" value="0" disabled="disabled" />
        Total Processing Cost <input id="total_processing_cost2" type="text" value="0" disabled="disabled" />
        Total Card Sales <input id="total_card_sales2" type="text" value="0" disabled="disabled" />

    </form>

0%

css:
img { border-collapse: none; display: block; z-index: 1; position: relative;}
body { background: url(bg.png) repeat-x; }
#container { width: 936px; margin: 0 auto; position: relative; z-index: 1;}
form { position: absolute; }
label { display: none; }
input { border: none; background: transparent; width: 145px; height: 22px; font-size: 18px; z-index: 999; }
input#total_card_sales { position: absolute; top: 426px; left: 178px; }
input#total_deposits_received { position: absolute; top: 426px; left: 390px; }
input#total_processing_cost { position: absolute; top: 426px; left: 575px;color: #00395a; }
input#total_processing_cost2 { position: absolute; top: 500px; left: 178px; color: #00395a;}
input#total_card_sales2 { position: absolute; top: 500px; left: 390px; color: #00395a; }
#epr { color: #00395a; font-weight: bold; font-size: 30px; position: absolute; top: 567px; left: 535px; font-family: arial;}

A: set z-index for the form to 2
 form { position: absolute; z-index: 2}

Edit:
Ok, it's not about z-index. IE has a problem with fields that have transparent background. They become partially unclickable (only the side with text is clickable).
To fix it, use this
input { border: none; background-color: transparent; background-image: url('.'); width: 145px; height: 22px; font-size: 18px; z-index: 999; }

The added part is background-image: url('.');.

A: Have you looked into the CSS z-index attribute?


text:
Q: How to change afterwards, the value of a Dialog.AddFieldValue? In Axapta, i can add a field into a dialog with:
Dialog.AddFieldValue
But,Is it possible to change that value afterwards ? Maybe, when a new event is fired ?
I can't find a 'name' for that field!

A: Use the return value of Dialog.addFieldValue:
fld = dialog.addFieldValue(typeId(Counter), 117);

Later you can:
fld.value(118);


text:
Q: What is the best way to check if variable is a function? I have gone through multiple approaches to check if a variable is a function but I can't figure out the advantages and disadvantages, which one to use and why.
Are there any edge cases where my comparison can fail in case of typeof?
1) function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]'; }
2) typeof functionToCheck === 'function'
3) functionToCheck.constructor === Function

A: In a perfect world, all of them should return the same value.

const functionToCheck = () => {};

console.log(isFunction(functionToCheck));
console.log(typeof functionToCheck === 'function');
console.log(functionToCheck.constructor === Function);
console.log(functionToCheck instanceof Function);

function isFunction(functionToCheck){
  return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

In real world, their difference can be significant.

const functionToCheck = () => {};

// Altering `.toString()` function by some third-party code
Object.prototype.toString = function(){
  return '[ABCDEFG]';
}

// Mistake of programmer
functionToCheck.constructor = HTMLElement;

// Having a global scope variable named `Function` by some third-party code
window.Function = class ABC {};

console.log(isFunction(functionToCheck));
console.log(typeof functionToCheck === 'function');
console.log(functionToCheck.constructor === Function);
console.log(functionToCheck instanceof Function);

function isFunction(functionToCheck){
  return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

As you can see, I can freely alter the functions and constructor which in turn alter the results that you expect.
The safest way is to always use typeof to check a function as its result cannot be altered in any way.


text:
Q: How to Address DOM-based XSS from Security Review I have a remoting function on my page that takes a list of contacts, and displays them in on Lightning Design styled page. It works fine, but the final innerHTML statement gets flagged in security review as being a DOM based XSS vulnerability. I can't easily use the JSEncode functions, since I using JS Remoting, so trying to work out what I need to do to make this secure in the eyes of the Security Review team?
EDIT
Based on this post, sounds like I'd need a client side encoder?
function getEmailTargetList () {

  Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.KWAC_CampaignTargetsExtension.getEmailTargets2}',
                sName,
                sAccountName,

            function(result, event){
                if (event.status) {
                  var outputDiv = document.getElementById("contactList");

                  var html = '

';

                  html += '

Action	';
                  html += 'Account name	';
                  html += 'Contact ID

';
                  j$.each( result, function(index, value) {
                      html += '
<button class="slds-button slds-button--neutral slds-m-top--small selectRow" type="button">Select</button>	';
                      html += '' + value.Account.Name + '	';
                      html += '' + value.Id + '
';
                  });
                  html = html + '

';
                  outputDiv.innerHTML = html;

                }
              },
                {escape: false}
            );
}


text:
Q: Is there a way to change Image ( base 64 ) size so it can be uploaded via an axios call? I have a problem with Image size, taken from camera, I want to send some photos to the backend in base64 format, but when I pick an image from my storage ( galery ), it is sent perfectly to the backend, but when I take an image from the camera, it is too large to be uploaded, whe I try to send the base64 in a axios request, the request is just pending and then cancelled for reaching the time limit.
Is there a way to send the base64, but reduced in size, or something ?
This is my saga call to get the image :
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';

export default function* takePhotosFromCamera() {
  try {
    const { status: cameraRollPermission } = yield call(Permissions.askAsync, Permissions.CAMERA_ROLL);
    const { status: cameraPermission } = yield call(Permissions.askAsync, Permissions.CAMERA);
    const permissionsAccepted =
      cameraRollPermission === PERMISSIONS.GRANTED && cameraPermission === PERMISSIONS.GRANTED;

    if (!permissionsAccepted) {
      yield put(permissionAccepted('No'));
      yield cancel();
    }

    const photo = yield call(ImagePicker.launchCameraAsync, {
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      quality: 1,
      base64: true,
    });

    if (photo.cancelled) {
      yield cancel();
    }

    console.log(photo);

    yield put(setPhotosSuccess(result));
  } catch (e) {
    yield null;
  }
}

The console.log shows the correct result, an image with uri, base64, etc ..
I am using expo for my react-native app.
Any help would be much appreciated.

A: Changing the quality option between 0 and 1 will change the size of the photo, and quality of course.
const photo = yield call(ImagePicker.launchCameraAsync, {
  mediaTypes: ImagePicker.MediaTypeOptions.All,
  quality: 0.5, <-- Between 0 and 1
  base64: true,
});

If you want to transfer your photos in base64 format, you probably don't have any other options since base64 does not suit most compression algorithms. See this.
I've used ImagePicker and its compression is not very well. If you don't have to stick with base64, you could try to use another javascript compression on the output image, and send it to your backend as form data.


text:
Q: MailboxProcessor.PostAndReply design choice Looking at:
member this.PostAndReply : (AsyncReplyChannel<'Reply> -> 'Msg) * ?int -> 'Reply

I can't figure out why the signature looks so counter-intuitive to me. What we want to do is posting a message to an agent, and wait for a reply.
Why do we have to give him a weird function as a 'message'?
See again this MSDN snippet:
let rec loop() =
    printf "> "
    let input = Console.ReadLine()
    printThreadId("Console loop")
    let reply = agent.PostAndReply(fun replyChannel -> input, replyChannel)
    if (reply <> "Stopping.") then
        printfn "Reply: %s" reply
       loop()
    else
        ()
loop()

I'd rather prefer something like this:
member this.PostAndReply : 'Msg * ?int -> 'Reply

Thanks

A: This type signature looks pretty confusing when you see it for the first time, but it does make sense.
The F# library design
The idea behind the is that when you call PostAndReply you need to give it a function that:

*

*constructs a message of type 'Msg (to be sent to the agent)

*after the F# runtime builds a channel for sending messages back to the caller (channels are represented as values of type AsyncReplyChannel<'Reply>).

The message that you construct needs to contain the reply channel, but the F# library does not know how you want to represent your messages (and so it does not know how you want to store the reply channel in the message). As a result, the library asks you to write a function that will construct the message for the agent after the system constructs the channel.
Your alternative suggestion
The problem with your suggestion is that if PostAndReply had a type 'Msg -> 'Reply, the message that the agent receives after it calls Receive would be of the following type:
'Msg * AsyncReplyChannel<'Reply>

... so every message received to the agent would also have to carry a channel for sending replies back. However, you probably don't want to send a reply back for every received message, so this wouldn't really work. Maybe you could use something like:
'Msg * option<AsyncReplyChannel<'Reply>>

... but that's just getting more complicated (and it still isn't quite right, because you can only reply to some messages from 'Msg, but not to all of them).


text:
Q: Android 4.0+ tablet keyword? I heard that there is a keyword or method that Android developers can use to determine whether  Android 4.0+ is running on a tablet (without having to do any kludgy screen size comparisons). I can't find it.
So, is this true? If so, what is it?
Edit: I see that people are giving me answers that are not what I'm looking for. I already know how to determine whether a device is a tablet or phone using the kludgy screen size method and using the OS method. I'm looking for a method that has been available starting with API level 14 that will tell me the same information -- hopefully. I can't find it, so I'm wondering whether it even exists.

A: Tablet basically just means a big(er) screen, so it comes down to that.  There's an easy way of seeing if it's a tablet sized screen or not:
if ( getResources().getConfiguration().isLayoutSizeAtLeast( Configuration.SCREENLAYOUT_SIZE_XLARGE ) )
{
    //Is a tablet.
}

You could change Configuration.SCREENLAYOUT_SIZE_XLARGE to Configuration.SCREENLAYOUT_SIZE_LARGE if you want to catch smaller ones too.

A: As described in the android documentation, the SDK level (integer) the phone is running is available in:
android.os.Build.VERSION.SDK_INT;
The enum corresponding to this int is in the android.os.Build.VERSION_CODES class.
Code example:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.FROYO){
    // Do something for froyo and above versions
} else{
    // do something for phones running an SDK before froyo
}

Edit: This SDK_INT is available since Donut (android 1.6 / API4) so make sure your application is not retro-compatible with Cupcake (android 1.5 / API3) when you use it or your application will crash (thanks to Programmer Bruce for the precision).
Link

A: Android 4+ has the configuration object. You can use the "isLayoutSizeAtLeast(int size)" method to do your check. It's less kludgy than some other examples I've seen around.


text:
Q: Struts2 file upload max size I need to upload files upto 10 MB.I used the following  .In my struts.xml i configured like as follows.

<action name="doUpload" class="com.example.UploadAction">
<interceptor-ref name="fileUpload">
    <param name="maximumSize">20971520</param>
</interceptor-ref>
</action>

I did not configured any where other than this.I am getting the following error.
the request was rejected because its size (2102840) exceeds the configured maximum (2097152)
Can any one suggest me what might be the reason.Thanks in advance.

A: Put this in your struts.xml file
<constant name="struts.multipart.maxSize" value="30000000" />

See http://struts.apache.org/2.x/docs/file-upload.html#FileUpload-AdvancedConfiguration.
Updated link -
https://struts.apache.org/core-developers/file-upload.html#file-size-limits

A: Also check your container configuration. Tomcat itself, for example, has a maxPostSize parameter which, if not set defaults to 2097152 (2Mb)

A: put this code on your strtus.xml:
<constant name="struts.multipart.maxSize" value="50000000" />

where value denotes your file size limit . if you want to extend the limit you can change the value as well . hope it helps


text:
Q: Separating lists into a new dataframe I have a dataframe with one column that contains lists of lists. All the basic lists contain two strings. The lists that contain these basic lists have a variable amount of lists in them.
example:
            A
    0 [[1,1],[1,1]]
    1 [[1,1]]
    2 [[1,1],[1,1],[1,1]]

I want a new dataframe that has two columns. The first has the first item in each basic list, the second column has the second item. I solved it this way:
df = pd.DataFrame(data = {'A': [[[1,1],[1,1]], [[1,1]], [[1,1],[1,1],[1,1]]]})

df2 = pd.DataFrame(columns = ['A', 'B'])
for x in df.A:
    for i in x:
        n = pd.DataFrame([i], columns = ('A', 'B'))
        df2 = df2.append(n)

   A  B
0  1  1
0  1  1
0  1  1
0  1  1
0  1  1
0  1  1

I know it is not good to loop through a dataframe, but I couldn't figure out how. Here are some failed attempts:
for x in df1:
     df2 = [df2.append(pd.DataFrame([i], columns = ('A', 'B'))) for i in x]

df2 = df1.apply(lambda x: df2.append(pd.DataFrame([x[0]], columns = ['name', 'tid'])))

If I had got the first list comprehension to work I would have tried to move the for loop to the end of the first list comprehension.
Thank you in advance for your help!

A: does this do the trick?
import pandas as pd
import itertools

df = pd.DataFrame(data = {'A': [[[1,1],[1,1]], [[1,1]], [[1,1],[1,1],[1,1]]]})

a = []
b = []
for k in range(len(df)):
    a.append([x[0] for x in df.iloc[k].A])
    b.append([x[1] for x in df.iloc[k].A])

df2 = df2 = pd.DataFrame(data = {'A': list(itertools.chain(*a)), 'B': list(itertools.chain(*b))})

Result:
>>> df2
   A  B
0  1  1
1  1  1
2  1  1
3  1  1
4  1  1
5  1  1

A: quick solution:
obj = df['A'].explode()
df1 = pd.DataFrame(obj.tolist(), index=obj.index, columns=['A', 'B'])

Demo data:
df = pd.Series([
    [[1,2],[1,2]],[[3,4]], [[1,2],[1,3],[1,4]]
], name='A').to_frame()
print(df)

                          A
0          [[1, 2], [1, 2]]
1                  [[3, 4]]
2  [[1, 2], [1, 3], [1, 4]]

use explode to transform each element of a list-like to a row, replicating index values.
obj = df['A'].explode()
df1 = pd.DataFrame(obj.tolist(), index=obj.index, columns=['A', 'B'])
df_result = df1.groupby(level=0)[['A', 'B']].agg(list)

df_result

               A          B
    0     [1, 1]     [2, 2]
    1        [3]        [4]
    2  [1, 1, 1]  [2, 3, 4]

df1

       A  B
    0  1  2
    0  1  2
    1  3  4
    2  1  2
    2  1  3
    2  1  4

use .apply(pd.Series) to convert a column with list element to dataframe.
df2 = df.A.apply(pd.Series)
print(df2)

       0       1       2
0  [1, 2]  [1, 2]     NaN
1  [3, 4]     NaN     NaN
2  [1, 2]  [1, 3]  [1, 4]


text:
Q: Update salesforce pushtopic soql query After creating pushtopic in salesforce, how can I update the query?
ex: I need to add one more field to my query
Any help would be appreciated

A: In case if someone wants the solution
Go to Developer console -> Debug -> Open Execute Anonymous Window
Then type the below
PushTopic pt = new PushTopic(Id='', Query = 'select  id, name from account');
update(pt);
execute the query

A: If you are using the 'workbench', you can update it by manually editing the query when you select it from a list (if there are some PushTopics already created or you can create one from right there).
You get two fields, namely, Name and Query after you select your PushTopic from the dropdown. You can edit the query right there :) .
Hope this helps when and if you are using workbench to run the PushTopics and you have logged in using the same credentials as of your 'org' (Developer Console, where you have created the PushTopic).

A: PushTopics are also stored in the pushtopic table and you can use soql to update them.


text:
Q: Camunda Disable DbHistoryEventHandler on Spring Boot application Hello I'm new at camunda and now I'm migrating camunda from 3.4 to 7.14, I want to disable DbHistoryEventHandler so it won't write to history table (https://docs.camunda.org/manual/7.14/update/minor/712-to-713/#changed-behavior-for-custom-historyeventhandler), but the problem is I can't found enableDefaultDbHistoryEventHandler on spring boot camunda engine properties (https://docs.camunda.org/manual/7.14/user-guide/spring-boot-integration/configuration/#camunda-engine-properties), can anyone please help me regarding this.

A: Already found the answer, for everyone facing this problem you can disable it on your spring boot application.yaml by adding this
  camunda.bpm:
    generic-properties:
      properties:
        enableDefaultDbHistoryEventHandler: false

reference: https://docs.camunda.org/manual/7.14/user-guide/spring-boot-integration/configuration/#generic-properties


text:
Q: What are each part of macros named in the C standard? I am writing an academic paper related to the C language, but I am pretty confused about the terminology and afraid that the word I used is not complied with the standard.
For example,
#define AREA_CIRCLE(radius) (M_PI * radius * radius)
|<-----------------------A------------------------>|
|<-B->| |<---C--->| |<D >|  |<----------E--------->|

printf("%f\n", AREA_CIRCLE(1024));
               |<------A'----->|
               |<---C'-->| |E'|

I am not so sure, but I guess that
A:  macro definition
B:  macro directive (preprocessor directive)
C:  macro name
D:  macro parameter
E:  macro substitution rule
A': macro ???
C': macro ???
E': macro argument

What does the accurate terminology that would not make them ambiguous for the readers?

A: According to the standard, Sec. 6.10.3, §9, the name of the macro is also called macro name when it is used for replacement. In the definitions part of the standard, more specifically in Sec. 3.3, it is stated that the function-like construction you show in your question is a "macro invocation". So
printf("%f\n", AREA_CIRCLE(1024));
               |<------A'----->|
               |<---C'-->| |E'|

A': macro invocation
C': macro name
E': [macro] argument