text:
Q: Apple Animation in React with inline CSS problem I try to recreate this animation with HTML and CSS in React with Typescript using inline styling.I am creating an object with styling information, and refer to it in the style attribute. The code is down below. It does not work and I am not sure what I am doing wrong, I suspect the styles are not defined and referred correctly?
Here is the original Codepen example I try to rewrite: Apple Animation
And here is my code
import React from 'react';

const styles = {

    '@keyframes showTopText': {
        '0%': { transform: 'translate3d(0, 100%, 0)' },
        '40%, 60%': { transform: 'translate3d(0, 50%, 0)' },
        '100%': { transform: 'translate3d(0, 0, 0)' },
    },
    '@keyframes showBottomText': {
        '0%': { transform: 'translate3d(0, -100%, 0)' },
        '100%': { transform: 'translate3d(0, 0, 0)' },
    },

    animatedTitle: {
        color: '#222',
        fontFamily: 'Roboto, Arial, sans-serif',
        height: '90vmin',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        width: '90vmin',
    },
    'animatedTitle > div': {
        height: '50%',
        overflow: 'hidden',
        position: 'absolute',
        width: '100%',
    },
    'animatedTitle > div div': {
        fontSize: '12vmin',
        padding: '2vmin 0',
        position: 'absolute',
    },
    'animatedTitle > div div span': {
        display: 'block',
    },
    'animated-title > div.text-top': {
        borderBottom: '1vmin solid #000',
        top: 0,
    },
    'animatedTitle > div.text-top div': {
        animation: 'showTopText 1s',
        animationDelay: '0.5s',
        animationFillMode: 'forwards',
        bottom: 0,
        transform: 'translate(0, 100%)',
    },
    'animatedTitle > div.text-top div span:first-child': {
        color: '#767676',
    },
    'animatedTitle > div.text-bottom': {
        bottom: 0,
    },
    'animatedTitle > div.text-bottom div': {
        animation: 'showBottomText 0.5s',
        animationDelay: '1.75s',
        animationFillMode: 'forwards',
        top: 0,
        transform: 'translate(0, -100%)',
    },
};

function Design() {
    return (

 div.text-top div']}>

                    mimicking
                    apple's design

 div.text-bottom']}>

for the win!

    );
}

export { Design };

A: You can try using styled-components to keep your component more flexible and compatible. I replicated the codepen example with styled-components and made it easily extensible.
So, TopAnimateBlock and BottomAnimateBlock have numOfLine property hence how many lines is inside the block. The second property in BottomAnimateBlock is  delayTopLine, it should have the same numbers as a numOfLine in TopAnimateBlock, because we need to wait for top lines to play.
Also you can easily change the text color with color property in TextStyle and pass as color value, HEX color or rgba() / hsla().
TextAnimation.tsx
import styled, { keyframes } from 'styled-components';

const showTopText = keyframes`
  0% { transform: translate3d(0, 100% , 0); }
  40%, 60% { transform: translate3d(0, 50%, 0); }
  100% { transform: translate3d(0, 0, 0); }
`;
const showBottomText = keyframes`
  0% { transform: translate3d(0, -100%, 0); }
  100% { transform: translate3d(0, 0, 0); }
`;

const Section = styled.section`
  width: calc(100% + 10vmin);
  display: flex;
  flex-flow: column;
  padding: 2vmin 0;
  overflow: hidden;
  &:last-child {
    border-top: 1vmin solid white;
  }
`;

const Block = styled.div<{ numOfLine: number }>`
  position: relative;
`;
const TopAnimateBlock = styled(Block)`
  animation: ${showTopText} calc(0.5s * ${props => props.numOfLine}) forwards;
  animation-delay: 0.5s;
  transform: translateY(calc(100% * ${props => props.numOfLine}));
`;
const BottomAnimateBlock = styled(Block)<{ delayTopLine: number }>`
  animation: ${showBottomText} calc(0.5s * ${props => props.numOfLine}) forwards;
  animation-delay: calc(0.7s * ${props => props.delayTopLine});
  transform: translateY(calc(-100% * ${props => props.numOfLine}));
`;

const TextStyle = styled.p<{ color: string }>`
  font-family: Roboto, Arial, sans-serif;
  font-size: 12vmin;
  color: ${props => props.color};
`;

export const TextAnimation = () => {
  return (
    <>

        <TopAnimateBlock numOfLine={2}>
          <TextStyle color="grey">mimicking</TextStyle>
          <TextStyle color="white">apple's design</TextStyle>
        </TopAnimateBlock>

        <BottomAnimateBlock numOfLine={1} delayTopLine={2}>
          <TextStyle color="white">for the win!</TextStyle>
        </BottomAnimateBlock>

    </>
  );
};

If we want to animate 3 lines instead of 2, just add / change:

*

*Add new TextStyle component

*Change from 2 to 3 numOfLine in TopAnimateBlock and delayTopLine in BottomAnimateBlock

*And replace keyframes to this fragment:

const showTopText = keyframes`
  0% { transform: translate3d(0, 100% , 0); }
  25%, 40% { transform: translate3d(0, 66%, 0); }
  60%, 75% { transform: translate3d(0, 33%, 0); }
  100% { transform: translate3d(0, 0, 0); }
`;


text:
Q: connecting sql server using amazon web services to python I want to access the sql server using the amazon web services. How do I do it? I have tried this using mysql.connecter in python.
import mysql.connecter
conn=mysql.connector.connect(host="hostname",database="datbasename",user="root",password="a")
if conn.is_connected():
    print('connected to mysql database')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grouping cases having at least twice the same descriptors in the same order I have the following dataframe :
+--------+--------------------+
|      id|         description|
+--------+--------------------+
|14144206|(1.0, 0.0, 0.0, 0.0)|
|14144206|(0.0, 1.0, 0.0, 0.0)|
|19461601|(0.0, 0.0, 1.0, 0.0)|
|19461601|(0.0, 0.0, 0.0, 1.0)|
|34578543|(1.0, 0.0, 0.0, 0.0)|
|34578543|(0.0, 1.0, 0.0, 0.0)|
|45672467|(0.0, 1.0, 0.0, 0.0)|
|45672467|(0.0, 0.0, 1.0, 0.0)|
|45672467|(0.0, 0.0, 0.0, 1.0)|
+--------+--------------------+

which can be obtained with the following code :
df = sqlCtx.createDataFrame(
    [
        (14144206, '(1.0, 0.0, 0.0, 0.0)'),
        (14144206, '(0.0, 1.0, 0.0, 0.0)'),
        (19461601, '(0.0, 0.0, 1.0, 0.0)'),
        (19461601, '(0.0, 0.0, 0.0, 1.0)'),
        (34578543, '(1.0, 0.0, 0.0, 0.0)'),
        (34578543, '(0.0, 1.0, 0.0, 0.0)'),
        (45672467, '(0.0, 1.0, 0.0, 0.0)'),
        (45672467, '(0.0, 0.0, 1.0, 0.0)'),
        (45672467, '(0.0, 0.0, 0.0, 1.0)')
            ],
    ('id', 'description')
)

The desired output is a list of tuples (which can be of length 2, 3, up to length(description)) and where each tuple contains the id that appeared 2 times, or 3 times, or 4 times etc. in the same order in the column description. So here the output should be :
[(14144206, 34578543), (34578543, 45672467)]

The first step would be to groupBy the id and sum the description in order to get the following data frame :
+--------+--------------------+
|      id|         description|
+--------+--------------------+
|14144206|(1.0, 1.0, 0.0, 0.0)|
|19461601|(0.0, 0.0, 1.0, 1.0)|
|34578543|(1.0, 1.0, 0.0, 0.0)|
|45672467|(0.0, 1.0, 1.0, 1.0)|
+--------+--------------------+

However, I encounter the following error when executing this instruction :
df.groupBy("id").agg(sum("description").alias("sum_description"))

Error :"cannot resolve 'sum(`description`)' due to data type mismatch: function sum requires numeric types, not org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7

Then for the grouping task, I don't see if there is an existing function for this purpose.
For information, my real dataframe's column description is of length 35 000, and there are about 15 000 distinct id

A: Not certain I am following the logic as I get a slightly different answer, but here goes:
# Find the cardinality of each description
description_cnt=df.groupby('description').agg(f.sum(f.lit(1)).alias('id_cnt'))
df=df.join(description_cnt, on='description')

# Group by description and count and gather the Id's into a list
df_id_grp=df.groupby('description','id_cnt')
             .agg(f.collect_list('id')
             .alias('grouped_id'))

# Filter down to count 2 and display
df_id_grp.filter(df_id_grp['id_cnt']==2)
         .select('grouped_id')
         .rdd.map(lambda x: tuple(x['grouped_id']))
         .take(20)

As you can see, the answer differs from yours, but I think the logic is as you described. If you can review and let me know your thoughts I will amend accordingly.


text:
Q: Columns in Kivy RecycleView not displaying all items I am finding it difficult to display 7 columns of items using Kivy RecycleView. I observed that if set the column length/length of the items list (self.columns) less to actual length of my items list e.g. 6, the 7 columns appear but not on a single row as expected. I will like to get all the items in the list display on a single row of 7 columns. Thank you in advance.
I am using python 3.7 on a virtual environment created in Anaconda.
Here is my code:
from kivy.app import App
from kivy.lang import Builder
# from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

items = ['First Name', 'Last Name', 'Email', 'Phone Number', 'Fax','Address 1', 'Address 2']

Builder.load_string('''
<DataTable>:
    id: main_win
    RecycleView:
        viewclass: 'CustLabel'
        id: table_floor
        RecycleGridLayout:
            id: table_floor_layout
            cols: 7
            default_size: (None,250)
            default_size_hint: (1,None)
            size_hint_y: None
            height: self.minimum_height
            spacing: 5
<CustLabel@Label>:
    bcolor: (1,1,1,1)
    canvas.before:
        Color:
            rgba: root.bcolor
        Rectangle:
            size: self.size
            pos: self.pos
''')
class DataTable(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.columns = len(items)

        table_data = []
        for t in items:
            table_data.append({'text':str(t),'size_hint_y':None,'height':50,'bcolor':(.06,.45,.45,1)})
            # table_data.append({'text':str(t)})

        self.ids.table_floor_layout.cols = self.columns
        self.ids.table_floor.data = table_data

class DataTableApp(App):
    def build(self):

        return DataTable()

if __name__=='__main__':
    DataTableApp().run()

A: Ok, i had the same problem. I finally solved it by adding a database. It means when your database is empty you won't be able to display all the columns. This will create a database with the desired columns. So here is how you can create a Mongo database:
create a .py file called testdb and add to it this source code:
import pymongo

client = pymongo.MongoClient('mongodb://127.0.0.1:27017')
mydb = client['silverpos']

products = mydb.stocks

record = {
    'product_code': '14527',
    'product_name': 'Jely',
    'product_weight': '45',
    'in_stock': '400',
    'sold': '678',
    'order': 'wesd',
    'last_purchase': '23 june'
}

products.insert_one(record)

After that, you will have a running database as a service. Try to display your GUI again with 7 as several columns or [you know, do the math]


text:
Q: Square when pie jqplot is 100% I am using jqplot for drawing a pie chart. But when I draw a pie chart with data that represent 100% of a variable, it shows a very strange pie chart.

This is my code

A: You have two extra commas in
title: {
            text: '',   // title for the plot,
            show: true,
        },

and in
        rendererOptions: {
          dataLabelFormatString: "%d%",
          diameter: 135,
          showDataLabels: true,
          sliceMargin: 1,
          textColor: "#ABBBBB",
          lineWidth: 5
        },

That is invalid in javascript. Therefore the reason for this issue could be this.

A: problem is

sliceMargin: 1,

without it all works ok.


text:
Q: FTP upload never throws an error issue I've created an application that uploads files to a remote FTP server. If the credentials (address, username, password, etc.) are wrong I want to to throw an error. As of right now it never does. What is wrong with my code? When the credentials are correct it does successfully upload.
here is the class I am using:
 public void upload(string remoteFile, string localFile)
    {
        try
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpStream = ftpRequest.GetRequestStream();
            FileStream localFileStream = File.OpenRead(localFile);
            byte[] byteBuffer = new byte[bufferSize];
            int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            try
            {
                while (bytesSent != 0)
                {
                    ftpStream.Write(byteBuffer, 0, bytesSent);
                    bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            localFileStream.Close();
            ftpStream.Close();
            ftpRequest = null;
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        return;
    }

and where I'm calling the upload function in the form:
On button click =
    ftp ftpClient = new ftp(@"ftp://weburl.com/", "user", "password");
    UploadToFTP("testing/file.txt" , @"C:\file.txt");

    void UploadToFTP(string FTPfolder, string LocalFolder)
    {
        try
        {
            ftpClient.upload(FTPfolder, LocalFolder);
            Messagebox.Show("Uploaded Successfully!");
        }
        catch (Exception ex)
        {
            Messagebox.Show(ex.ToString());
        }
    }

A: From my comment if there is an error, its spitting it to the console, but isn't waiting for readkey, so the console is disappearing, you never catch another exception in your call because the catch in the function is handling the error. Inside the function replace Console.WriteLine with Messagebox.Show to see the caught errors
 public void upload(string remoteFile, string localFile)
    {
        try
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpStream = ftpRequest.GetRequestStream();
            FileStream localFileStream = File.OpenRead(localFile);
            byte[] byteBuffer = new byte[bufferSize];
            int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            try
            {
                while (bytesSent != 0)
                {
                    ftpStream.Write(byteBuffer, 0, bytesSent);
                    bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                }
            }
            catch (Exception ex) { Messagebox.Show(ex.ToString()); }
            localFileStream.Close();
            ftpStream.Close();
            ftpRequest = null;
        }
        catch (Exception ex) { Messagebox.Show(ex.ToString()); }
        return;
    }

A: Rewrite your upload function is eating the exception.
I would rewrite your catch block this way:
        try
        {
            // ....
        }
        catch (WebException webEx)
        {
            string message = string.Empty;

            if (webEx.Response.GetType() == typeof(FtpWebResponse))
            {
                FtpWebResponse response = (FtpWebResponse)webEx.Response;
                message = string.Format("{0} - {1}", response.StatusCode, response.StatusDescription);
            } else
            {
                message = webEx.Message;
            }

            throw new Exception(message);
        }


text:
Q: Custom URL Scheme for Windows 8 Is there something similar for the Windows 8 platform to the custom url scheme found on the iOS platform?
I have found information on MSDN about an application URI scheme. This is not the answer.
In my iPad app, the user receives an email with a couple of long keys. The user clicks the url and my app opens to the right page with these values populated. Is there similar functionality available for Windows 8 that I have missed?

A: You're looking for protocol activation.
You can add a supported protocol to Package.appxmanifest on the Declarations tab by adding a Protocol. This adds the following block to your Package.appxmanifest file:
<Extensions>
  <Extension Category="windows.protocol">
    <Protocol Name="alrt" />
  </Extension>
</Extensions>

You need to handle protocol activation in App.xaml.cs by overriding OnActivated:
protected override void OnActivated(IActivatedEventArgs args)
{
    base.OnActivated(args);

    if (args.Kind == ActivationKind.Protocol)
    {
        var protocolArgs = args as ProtocolActivatedEventArgs;

        var rootFrame = new Frame();
        rootFrame.Navigate(typeof(MainPage), protocolArgs.Uri.AbsoluteUri);
        Window.Current.Content = rootFrame;
        Window.Current.Activate();
    }
}

Check this page for a more detailed explanation.

A: Take a look at protocol activation.  The Association launching sample should provide a sample you can tweak for your own needs.
The Bing Maps app for instance has a fairly extensive URI scheme (not that you can see how they implemented it, of course :))


text:
Q: Unable to display nodes of the list properly starting from the tail to head My insert method explanation:
I assigned the "next variable" of tail to hold the address of the old node. I assigned the tail with the new node inserted into the list.
I tried to display the list starting from the tail and going through the list until it reached the head.
Problem:
But the input displayed C which is not what I wanted. Display method is supposed to display C, B, A.
I even debug my code on paper. I don't know why the display is not retrieving the last address of the nodes linked in the linked list. It only retrieved the last node in the list and display only that last node in the list.
public static void main(String[] args)
    {
        LinkedList list = new LinkedList();
        list.insert("A");
        list.insert("B");
        list.insert("C");
        list.display();

    }

public void insert(String data)
    {
        Link link = new Link(data);

        // this code only executes the first time when the list has
        // no node
        if(head == null)
        {
            head = link;
            tail= link;
        }
        // this code will execute when the linked list has one or more node
        else
        {
            tail.next = tail;
            tail = link;

        }
    }

    public void display()
    {

        while(tail != null)
        {
            System.out.println(tail.data);
            tail = tail.next;

        }

    }

A: You have created a singly linked list. The list has a head and tail, the links are from head to tail. A singly linked list by design has one direction "forward". With elements [a,b,c] the list is linked a->b->c. To print the elements in reverse order you have at least two options. Use recursion to print the elements c , b, a or implement a doubly linked list


text:
Q: what is the difference between struct {0} and memset 0 Assume we have struct like this:
struct A
{
    int x;
    int y;
};

what is the difference between
A a = {0};

and
A a;
memset(&a,0,sizeof(A));

A: Both are setting memory to 0
The first is used to set only a static allocation memory to 0
A a ={0}; // set a staic memory to 0

And you could not do it in this way:
A *a = malloc(sizeof(A)); a = {0} // This could not be done

The second is used to set both dynamic and static allocation memory to 0
A a;
memset(&a,0,sizeof(A));

And you could do also
A *a = malloc(sizeof(A)); memset(a,0,sizeof(A));

Another thing
when using memset to set your memory to 0, here your are calling a function (and this take time). And when setting with {0}, you are not calling a function. So the {0} could be faster than memset

A: None. The final outcome is that both initialize structure members to 0.
C99 Standard 6.7.8.21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Your structure A is an aggregate and above rule applies to it. So all the structure members are initialized with value same as for static storage duration. Which is 0.
C99 Standard 7.21.6.1 The memset function:
void *memset(void *s, int c, size_t n);

The memset function copies the value of c (converted to an unsigned char) into each of the first n characters of the object pointed to by s.

In simple words all the members including the alignment/padding bits in object of your structure A are set to 0.
Note that only difference between the two constructs in C is that memset sets the alignment/padding  to 0 as well, while the aggregate initialization only guarantees that your structure members are set to 0.
In either case you do not have access to the alignment/padding bytes through convention language constructs and hence both get you the same effect.


text:
Q: Where should I store data that needs to persist for a given appleID? The answer to this question may be iCloud storage, but I am using this for a very light-weight piece of data and think it may be extreme to use iCloud for this one purpose.  We have an in-app subscription app.  Before we provided the app for free but would not deliver any content to it until the user subscribed to content through the in-app subscription.
Some reviews indicate people think that we are trying to trick them by saying free and then saying they have to subscribe.  We want the app to be listed as the price of the subscription to avoid this misunderstanding but after the first year has elapsed offer them the in-app subscription to continue.  We plan to store the initial launch date in persistent storage so that we can determine when to begin requiring a subscription receipt.
1) We wanted to use the keychain storage since this information will persist even if a user removes the app from his/her device and then re-installs.  The problem is if the user gets a new device and does not restore it from an encrypted backup, then the initialized value will be lost.
2) If we use our servers to store this value for them, then there seems to be no way to tie it to that appleID; so that is ruled out as a possibility.
3) Back to iCloud, it just seems like a lot to add iCloud support just for this, and I believe the user still has to have iCloud enabled for this to work.
Does anyone know the solution to this data persistence problem?  Help is appreciated!

A: Yes, nsubiquitouskeyvaluestore is the way to get it synched with new devices.  Using this in conjunction with both keychain for storing on a device after app as been removed and nsuserdefaults for quick and easy unconstrained access is the way to go.  Apple also has a way to read receipts for the actual app purchase now, but it only works for iOS 7. Solutions should conditionally rely on receipt data from nsbundle.mainbundle url if it is available.


text:
Q: Output data based on the dropdown list selection I have a dropdown list in my Excel sheet that contains a series of months (Jan - 2012, Feb - 2012 etc..)
I have the drop down working perfectly but say on another sheet. I want the text Today the month is <insert drop down text> how would I go about achieving that?

A: 1) Click on that drop down cell
2) Type a name for that cell into the NAME BOX to the left of the formula bar.  Let's name this cell MyDate

3) on your other sheet, use this formula:
="The month is " & MyDate

A: Nevermind.. I figured it out :)
What I did was first of all give all months a reference number (so the first month would be 1 then 2 etc..).
Then on  my dropdown liost. I made sure if was referencing the list of months with the reference numbers in the next collumn and then linked it to cell A1 on the same sheet.
This number corresponded to a month listed in the list of months and would change dynamiclly based on the item selected in the drop down list.
I then did a simple VLOOKUP formula that matched the number to the month and... voila!
Here's the vlookup formula I used.
=VLOOKUP(A1,A3:D14,2,FALSE)


text:
Q: Loading Moqui without Demo Data I'm new to Moqui/ Hivemind, I have been able to get Hivemind / Moqui up and running with Demo Data, by loading data using
java -jar moqui.war load conf=conf/MoquiDevConf.xml

however, I need to get Hivemind up without Demo Data (i.e only seed data) and have tried loading data using
java -jar moqui.war load types=seed,seed-inInitial,install conf=conf/MoquiDevConf.xml

System gets up and running, without Demo Data, but the system does not have any styles. What is the best way to load Seed Data (including default style) without Demo Data. Appreciate any pointers

A: Solved.
It seems like the below section in -> https://www.moqui.org/m/docs/framework/Multi-instance+with+Docker has an error instead of seed-initial it calls out as seed-inInitial, I fixed that with the below command for loading seed data and every thing works well
Working Command -> java -jar moqui.war load types=seed,seed-initial
Step 6: Check the moqui.local instance
You can see if the instance is running from the Instances screen using the 'Check' button in the Instance column. You can also use docker directly to see if the instance is running (with docker ps).
To see the logs for the instance use something like docker logs -f moqui_local
To resolve the moqui.local domain name add it to the system, i.e. in /etc/hosts.
Now in your browser you can go to 'http://moqui.local' and if all worked properly you will see a fresh copy of Moqui running with production settings and a database with only seed, seed-ininitial, and install data loaded. Note that there are no users yet in the system so the Login screen will show you a form to create an admin user. This should be done right away after setting up a new instance so that option is disabled.


text:
Q: Upload file to Sharepoint from Data Factory We are generating an extract file in Data Factory(blob) that we need to upload to a SharePoint location. Is there any service available in azure to do this activity?

A: We were able to do this via Logic Apps.

A: since your source is blob and destination s sharepoint , HTTP is not available as a sink in ADF . SO unfortunately you cannot use the REST API and also there is no direct connector to sharepoint.
So you can use Logic app or Azure function for the copy task from blob to sharepoint


text:
Q: Theming in tiling window managers? I am trying out tiling window managers like scrotWM, and have noticed that GUI programs start with a "theme" (or lack, thereof) that looks like the bland Redmond theme. Is there a way to specify the appearance/themes of windows in a tiling window manager? Or is it window manager OR GUI toolkit specific? Is there anything I can do? Thanks.

A: Yes, theming is specific to each particular application (window manager or otherwise). Applications that use the same GUI toolkit usually use the same configuration mechanism to select a theme, so they'll look the same.
Many tiling window managers are designed to have a low visible footprint, so there's not much room for visual theming. Maybe that's why you consider them bland.

A: For GTK applications themes can be set in the file ~/.gtkrc-2.0. Mine is
gtk-icon-theme-name="gnome"

and that makes various applications use the gnome icons. You can see a list of available icon themes in /usr/share/icons/.


text:
Q: DataReader->ReadString throws exception I have code below. Creating array of BYTEs, filling it with some sytes, and then trying to read it. When reading, i got an error:
int imageSize = 1024;
BYTE* input = new BYTE[imageSize];
// input is filling by some bytes..
DataWriter ^writer = ref new DataWriter();
writer->WriteBytes(ArrayReference<BYTE>(input, imageSize));

IBuffer ^buffer = writer->DetachBuffer();
DataReader ^ reader = DataReader::FromBuffer(buffer);
auto res = reader->ReadString(buffer->Length); // THIS STRING THROW Platform::COMException ^

A: Strings cannot contain random data - they must contain well-formed Unicode code-points. I assume the error (which you don't include) says this:

HRESULT:0x80070459 No mapping for the Unicode character exists in the target multi-byte code page.

From the name of your variable (imageSize) it sounds like you're trying to load bitmap data, which is not a valid String.


text:
Q: Calling C++(cocos2dx) method from java(android) for my in-app billing I'm trying to add in-app billing in my cocos2dx-android project. I am able to give a call to java function from c++ class via jni.
This is the way i give a call to my java function via jni.
    JniMethodInfo t;
        JniHelper::getStaticMethodInfo(t
                , "com/test/project/Project"
                , "BuyProduct"
                , "(Ljava/lang/String;)V");

        char buffer[20];
        sprintf(buffer,"product1");
        jstring StringArg1 = t.env->NewStringUTF(buffer);

    t.env->CallStaticVoidMethod(t.classID, t.methodID, StringArg1);

The in-app billing is working fine, but now i have to give a call back to my c++ class to inform if the product purchase was successful or not.
I could return the result from the called method only by mentioning the specified return type, but the in-app process being a asynchronous process-goes through a lot of method calls, and my control is not returned back to the same method. So returning a value would not work.
So is there any other way of passing a value(in my case the result of in-app purchase) to my c++ class from java function???

A: check the cocos2dxHelper.cpp file to have a look how cocos2dx call c++ method.
basically there is a method in cocos2dxHelper.java which only have the definition but not the implementation, usually it looks like
public static native blahblah();

and there is a corresponding function in cpp file called
Java_org_cocos2dx_cocos2dxHelper_blahblah()

if you call the blahblah() in Java code with runOnUIThread(), the c++ function
Java_org_cocos2dx_cocos2dxHelper_blahblah()

will be called.
by the way, the c++ code need to be in something extern C { }


text:
Q: Improper animation after clicking the mouse button When I run below code my expected output is that the player should continuosly animating and when user taps on screen the player should jump. My player's frames are diffrent and jump frames are different. I am calling frames on mouse left button click. All frames are processed but its too fast so the animation is not visible.
    private void OnUpdate(object sender, GameTimerEventArgs e)
    {
        float elapsed = (float)e.ElapsedTime.TotalSeconds;
        timer5 -= elapsed;

        TouchPanel.EnabledGestures = GestureType.Tap;
        TouchCollection touches = TouchPanel.GetState();

        MouseState mousestate = Mouse.GetState();

        //Texture.position += velocity;
        //if (rect.Contains(new Microsoft.Xna.Framework.Point(mousestate.X, mousestate.Y)) && mousestate.LeftButton == ButtonState.Pressed)

        if (mousestate.LeftButton==ButtonState.Pressed)
        {
            for (int i = 0; i < 32; i++)
            {

               jump();
                jumpframe++;
                if (jumpframe > 24)
                {
                    jumpframe = 0;
                }
                System.Diagnostics.Debug.WriteLine("currentframe:"+ jumpframe);
            }
        }

        if (timer5 <= 0)
        {
            playerr();
            currentframe++;
            if (currentframe > 24)
            {
                currentframe = 0;
            }
            timer5 = TIME_BET_FRAME;
        }
    }

    private void OnDraw(object sender, GameTimerEventArgs e)
    {
        SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();

        //level.Draw(spriteBatch);
        rect2 = new Rectangle(0, 0, 960, 620);
        rect = new Rectangle(0, 0, 420, 300);

        spriteBatch.Draw(Texture.player[currentframe], Texture.position, Color.White);
        spriteBatch.Draw(Texture.jumpplayer[jumpframe], Texture.jumpposition,                 Color.White);
        spriteBatch.Draw(Texture.jumpbtn, Texture.rect, Color.White);
        spriteBatch.DrawString(font, "Score", new Vector2(10, 0), Color.Gold);
        spriteBatch.End();
    }

    public void jump()
    {
        Texture.jumpposition.X = 10;
        Texture.jumpposition.Y = 243;
        Texture.position.X = -400;
        Texture.position.Y = 243;
    }

    public void playerr()
    {
        Texture.position.X = 10;
        Texture.position.Y = 243;
        Texture.jumpposition.X = -400;
        Texture.jumpposition.Y = 243;
    }

A: What I see is the loop
for(int i=0;i<32;i++){...}

which is drawing a complete jump animation at once in the OnUpdate.
What you can do instead:
bool _jump;

private void OnUpdate(object sender, GameTimerEventArgs e)
{
    // ...
    if (mousestate.LeftButton==ButtonState.Pressed)
    {
         if(!_jump)
         {
             // start jumping
             _jump = true;
         }
         else
         {
             // jumping in progress
             _jumpframe++;
             // end of jumping check
             if(_jumpframe > 24)
             {
                 _jumpframe = 0;
                 _jump = false;
             }
         }
         jump();
    }
}

This should perform animation of jumping with the speed (frequency) of OnUpdate.


text:
Q: Why is my universal selector overriding my element selector? Apologies if this has been asked, but I can't figure out why this is happening! The text is appearing as black, even though I've set it up in the body selector as red. I appreciate the help.
(Note: The same thing happens with the div selector)
css:
* {
  color: black;
}

body {
  font-family: "Courier New", Courier, monospace;
  line-height: 1.5em;
  color: red;
}

HTML:

Hi!

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus,
      reprehenderit expedita, non eveniet qui eos nostrum, tenetur odit
      perferendis praesentium voluptatem nobis rerum laborum. Nobis consequuntur
      reprehenderit id nesciunt exercitationem!

A: The body doesn't contain any text directly. That is why you can't see the red text. While * applies to all the selectors, hence you can only see the black color.
Look at the following code, it will make more sense to you.

*{
  color: black;
}

body {
  color: green;
}

p {
  color: red;
}

   Body text

Hi!

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus,
      reprehenderit expedita, non eveniet qui eos nostrum, tenetur odit
      perferendis praesentium voluptatem nobis rerum laborum. Nobis consequuntur
      reprehenderit id nesciunt exercitationem!

A: You want to target the paragraph and the heading (p/h2)
The * applies to all selectors but CSS is cascading as the name explains which means that any style you give to a div below the first rule, will override whatever you have on the *
Give them a class attribute
HTML

Hi!

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus,
    reprehenderit expedita, non eveniet qui eos nostrum, tenetur odit
    perferendis praesentium voluptatem nobis rerum laborum. Nobis consequuntur
    reprehenderit id nesciunt exercitationem!

CSS
* {
  color: black;
}

.heading, .paragraph {
  font-family: "Courier New", Courier, monospace;
  line-height: 1.5em;
  color: red;
}


text:
Q: AJAX/PHP login - error messages not working I have a login system where the user can enter in their credentials and it will redirect them to either a "client" view or an "admin" view of the website. This is working properly.
My issues is when the user types in incorrect credential information my error messages are being displayed, i.e. Invalid username and password.
Here is my login form:
<form name="ajaxform" id="ajaxform" action="auth/ajax-auth.php" method="POST" >

Client Login

            Username
            <input id="username" class="form-control" name='username' placeholder="Username">
            Password
            <input type="password" class="form-control" id="password" name='password' placeholder="Password">

            <button type="button">Close</button>
            <button type="submit" id="loginbtn">Login</button>

</form>

Now if the user enters in bad credentials my error message should be displayed within

.
Here is what ajax-auth.php looks like:
session_start();

error_reporting(E_ALL);                //THIS IS AMAZING0
ini_set('display_errors', 1);          // <----

$username = $_POST['username'];
$password = $_POST['password'];

include '../connection.php';
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";

$result = mysqli_query($dbc, $sql);

    if (mysqli_num_rows($result) == true)
    {
        $_SESSION["username"] = $username;

        $row = mysqli_fetch_array($result);
        if ($row["permission"] == 2)
        {
            $_SESSION["permission"] = 2;
            // Redirect to the admin login page.
            echo 'admin';
        }
        else if ($row["permission"] == 1)
        {
            $_SESSION["permission"] = 1;
            $_SESSION["userId"] = $row["user_id"];
            $_SESSION["account"] = $row["account_id"];
            echo 'client';
        }
    }
    else
    {
        echo "User not found!";
        header("Location: ../index.html");
    }

And finally here is my AJAX function that handles my redirecting.
$("#ajaxform").submit(function(e)
                          {
        e.preventDefault();
        var username=$("#username").val();
        var password=$("#password").val();
        var dataString = 'username='+username+'&password='+password;
        if($.trim(username).length>0 && $.trim(password).length>0) {
            $.ajax({
                type: "POST",
                url: "auth/ajax-auth.php",
                data: dataString,
                cache: false,
                beforeSend: function(){ $("#loginbtn").val('Connecting...');},
                success: function(data){
                    if(data) {
                        //alert(data + " Logged in!");

                       if(data == "admin"){
                           window.location.href = "/TTW-Website-Final/admin/admin.php";
                       }
                       else if(data == "client"){

                        //uncomment when index.php page is ready
                        //window.location.href = "index.php";

                        window.location.href = "index.html";

                       }

                    } else {
                        $("#error").html("Error: Invalid username and password. ");
                        $("#loginbtn").val('Submit')
                    }
                }

            });
        }

When I enter in bad credentials into my form and hit login nothing happens at all and I can't seem to figure out why. It should be displaying my error message that is in my Ajax function.
$("#error").html("Error: Invalid username and password. ");

What am I doing wrong here?
I know I am close to getting this to work how I need it to and it's probably something really silly I am overlooking, any help would be greatly appreciated.

A: With the help of jeroen I understand what I was doing wrong.
I should have echoed out a value if the results from my query returned false and then have a third option in my AJAX function that deals with the value returned to my success function.
Here is what I changed in regards to my PHP:
if(mysqli_num_rows($result) == true)
    {
        $_SESSION["username"] = $username;

        $row = mysqli_fetch_array($result);
        if ($row["permission"] == 2)
        {
          $_SESSION["permission"] = 2;
          // Redirect to the admin login page.
          echo 'admin';
        }
        else if ($row["permission"] == 1)
        {
           $_SESSION["permission"] = 1;
           $_SESSION["userId"] = $row["user_id"];
           $_SESSION["account"] = $row["account_id"];
           echo 'client';
        }
    }
    else
    {
        echo "unauthorized";
    }

and within my AJAX function I added a third option to handle what happens with this returned value.
if(data) {
   if(data == "admin"){
        window.location.href = "/TTW-Website-Final/admin/admin.php";
    }
    else if(data == "client"){
        window.location.href = "index.html";
    }
    else if(data == "unauthorized"){
       $("#error").html("Error: Invalid username and password. ");
       $("#loginbtn").val('Submit')
    }
}

Doing this resolved my issue and my error messages are being displayed if I add in incorrect credentials.


text:
Q: Build Errors when installing openfeint 2.4.4 SDK I have 12 build errors when trying to install the openFeint SDK.
Build Invisible_Pong of project rocket_pong with configuration Debug
Ld "build/Debug-iphonesimulator/Invisible Pong.app/Invisible Pong" normal i386
cd /Users/robkwok/Documents/rocket_pong
setenv MACOSX_DEPLOYMENT_TARGET 10.5
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/g++-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0.sdk -L/Users/robkwok/Documents/rocket_pong/build/Debug-iphonesimulator -F/Users/robkwok/Documents/rocket_pong/build/Debug-iphonesimulator -filelist "/Users/robkwok/Documents/rocket_pong/build/rocket_pong.build/Debug-iphonesimulator/Invisible_Pong.build/Objects-normal/i386/Invisible Pong.LinkFileList" -mmacosx-version-min=10.5 -lobjc -framework Foundation -framework UIKit -framework CoreGraphics -framework QuartzCore -framework Security -framework SystemConfiguration -lsqlite3 -o "/Users/robkwok/Documents/rocket_pong/build/Debug-iphonesimulator/Invisible Pong.app/Invisible Pong"

Undefined symbols:
  ".objc_class_name_CLLocationManager", referenced from:
      literal-pointer@__OBJC@__cls_refs@CLLocationManager in OFLocation.o
  ".objc_class_name_CLLocation", referenced from:
      literal-pointer@__OBJC@__cls_refs@CLLocation in OFHighScoreAnnotation.o
      literal-pointer@__OBJC@__cls_refs@CLLocation in OFHighScoreMapViewController.o
  "_kCFStreamErrorDomainSystemConfiguration", referenced from:
      _kCFStreamErrorDomainSystemConfiguration$non_lazy_ptr in OFAsyncSocket.o
  "_kCFStreamSSLValidatesCertificateChain", referenced from:
      _kCFStreamSSLValidatesCertificateChain$non_lazy_ptr in OFCRVStompClient.o
  "_kCFStreamErrorDomainNetDB", referenced from:
      _kCFStreamErrorDomainNetDB$non_lazy_ptr in OFAsyncSocket.o
  "_kCFStreamPropertySSLSettings", referenced from:
      _kCFStreamPropertySSLSettings$non_lazy_ptr in OFAsyncSocket.o
  "_kCFStreamErrorDomainNetServices", referenced from:
      _kCFStreamErrorDomainNetServices$non_lazy_ptr in OFAsyncSocket.o
  "_kCLLocationAccuracyBest", referenced from:
      _kCLLocationAccuracyBest$non_lazy_ptr in OFLocation.o
  "_kCFStreamSSLAllowsAnyRoot", referenced from:
      _kCFStreamSSLAllowsAnyRoot$non_lazy_ptr in OFCRVStompClient.o
  "_kCFStreamErrorDomainMach", referenced from:
      _kCFStreamErrorDomainMach$non_lazy_ptr in OFAsyncSocket.o
  "_kCFStreamSSLLevel", referenced from:
      _kCFStreamSSLLevel$non_lazy_ptr in OFCRVStompClient.o
  ".objc_class_name_MKAnnotationView", referenced from:
      .objc_class_name_OFHighScoreAnnotationView in OFHighScoreAnnotationView.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Here's what I've done so far:

*

*Unzipped the openFeint folder and dragged it into my project

*Added the appropriate frameworks  (including libsqlite3.dylib)

*Added #import "openFeintPrefix.pch" to my APP_prefix.pch

A: You have to include the CoreLocation, CFNetwork and MapKit frameworks also.


text:
Q: Question about coordinate change Say $f$ is a function $f: \mathbb R^2 \to \mathbb R$. Can someone show me an example of such an $f$ with the property that $(\partial / \partial x)^2 f(x,y) = 0$ and $(\partial / \partial y)^2 f(x,y) = 0$ in one example of coordinates and $(\partial / \partial x)^2 f(x,y) \neq 0$ and $(\partial / \partial y)^2 f(x,y) \neq 0$ in another? Is it possible?

A: Take $f(x,y)=xy$. Then both pure second partial derivatives are 0, but if we change coordinates to $x=u+v$, $y=u-v$, then $f=(u+v)(u-v)=u^2-v^2$, which has non-zero pure second partials.


text:
Q: Volume charge density of a single point The original problem:

I read this one, but there's something that is still unclear, even after going through all their answers and comments.
Why doesn't the expression use the 3-dimensional Dirac Delta function? That is, shouldn't the expression be: $$\rho (\overrightarrow r ) = q \delta^3 (\overrightarrow r  - \overrightarrow r')$$

A: That's just a notational issue.  $\delta(\vec{r} - \vec{r}')$ does refer to the 3D delta function, as you can tell because it has vectors inside of it.  It's probably more clear to write it as $\delta^3(\vec{r} - \vec{r}')$ but it means the same thing.


text:
Q: Python, import a modulo from a father directory I want to know how import a file that is one level up.
I read in google this:
>>> sys.path.append("../")

But I dont like it and i hope there are a better solution

A: Another option, if what you are writing is part of a package, is to use relative imports like so:
from .. import foo

where foo is the name of the module you're trying to import.
Similarly, if you've got another module in the current directory, you can use:
from . import bar

Sadly (or perhaps not so sadly), though, this doesn't extend any further than this.  You can't go up to a grandparent, or higher.
EDIT:
As so graciously pointed out by JAB, my last comment there is not true:

from ...sys import path
Note that while that last case is legal, it is certainly discouraged ("insane" was the word Guido used).

I must have internalized Guido's description of it too much. ;^)
EDIT:
Okay, I just verified this in 2.7 - this apparently goes as deep as you like, and is dependent on the number of .
from .... import greatgrandparent

works juuuust fine.  I think I'm going to need a bucket

A: Depending how your project is organized you may be able to import it normally. Lets say your project structure is like this:
/tmp/test_prj/launcher.py
/tmp/test_prj/mymodule/__init__.py
/tmp/test_prj/mymodule/helper.py
/tmp/test_prj/mymodule/mysubmodule/__init__.py

If you use a launcher (launcher.py in this case) and always calls your project with ./launcher.py you may import helper.py inside mysubmodule using the following line:
from mymodule import helper

This works because your current working directory is /tmp/test_prj. You can check it with print sys.path, it should be the first one.
Let me know if I wasn't clear enough :D


text:
Q: Docker Laravel migration error Illuminate\Database\QueryException SQLSTATE[HY000] I have this error when running php artisan migrate:fresh:
#15 0.576    Illuminate\Database\QueryException
#15 0.576   SQLSTATE[HY000] [2002] No such file or directory (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

My docker-compose.yml:
version: "3.7"

networks:
  app-network:
    driver: bridge

services:
  app:
    build:
      context: ./
      dockerfile: Dockerfile
    image: laravel8-php-fpm-80
    container_name: app
    restart: unless-stopped
    tty: true
    working_dir: /var/www
    volumes:
      - ./:/var/www
    networks:
      - app-network

  db:
    image: mysql:5.7.33
    container_name: db
    restart: unless-stopped
    tty: true
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: db
    volumes:
      - ./mysql/data:/var/lib/mysql
    networks:
      - app-network

  nginx:
    image: nginx:1.19.8-alpine
    container_name: nginx
    restart: unless-stopped
    tty: true
    ports:
      - 8100:80
    volumes:
      - ./src:/var/www
      - ./nginx/conf:/etc/nginx/conf.d
    networks:
      - app-network

My Dockerfile:
FROM php:8.0.3-fpm-buster

RUN docker-php-ext-install bcmath pdo_mysql

RUN apt-get update
RUN apt-get install -y git zip unzip
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
COPY . /var/www
WORKDIR /var/www
RUN composer install
RUN php artisan config:clear
RUN php artisan migrate:fresh

EXPOSE 9000

My env file:
APP_NAME=App Name
APP_ENV=local
APP_KEY=base64:1XGhFF8+2qNi2IPyQVgdv783pZqTgsUl4Y77K9gUoYY=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=123456

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

in my config/database.php I got:
'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', 'forge'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

I'm new in docker, so maybe I'm missing something. Does anyone know what may be the problem here :( I spent two days investigating this error and didn't find any good answer

A: I find a solution by running bash script like this:
#!/bin/bash
echo "Migration Started";
 php artisan migrate
 echo "Seeding started"
 php artisan db:seed
 echo "Server starting"
return

but now I have problem because my migrations are running in loop, migrating never stops. I don't know why it behaves like this. Does anyone know a solution to this migration in loop problem? I also tried with adding php artisan serve before return statement and migrations finished and server does start, but then my problem is I cannot open application on port 8100, I think its because of artisan serve.


text:
Q: How to read and parse data in Java with HandleMessage method? I am building an android app that will be able to read values from a load sensor. The load sensor is connected to a LCD to display the values of weight applied to the sensor and an Arduino board. I am simply building this app to get the weight values from the LCD/load sensor. I am using HC-06 Bluetooth module, and I am able to connect/pair with this device successfully. The 'MainActivity' activity has a 'get data' button to read the data from the load sensor but anytime It is pressed the app freezes. I have been told by the author of the following tutorial that I need to write some 'Handler' method. I have made an attempt with no luck.
I've been following this tutorial but I'm stuck on reading data
https://wingoodharry.wordpress.com/2014/04/15/android-sendreceive-data-with-arduino-using-bluetooth-part-2/
Here is my code :
package com.proj.splate;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("unused")
public class MainActivity extends Activity {

  Button btnscan;
  TextView txtArduino, txtString, txtStringLength, calorie;
  Handler bluetoothIn;

  final int handlerState = 0;                        //used to identify handler message
  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket; //= null;
  private StringBuilder recDataString = new StringBuilder();

  private ConnectedThread mConnectedThread;

  // SPP UUID service - this should work for most devices
  private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // String for MAC address
  private static String address;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    //Link the buttons and textViews to respective views
    btnscan = (Button) findViewById(R.id.scanBtn);
    txtString = (TextView) findViewById(R.id.txtString);
    txtStringLength = (TextView) findViewById(R.id.testView1);

    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == handlerState) {
                String readMessage = (String) msg.obj;
                recDataString.append(readMessage);
                int endOfLineIndex = recDataString.indexOf("~");
                if (endOfLineIndex > 0) {
                    String dataInPrint = recDataString.substring(0, endOfLineIndex);
                    txtString.setText("Data Received = " + dataInPrint);
                    int dataLength = dataInPrint.length();
                    txtStringLength.setText("String Length = " + String.valueOf(dataLength));

                    if (recDataString.charAt(0) == '#')
                    {
                        //get sensor value from string between indices 1-20
                        String weight = recDataString.substring(1, 20);
                        //update the textviews with sensor values
                        calorie.setText(weight + "kg");

                    }
                    recDataString.delete(0, recDataString.length());
                   // strIncom =" ";
                    dataInPrint = " ";
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
    checkBTState();

  // Set up onClick listeners for button to scan for data
    btnscan.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mConnectedThread.write("0");
      }
    });
}

  private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

      return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
      //creates secure outgoing connecetion with BT device using UUID
  }

  @Override
  public void onResume() {
    super.onResume();

    //Get MAC address from DeviceListActivity via intent
    Intent intent = getIntent();

    //Get the MAC address from the DeviceListActivty via EXTRA
    address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

    //create device and set the MAC address
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
    }
    // Establish the Bluetooth socket connection.
    try
    {
      btSocket.connect();
    } catch (IOException e) {
      try
      {
        btSocket.close();
      } catch (IOException e2)
      {
        //insert code to deal with this
      }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();

    //I send a character when resuming.beginning transmission to check device is connected
    //If it is not an exception will be thrown in the write method and finish() will be called
    mConnectedThread.write("x");
  }

  @Override
  public void onPause()
  {
    super.onPause();
    try
    {
    //Don't leave Bluetooth sockets open when leaving activity
      btSocket.close();
    } catch (IOException e2) {
        //insert code to deal with this
    }
  }

 //Checks that the Android device Bluetooth is available and prompts to be turned on if off
  private void checkBTState() {

    if(btAdapter==null) {
        Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
    } else {
      if (btAdapter.isEnabled()) {
      } else {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
      }
    }
  }

  //create new class for connect thread
  private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        //creation of the connect thread
        public ConnectedThread(BluetoothSocket socket) {
            btSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                //Create I/O streams for connection
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;

            // Keep looping to listen for received messages
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);
                    bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }

        //write method
        public void write(String input) {
            byte[] msgBuffer = input.getBytes();//converts entered String into bytes
            try {
                mmOutStream.write(msgBuffer);//write bytes over BT connection via outstream
            } catch (IOException e) {
                //if you cannot write, close the application
                Toast.makeText(getBaseContext(), "Connection Failed", Toast.LENGTH_LONG).show();
                finish();

              }
            }

        public class BluetoothInHandler extends Handler{
            private Looper sLooper = null;

            private Handler mWorkerThreadHandler;

            final int handlerState = 0;                        //used to identify handler message

            protected class WorkerArgs {
                Handler handler;
                String input;
                String output;
            }

            public BluetoothInHandler() {
                super();
                synchronized (BluetoothInHandler.class) {
                    if (sLooper == null) {
                        HandlerThread thread = new HandlerThread("AsyncWorker");
                        thread.start();

                        sLooper = thread.getLooper();
                    }
                }
                mWorkerThreadHandler = new WorkerHandler(sLooper);
            }

            @Override
            public void handleMessage(Message msg) {
                if (msg.what == handlerState) {
                    WorkerArgs args = (WorkerArgs) msg.obj;
                    String readMessage = args.output;
                    //your job;
                } else {
                    super.handleMessage(msg);
                }
            }

            public void write(String input) {
                WorkerArgs args = new WorkerArgs();
                args.handler = this;
                args.input = input;
                Message message = mWorkerThreadHandler.obtainMessage(handlerState);
                message.obj = args;
                mWorkerThreadHandler.sendMessage(message);
            }

            protected class WorkerHandler extends Handler {
                public WorkerHandler(Looper looper) {
                    super(looper);
                }

                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == handlerState) {
                        WorkerArgs args = (WorkerArgs) msg.obj;
                        byte[] buffer;
                        //the code here run in a thread, not in the ui thread
                        //do your job like:
                        byte[] bytes = mmInStream.read(buffer);

                        args.output = new String(bytes);
                        Message message = args.handler.obtainMessage(handlerState);
                        message.obj = args;
                        message.sendToTarget();
                    }
                }
            }

        }

        }//ConnectedThread End

}

Here is my Arduino Code:
#include <LiquidCrystal.h>

int led = 13;
int button = 12;

LiquidCrystal lcd(9, 8, 4, 5, 6, 7);
// Pins used for inputs and outputs********************************************************

float sensorValue1;
float containerValue;
char inbyte = 0;
int flag;
const int numReadings = 50;
int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;

//*******************************************************************************************

void setup()
{

  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
  Serial.begin(9600);

  for (int thisReading = 0; thisReading < numReadings; thisReading++)
  {
      readings[thisReading] = 0;
  }

  lcd.begin(16, 2); //change to 16, 2 for smaller 16x2 screens
  lcd.clear();
  lcd.print("hello, world!");
  delay (1000);
  lcd.clear();
  delay (500);

}

void loop()
{
  digitalWrite(led, HIGH);
  readSensor2();    //DONE

  printLCD();       //DONE
  return;

 sendAndroidValues();

  //when serial values have been received this will be true
  if (Serial.available() > 0)
  {
    inbyte = Serial.read();
    if (inbyte == '0')
    {
      //LED off
      digitalWrite(led, LOW);
    }
    if (inbyte == '1')
    {
      //LED on
      digitalWrite(led, HIGH);
    }
  }

  //delay by 2s. Meaning we will be sent values every 2s approx
  //also means that it can take up to 2 seconds to change LED state
  delay(2000);

void readSensor2()
{
  total = total - readings[index];

  readings[index] = analogRead(A0);

  total = total + readings[index];

  index = index + 1;

  if (index >= numReadings)
  {
     index = 0;
  }

  average = total / numReadings;

   //sensorValue1 = (analogRead(A0) - 330)* i;
   //delay(200);

   Serial.println(average);
   delay(100);

   if( digitalRead(button) == HIGH && flag == 1)
  {
    flag = 0;
    containerValue = 0;

  }
  else if (digitalRead(button) == HIGH && flag != 1)
 {
  flag = 1;                        //when the button is pressed the initially sesnsor
    containerValue = sensorValue1;
    delay(10);
  }

  //Serial.println(digitalRead(button));
   delay (1000);

}

//sends the values from the sensor over serial to BT module
void sendAndroidValues()
 {
  //puts # before the values so our app knows what to do with the data
 Serial.print('#');
  //for loop cycles through 4 sensors and sends values via serial
  Serial.print(sensorValue1);
  Serial.print('+');
    //technically not needed but I prefer to break up data values
    //so they are easier to see when debugging
 Serial.print('~'); //used as an end of transmission character - used in app for string length
 Serial.println();
 delay(5000);        //added a delay to eliminate missed transmissions
}

void printLCD()
{
  lcd.setCursor(4, 0);
  lcd.print("   GRAMS    ");
  lcd.setCursor(4, 1);
  lcd.print(sensorValue1);
}

A: Not sure if this is much of a problem, since it doesn't look like you're doing a ton of work in your handleMessage(Message msg) method, but your Handler is still being created on the main thread.  To use a Handler to process background messages, you'll need to pass it a separate Looper.  An easy way to to do this would be to use the HandlerThread class to provide your Looper.
Once you do this, however, you'll need to post results back to your UI thread from your handleMessage(Message msg) since you can't modify UI elements (or use Toasts, see your "write" method) from threads other than the main thread (See Activity.runOnUiThread(Runnable runnable)).
Also, you're still using your "ConnectedThread" object as an object by how you're calling your methods from within your onClickListener...so it's not really doing what you're intending it to do in that regard.  To verify this, use Looper.myLooper() == Looper.getMainLooper() to see which thread is currently executing.  I'd advise more towards the Handler solution suggested above, and posting Runnables for execution.
Lastly, since you're ConnectedThread runs continously in a while(true) loop without pauses, this could be flooding your handler potentially as well.


text:
Q: Debounce function with args underscore I've got a function which takes in some arguments. But usage of underscore debounce is :
var lazyLayout = _.debounce(calculateLayout, 300);

But in my case calculateLayout needs some arguments to run. How can I pass them in this case?
Update :
Sample calculateLayout function :
var calculateLayout = function(a,b) {
  console.log('a is ' + a + ' and b is ' + b);
}

A: @Jamie's answer is better.
I'll keep my original answer as below, although the it should be better to use Jamie's answer if you are familiar with JS:
var calculateLayout = function(a,b) {
  console.log('a is ' + a + ' and b is ' + b);
}

var debounceCalculate = _.debounce(function(a, b){
    calculateLayout(a, b);
}, 300);

debounceCalculate(1, 2);

A: You should be able to just use an anonymous function as the first argument, then call whatever you like in it:
_.debounce(function(){
    calculateLayout(20, 30);
}, 300);

A: Since nobody has written the one liner without extra var and function, I'll do it myself:
_.debounce(calculateLayout, 300)(a, b);

Debounce function returns another function, so you can call it just afterwards debounce is executed.

A: You don't need an anonymous function in the middle, arguments will automatically be passed to the original function when you run the debounced version.
  var debounceCalculate = _.debounce(calculateLayout, 300);
  debounceCalculate(a,b);

As an advantage you don't have to hardcode-bind the arguments in advance
You can try it and if curious just check the source


text:
Q: How to integrate $1/(x^3 + 8)$? I need some suggestions to solve this integral:
$$\int_{1}^{3} \frac{1}{x^3 + 8} dx$$
Thanks.

A: 1) split $\dfrac{1}{x^3 +8}$ in a sum of $\dfrac{\alpha}{x - \beta}$ or $\dfrac{\alpha x + \beta}{x^2 + \gamma x + \delta}$ ;
2) then you should be able to calculate those classical integrals.

A: Hint: Use partial fractions: $x^3+8=(x+2)(x^2-2x+4)$.


text:
Q: shinydashboard box collapse library(shinydashboard)
library(shiny)
library(dplyr)

trtall <- rbind(rep("A",100),rep("B",100), rep("C",100))
trt <- sample(trtall,80)
agecat.temp <- c(rep("18-40",100), rep("> 40", 100))
agecat <- sample(agecat.temp, 80)
sex <- sample(rbind(rep("M",100),rep("F",100)),80)
race <- sample(rbind(rep("Asian",50),rep("Hispanic",50),rep("Other",50)),80)

df <- data.frame(trt, agecat, sex, race)

body <- dashboardBody(
  fluidRow(box(width=12,collapsed=F, collapsible = T, title="Filters", solidHeader = T,status="primary",
               box(width=5, height="220px", status="primary",
                   fluidRow(column(6,uiOutput("uivr1")),
                            column(6,uiOutput("uivl1")))))))

ui <- dashboardPage(
  dashboardHeader(disable = T),
  dashboardSidebar(disable = T),
  body, skin = "green"
)

 server = function(input, output) {
  reacui1 <- reactiveVal()

   observeEvent(input$vr1,{
      reacui1(as.list(df %>% distinct(!!input$vr1) %>% arrange(!!input$vr1)))
  })

  output$uivr1 <- renderUI(varSelectInput(width = "200px", "vr1",NULL,df))
  output$uivl1 <- renderUI(selectInput("vl1",width="200px",multiple=T,NULL,choices=reacui1()))

}

shinyApp(ui,server)

Hi,
I am dynamically trying to create UI in shiny app. The logic works fine until I collapse the box in shiny dashboard.
I did following steps and got unexpected results.

*

*I select 'trt' in "vr1" and choose "A" from "vl1".

*I collapsed the box.

*Then un-collapsed the box.

*I select 'agecat' in "vr1" - now I still see various treatments (A,B,C) but not distinct age categories (18-40, >40) in "vl1"

Can you please help.

A: The problem comes from the fact that the shown event is not passed down to the elements which are in a box inside the collapsed box.
Compare this to this slightly changed example:
body <- dashboardBody(
  fluidRow(
    box(width = 12, collapsed = FALSE, collapsible = TRUE,
        title = "Filters", solidHeader = TRUE, status = "primary",
        # box(width=5, height="220px", status="primary",
            fluidRow(column(6, uiOutput("uivr1")),
                     column(6, uiOutput("uivl1"))
        #     )
        )
    )
  )
)

and you see that in this case the second input is properly updated.
You can also use your example, go to the JS console and type $('.box').trigger('shown') and you will see that the select input is suddenly updated.
That means the problem is, that shiny still believes that the inputs are hidden and because hidden inputs are not updated you observe this behavior.
But this tells us how we can fix it:

*

*Workaround is to switch off the suspendWhenHidden property. Add this to your server:
  session$onFlushed(function() {
    outputOptions(output, "uivl1", suspendWhenHidden = FALSE)
  })

This is however, just fixing the symptom and not solving the issue.

*Another approach would be to make sure the shown.bs.collapse event is also triggered at the box inside the box. For this we can listen to the shown.bs.collapse event and once received, wait a bit (800ms) such that the box is fully visible and then inform all shiny-bound-output children that they should be shown:
js <- "$(() => $('body').on('shown.bs.collapse', '.box', function(evt) {
      setTimeout(function(){
         $(evt.target).find('.shiny-bound-output').trigger('shown.bs.collapse');
      }, 800);
   }))"

body <- dashboardBody(
  tags$head(tags$script(HTML(js))),
  fluidRow(
    box(width = 12, collapsed = FALSE, collapsible = TRUE,
        title = "Filters", solidHeader = TRUE, status = "primary",
        box(width = 5, height = "220px", status = "primary",
            fluidRow(column(6, uiOutput("uivr1")),
                     column(6, uiOutput("uivl1"))
            )
        )
    )
  )
)

This is, BTW, already reported as bug: https://github.com/rstudio/shinydashboard/issues/234


text:
Q: How to display the view of virtual studio in WPF panel? I have the code that starts the engine of external dll file and shows the view of virtual studio that is created in this dll file. The code runs perfectly in Windows Forms. Now when I try to use the same code in WPF, it complains about the final line that shows the output, and this line involves window handling. I am not that familiar with the code below and I do not know much about delegates and handling, but could somebody please help me make this run in WPF?
namespace MSShowTestGUI
    {
    public delegate void CallbackDelegate();
    public delegate void NotificationsCallbackDelegate(CinectorNotification message);

public partial class Form1 : Form
{

    MSShowAPI.API instance = new API();

    //List<AudioDevice> audioDevices = new List<AudioDevice>();
    //List<CameraDevice> cameraDevices = new List<CameraDevice>();

    CallbackDelegate clickIntoDeleg;
    IntPtr clickIntoPointer;

    NotificationsCallbackDelegate notificationsCallbackDeleg;
    IntPtr notificationsCallbackPointer;

    bool engineRunning = false;

    public Form1()
    {
        InitializeComponent();

        if (checkBox_autostart.Checked)
        {
            InitializeEngine2();
        }

        Application.Idle += Update;
        clickIntoDeleg = ClickIntoCallback;
        clickIntoPointer = Marshal.GetFunctionPointerForDelegate(clickIntoDeleg);
        instance.SetClickIntoCallback(clickIntoPointer);

        notificationsCallbackDeleg = NotificationsCallback;
        notificationsCallbackPointer = Marshal.GetFunctionPointerForDelegate(notificationsCallbackDeleg);
        instance.SetNotificationsCallback(notificationsCallbackPointer);

        //instance.SetNotificationsCallback()
    }

    #region initialization

    private void InitializeEngine2()
    {
        UpdateControls();
        if (!engineRunning)
        {
            CallbackDelegate handler = ReadyCallback;
            IntPtr delegPointer = Marshal.GetFunctionPointerForDelegate(handler);

            instance.InitializeEngine(CinectorWindow.Handle, new Resolution(1920, 1080), 1000, delegPointer); //this line shows the view of the studio in a panel but in WPF there is no "CinectorWindow.Handle"
        }
    }

    protected void ReadyCallback()
    {
        engineRunning = true;
        instance.SetActiveStudio(0);

        UpdateControls();

        // called only first run?
        /*engineRunning = true;
        UpdateControls();*/
    }

    private void button_initEngine_Click(object sender, EventArgs e)
    {
        InitializeEngine2();
    }

    private void UpdateControls()
    {
        button_initEngine.Enabled = !engineRunning;

        button_killEngine.Enabled = engineRunning;
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        ShutdownEngine();
    }

    private void ShutdownEngine()
    {
        if (engineRunning)
        {
            instance.ShutdownEngine();
            engineRunning = false;
        }
        UpdateControls();
    }

    private void button_killEngine_Click(object sender, EventArgs e)
    {
        ShutdownEngine();
    }

    #endregion

    private void ClickIntoCallback()
    {
        //code
    }

    private void NotificationsCallback(CinectorNotification notif)
    {
        notificationBox.AppendText("[" + notif.timestamp + "] " + notif.type + ": " +  notif.message + Environment.NewLine);
    }

    void Update(object sender, EventArgs e)
    {
        instance.Update();
    }

    private void CinectorWindow_Paint(object sender, PaintEventArgs e)
    {

    }

    }
    }

A: EDIT: Turns out that not only Windows have Handles.
There's a control named WindowsFormsHost that is used to host WinForms elements inside WPF views, and this control does have its own Handle property.
So you just have to change CinectorWindow and make it of type WindowsFormsHost, instead of a StackPanel, and use its Handle just like you're already doing in your question.
-- Original answer --
In WPF, only Windows have Handles, and there is no Handle property.
To get the Handle of your Window you need to do:
// "this" being the current Window
WindowInteropHelper windowHwnd = new WindowInteropHelper(this);
IntPtr hWnd = windowHwnd.Handle;


text:
Q: Return array from function in Nodejs and send it to ejs view? Okay, so my code is pulling data from a yelp business using their official API. My problem is that I can't seem to get the data to return out of the function. The problem isn't in ejs, it's that the data doesn't return when I tell it to! I just get undefined with some attempts, and with others (including the one I'm going to show here), I get an empty array. I'm pasting only the code that's important, let me know if you need more!
 function yelp(){

  var b = [];
  var i = 0;
 (struck the initialization of client)
client.business("(struck)", function(error, data) {
      if (error != undefined){
        res.send("an error occured. exiting");
        process.process.reallyExit();
      }
      b[i++] = data.name;
      b[i++] = data.display_phone;
      b[i++] = data.rating;
      console.log(b); //NEW!!
    });
    console.log(b);
    return b;
}

app.get('/yelp', function(req,res){
     var arr = yelp();
     console.log(arr);
     res.render('yelp.ejs', {title: 'Yelp!', arr: arr});
  });
}

I added one more line of code, that I THINK may have narrowed down the problem to being related to my poor internet connection. I added ANOTHER console.log(b), this time inside of the business API call. the console.log(arr) is shows second, the console.log(b); just before the reutrn shows first, and LAST is the console.log(b) INSIDE the API call. It also took a good 30 seconds for that log to appear, and it appeared AFTER the page loaded. So, how do I go about making the page wait for the data? Or is this unrelated to my problem?

A: Without knowing their API, I do recognize the callback style. The result of the call to your client would then be in the data parameter in the callback, and thats where you want to render your view.
The following is not tested.
function yelp(cb) {
    var b = [];
    var i = 0;
    // (struck the initialization of client)
    client.business("(struck)", function(error, data) {
        if (error) {
            return cb(error);
        }
        b[i++] = data.name;
        b[i++] = data.display_phone;
        b[i++] = data.rating;
    });
    console.log(b);
    cb(null, b)
}

app.get('/yelp', function(req, res) {
    yelp(function(err, arr) {
        if (err) {
            res.send("an error occured. exiting");
            process.process.reallyExit();
            return;
        }
        console.log(arr);
        res.render('yelp.ejs', {
            title: 'Yelp!',
            arr: arr
        });
    });

});

The thing to notice here, is the callback passing. This is normally how you do
async work in Node.js. It can be made a bit prettier using promises.

A: nodejs is async, meaning the app won't wait for the yelp() function to return. you can pass the yelp function a callback like so:
 function yelp(callback){

  var b = [];
  var i = 0;
 (struck the initialization of client)
client.business("(struck)", function(error, data) {
      if (error != undefined){
        res.send("an error occured. exiting");
        process.process.reallyExit();
      }
      b[i++] = data.name;
      b[i++] = data.display_phone;
      b[i++] = data.rating;
    });
    console.log(b);
    callback(b);
}
yelp(funtion(arr) {
 res.render('yelp.ejs', {title: 'Yelp!', arr: arr});
})

A: You are expecting sync things to happen, but it's async.  Your client.business method takes in a callback as it's second argument which isn't returning by the time res.render gets called.
Try this:
function yelp(callback) {

  var b = [];
  var i = 0;

  client.business("(struck)", function(error, data) {
    if (error != undefined){
      res.send("an error occured. exiting");
      process.process.reallyExit();
    }
    b[i++] = data.name;
    b[i++] = data.display_phone;
    b[i++] = data.rating;

    // No returns in async.  Just call the callback.
    callback('yelp.ejs', { {title: 'Yelp!', arr: b}})

  });

}

app.get('/yelp', function(req,res){
  yelp(res.render);
});


text:
Q: 12.10: unable to upgrade/install softwares i have changed new release with old release in order to update also unchecked ppa. please help me out.im getting a getting a error message: W: Failed to fetch http://in.old-releases.ubuntu.com/ubuntu/dists/quantal-backports/multiverse/binary-i386/Packages  Unable to connect to in.old-releases.ubuntu.com:http:  and so on......

A: As Charles has said, you need to remove the "in." at the start of your source URL. Open a Terminal and enter this command:  sudo nano /etc/apt/sources.list
Then find the url thrown by APT in the error message and remove the "in." so that the url changes from  http://in.old-releases.ubuntu.com/ubuntu/dists/quantal-backports/multiverse/binary-i386/Packages to http://old-releases.ubuntu.com/ubuntu/dists/quantal-backports/multiverse/binary-i386/Packages
Once the change has been made, press Ctrl + O to save the changes, answer 'y' when prompted, and press Ctrl + X to exit nano.
Once that's saved, run sudo apt-get update and try to install your software after that's finished.


text:
Q: Как посмотреть/декодировать исходный код игры написанный на Lua? Есть исходный код игры написанный на Lua, как посмотреть/декодировать код, чтобы отображался в нормальном формате?
В данный момент один и тот же код отображается вот так:
Нотпад++:
LJi  +  7 7  >+ % >: 2  : G  ÀÀ
childrendata/image/frame.png
framenew
Sublime:
1b4c 4a01 0269 0001 0302 0500 0c2b 0100
0037 0100 0137 0101 0110 0200 003e 0102
012b 0101 0025 0203 003e 0102 023a 0102
0032 0100 003a 0104 0047 0001 0005 c002
c00d 6368 696c 6472 656e 1964 6174 612f
696d 6167 652f 6672 616d 652e 706e 670a
6672 616d 6508 6e65 770a 7375 7065 7247

A: Есть специальная тула для этого: LuaDec. Но вопрос в версии исходников. Вообще надо посмотреть тут и посмотреть, какой из декомпиляторов тебе поможет.
Аналогичный вопрос на английском SO:
https://stackoverflow.com/questions/743684/best-tools-for-decompiling-lua-bytecode


text:
Q: Need to find all sets of 2 capital words Hello I need to find all sets of 2 capital words : So far I have:
([A-Z][a-z]+\s?){2}

But it does not work always.
For Example with the string:
Expedition Runic Monster Markers

I expect to get :

*

*Expedition Runic

*Runic Monster

*Monster Markers

I only get 1 and 3. But I also want to get 2. I'm really stuck here. Any help is appreciated.

A: Overlapping matches need to be captured inside a lookahead.
\b(?=((?:[A-Z][a-z]+\s?\b){2}))

See this demo at Regex101 (further added \b word boundaries)
If you are on Python, there is PyPI regex with overlapped=True.


text:
Q: nmap vulnerability scan reports " smtps on port 465 ssl-dh-params" vulnerability, on Ubuntu 20.04 webserver. How to close the vulnerabilty? I am running an Ubuntu 20.04 LEMP (Linux, Nginx, MariaDb, PHP) email/web server. I am also doing some nmap vulnerability tests form my MacOS Client machine. On MacOS, I am using Oh My Zsh! with the nmap plugin enabled. To do some vulnerability tests on my Ubuntu Server from my MacOS client machine, I issued the command:
nmap_check_for_vulns my.server.ip.address

which is an alias command for
nmap --script=vuln

After issuing the command with my server's IP address, nmap reported the following Vulnerabilities:
465/tcp   open  smtps
| ssl-dh-params:
|   VULNERABLE:
|   Anonymous Diffie-Hellman Key Exchange MitM Vulnerability
|     State: VULNERABLE
|       Transport Layer Security (TLS) services that use anonymous
|       Diffie-Hellman key exchange only provide protection against passive
|       eavesdropping, and are vulnerable to active man-in-the-middle attacks
|       which could completely compromise the confidentiality and integrity
|       of any data exchanged over the resulting session.
|     Check results:
|       ANONYMOUS DH GROUP 1
|             Cipher Suite: TLS_DH_anon_WITH_AES_128_CBC_SHA
|             Modulus Type: Safe prime
|             Modulus Source: Unknown/Custom-generated
|             Modulus Length: 2048
|             Generator Length: 8
|             Public Key Length: 2048
|     References:
|_      https://www.ietf.org/rfc/rfc2246.txt

On the server, the output of sudo -ss lnpt is:
LISTEN                        0                             100                                                        0.0.0.0:465                                                      0.0.0.0:*                            users:(("smtpd",pid=586529,fd=6),("master",pid=2078,fd=29))

The provided nmap link https://www.ietf.org/rfc/rfc2246.txt, doesn't provide reference to this SPECIFIC vulnerability that I can find.
My question is, what does this vulnerability mean, what process is using it, and how can I mitigate this vulnerability on my Ubuntu 20.04 server, without disabling port 456? Do I need to fix the Diffie Hellman issue in the postfix/dovecot SMTP servers, and if so, how do I go about doing so?

A: Anonymous TLS is the kind of configuration is also known as "TLS without certificates". There is no chain of trust for server's keypair, therefore absolutely no protection from MitM attacks. Certificates were invented exactly to fight this issue.
Related Postfix documentation page is TLS_README.
Postfix smtp server (which is a service running on TCP port 465) supports certificate-less operation, but only for internal hosts:

For servers that are not public Internet MX hosts, Postfix supports configurations with no certificates.

First of all, this is the only mode enabled when you set smtpd_tls_cert_file = none, but you must not use this for public-facing server. Instead, use proper globally trusted certificate and key pair. The one from Let's Encrypt will do. It could be setup in a following way:
smtpd_tls_chain_files = /.../rsachain.pem
smtpd_tls_cert_file =
smtpd_tls_key_file =

where this rsachain.pem file should contain concatenation of the following, in that order: private key, server certificate, certificate chain.
Notice that TLS 1.3 does not support certificate-less operation. So one way get rid of the warning (good one, actually) is to disable anything older:
smtpd_tls_protocols = >=TLSv1.3

The problem with this is that some old or non-conforming clients (old enough to not support TLS v1.3) will be unable to establish TLS connection.
Other way is to directly disable certificate-less operation:
smtpd_tls_exclude_ciphers = aNULL

Anyway, if the nmap alert was raised simply because Postfix did not have this aNULL thing excluded, this is a false alarm, according to the Postfix manual:

One can't force a remote SMTP client to check the server certificate, so excluding anonymous ciphers is generally unnecessary.

The reason for this is the following consideration.
Even when this thing is disabled on the server there is an easily possible downgrade attack which is a MitM proxy that only publishes this aNULL suite and TLS v1.2 (or less). The only way to be completely protected from the issue is to configure clients to not use anonymous ciphers and/or vulnerable protocols and to check the server certificate. You must configure this on each client individually, so there is no point to disable it on the server.

A: The highest version of Postfix in Ubuntu 20.04 Server currently is Postfix v3.4.13. The highest stable version of postfix is Postfix v3.6, so mitigating these vulnerabilities depends on your version of postfix.
For either version of postfix, to mitigate these vulnerabilities, you need to disable anything below TLSv1.3 in Postfix.
In Postfix less than version 3.6 you can do this by editing your /etc/postfix/main.cf file.
sudo nano /etc/postfix/main.cf

and adding !SSLv2, !SSLv3, !TLSv1, !TLSv1.1 !TLSv1.2 to the following lines:
smtpd_tls_mandatory_protocols =
smtpd_tls_protocols =
smtp_tls_mandatory_protocols =
smtp_tls_protocols =

in my case I just had to add !TLSv1.2 by changing the following lines
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1

to
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1, !TLSv1.2
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1, !TLSv1.2
smtp_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1, !TLSv1.2
smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1, !TLSv1.2

In Postfix less than version 3.6, the above changes should effectively cause postfix to "only" accept TLSv1.3 connections and higher, successfully mitigating this vulnerability.
In postfix greater than or equal to v3.6 you can do this by editing your /etc/postfix/main.cf file.
sudo nano /etc/postfix/main.cf

and adding >=TLSv1.3 to the following lines:
smtpd_tls_mandatory_protocols =
smtpd_tls_protocols =
smtp_tls_mandatory_protocols =
smtp_tls_protocols =

so your configuration in /etc/postfix/main.cf should look like this:
smtpd_tls_mandatory_protocols = >=TLSv1.3
smtpd_tls_protocols = >=TLSv1.3
smtp_tls_mandatory_protocols = >=TLSv1.3
smtp_tls_protocols = >=TLSv1.3

In Postfix greater than or equal to version 3.6, the above changes should effectively cause postfix to "only" accept TLSv1.3 connections and higher, successfully mitigating this vulnerability.

A: smtps is the port for sending email using TLS encryption. The port is used by your SMTP server.
To close the vulnerability, you need to change your SMTP server configuration. There are two options:

*

*Disable port 465 from being used. You can still use other SMTP ports for sending email.

*Fix the DH issue in the SMTP server.

Another alternative is to block port 465 with the firewall.


text:
Q: Rotate image with its objects Firstly I'm using Android application to rotating image with selected angle. that image has drawable lines by canvas.
I'm able to rotate the image but the line not.
I want to rotate and draw lines with new directions.


text:
Q: PHP XSLTProcessor strips style attributes and tags I have this XSLT
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output encoding="iso-8859-1" method="html"/>
  <xsl:template match="/">

    <xsl:if test="count(list/*) > 0">

Ci sono <xsl:value-of select="count(list/element)" />  elementi!

    </xsl:if>
    <xsl:if test="count(list/*) = 0">

Niente!

    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

That I use to transform this XML
<list><element><id>2</id><uuid>96506f09-eb04-46a2-af86-42fe9c6767ce</uuid><langcode>it</langcode><type>stu_pratica</type><user_id>1</user_id><name>a</name><status>1</status><created>1552053309</created><changed>1552053331</changed><unique_key>a</unique_key><users>admin</users><xml_content></xml_content><default_langcode>1</default_langcode><field_stu_pratica_classe_proc></field_stu_pratica_classe_proc><field_stu_pratica_data_atto></field_stu_pratica_data_atto><field_stu_pratica_data_fine></field_stu_pratica_data_fine><field_stu_pratica_data_inizio></field_stu_pratica_data_inizio><field_stu_pratica_d_protocollo></field_stu_pratica_d_protocollo><field_stu_pratica_ente></field_stu_pratica_ente><field_stu_pratica_esito></field_stu_pratica_esito><field_stu_pratica_indirizzo></field_stu_pratica_indirizzo><field_stu_pratica_lat></field_stu_pratica_lat><field_stu_pratica_lon></field_stu_pratica_lon><field_stu_pratica_nome_proc></field_stu_pratica_nome_proc><field_stu_pratica_num_atto></field_stu_pratica_num_atto><field_stu_pratica_n_protocollo></field_stu_pratica_n_protocollo><field_stu_pratica_primo_int></field_stu_pratica_primo_int><field_stu_pratica_resp_unico></field_stu_pratica_resp_unico><field_stu_pratica_stato></field_stu_pratica_stato><field_stu_pratica_wkid></field_stu_pratica_wkid><field_stu_pratica_x></field_stu_pratica_x><field_stu_pratica_y></field_stu_pratica_y></element></list>

But, in any way I try to execute the transformation:
 - style attribute is stripped from every possible tag
 - style tag is removed, but it's content is not
This happens only in PHP XSLTProcessor, any online tool I used kept the CSS instructions.
How do I keep CSS instructions in the output?
Why does this happen only in PHP XSLTProcessor and not in the online tools?
Thanks everybody for the help.
EDIT:
That's the piece of PHP code I'm using to operate the transformation:
    $output = new \DOMDocument();
    $output->loadXML(utf8_encode($body)); // For the XML

    $xslt = new \XSLTProcessor();
    $xsl = new \DOMDocument();  // For the XSLT Template

    $xsl->load($xslt_path, LIBXML_NOCDATA);
    $xsl->formatOutput = TRUE;
    $xslt->importStylesheet($xsl);
// Setting some parameters, shouldn't have to do with the css problems i think...
    $xslt->setParameter('', 'base_url', $base_url);
    $auth_url = Url::fromRoute('stu_botfo.view_authenticated_element', ['bundle' => $bundle, 'id' => ''], ['absolute' => TRUE]);
    $xslt->setParameter('', 'view_authenticated_element_link', $auth_url->toString() . '/');
    $anon_url = Url::fromRoute('stu_botfo.view_anonymous_element', ['bundle' => $bundle, 'id' => ''], ['absolute' => TRUE]);
    $xslt->setParameter('', 'view_anonymous_element_link', $anon_url->toString() . '/');
    $xslt->setParameter('', 'map_url', $map_url);
    return $xslt->transformToXML($output);

A: Solved, thanks a lot everybody.
Turns out it was not XSLTProcessor fault, but some HTML filter I was not aware of that took place later in the rendering process, I'm really sorry for not thinking about it before.

A: In most cases if you expect HTML as output you better use transformToXML() directly in the PHP XSLTProcessor. You gain better control over xsl:output attributes.
I am not sure if you are directly calling transformToDoc() in the PHP code.


text:
Q: What's the meaning of "on good authority"? The news is on good authority.
What's the meaning of on good authority?
What's the meaning of on in the context?
I never have seen this type of sentence, plz help me to understand the actual sense.

A: The meaning here is

[based] on one or more reliable and knowledgeable authorities


text:
Q: HTML table as background? I used an html table to make some cellular automata animations and would like to have those animations as the background of a webpage. Is it possible to make a table the background of the page?

A: While you can certainly stack elements over your table, you can not use a table in the same way as you would a background image. It would be helpful if you provided an example of what you have now and what you are trying to achieve.

A: Yes, it's definitely possible. What you'd want to do is fill the page with the table, by setting its position to absolute, forcing it into the top left corner, and width/height values to 100%:
#your-table {
    position: absolute;

    /* Force table into the top right corner */
    top: 0px;
    left: 0px;

    /* Expand table out into the rest of the window */
    width: 100%;
    height: 100%;
}

If you set pointer-events to "none," most browsers will prevent the cursor from changing when the user mouses over the content. There is also user-select, that can be used to disable text selection highlighting. Thus I suggest adding the following CSS rules to your background table to make it behave more like a background:
/* Disable pointer events */
pointer-events: none;

/* Disable text selection highlighting */
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
 -khtml-user-select: none; /* Konqueror HTML */
   -moz-user-select: none; /* Old versions of Firefox */
    -ms-user-select: none; /* Internet Explorer/Edge */
        user-select: none; /* Non-prefixed version, currently
                              supported by Chrome, Opera and Firefox */

Best of luck on your project!


text:
Q: Why does calling a function onclick not work all the time in Chrome and FF, but works in IE? I have the below code:

Test - Click Me

It works in Internet Explorer every time, but rarely works in Chrome and Firefox. Why would this be?
Can these browsers not handle a function onClick very well? Are there any other options I can take?
I am trying to help a client figure out why one of their tracking tags are not firing off all the time on click in these browsers.
Thanks,

A: You've got some kind of browser-dependent race condition going on, as Musa pointed out.
Try hiding the link initially, waiting for the document to load, and then adding the onclick attribute and revealing the link with javascript.
So, for example, change the link HTML to something like:
Test - Click Me

And add in your javascript, below the myFunction(), something like:
 document.addEventListener('DOMContentLoaded', function(){
   var link_elem = document.getElementById("microsoft-link");
   link_elem.onclick = function() {
     myFunction('http://view.atdmt.com/jaction/adoakb_PiggybackJSTest_1');
   };
   link_elem.style.display = 'inherit';
 });

jsfiddle -- http://jsfiddle.net/m8VTy/3/
edit: I realized I may be misinterpreting what you're trying to do. What exactly is myFunction() supposed to accomplish ?