text:
Q: Inner join and selecting by category name in PDO prepared statements I am new to PDO prepared statements and I have learned there are numerous ways to write prepared statements of which I prefer using:
$query = $db->prepare("SELECT * from users WHERE username = :username");
$query->execute(array(':username'=>$un));

It's fast and easy way and i want to just keep myself on this line. Now take a look at code below which is my question:
$query = ("SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category
FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where
category='cat1' OR category='cat2' OR category='cat3' ORDER BY blogs_id desc LIMIT 2");

Now this was actually written in php mysqli and now I want to change it to the way I have used above for PDO prepared statements without any bindValue or bindParam but as here I am calling data directly from database by category names itself so  execute(array(':category'=>cat1)); is surely not going to work as we need a variable in place of cat1 or will this work? If not how to do this.

A: You have to use placeholders only if you have a variable to be used in the query.
If not - you don't need no placeholders at all, nor have to pass anything to execute(). In fact, you can use query() method instead of prepare/execute in this case.

A: Each param should be uniquely named otherwise you might get notices warning you about the fact and the number of placeholders must match the number of parameters in the $params array - so your query could be written like this. You cannot use bound parameters in the order by or group by clauses unfortunately.
$query = ("select b.`blogs_id`, b.`title`, b.`body`, b.`posted_by`, b.`full_name`, b.`bio`, b.`posted`, c.`category`
    from `blogs` b
    inner join `categories` c on c.`category_id`=b.`category_id`
    where `category`=:cat1 or `category`=:cat2 or `category`=:cat3 or `category`=:cat4
    order by `blogs_id` desc
    limit 2");

$params=array(
    ':cat1' =>  $somevar,
    ':cat2' =>  'a string',
    ':cat3' =>  $anothervar,
    ':cat4' =>  'fashion'
);

/* with the actual values you specify */
$params=array(
    ':cat1' =>  'Entertainment',
    ':cat2' =>  'Politics',
    ':cat3' =>  'Sport',
    ':cat4' =>  'Travel'
);


text:
Q: AutoMapper How to select Collection's property, project it into DTO & return projected collection? Source models:
public class ExampleModel
{
    public int Id { get; set; }
    public float Something { get; set; }
    public string Info { get; set; } = "";
}

public class ExampleModelContainer
{
    public int Id { get; set; }
    public ExampleModel Model { get; set; } = null!;
}

public class LargeEntity
{
    public int Id { get; set; }
    public List<ExampleModelContainer> ModelEntries { get; set; } = null!;
}

Target models:
public class ExampleModelDto
{
    public float Something { get; set; }
    public string Info { get; set; } = "";
}

public class LargeEntityDto
{
    public int Id { get; set; }
    public List<ExampleModelDto> Models { get; set; } = null!;
}

AutoMapper profile:
public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<ExampleModel, ExampleModelDto>();

        // One of my attempt, I thought converting container into model, and automatically example model into DTO. Failed
        CreateMap<ExampleModelContainer, ExampleModel>()
            .ConvertUsing(x => x.Model);

        CreateMap<LargeEntity, LargeEntityDto>()
            .ForMember(x => x.Models,
                opt => opt.MapFrom(y => y.ModelEntries));
    }
}

Expected result:
LargeEntities' List<ExampleModelContainer> collection is mapped into List<ExampleModelDto>.
Actual result:
Unhandled exception. AutoMapper.AutoMapperConfigurationException: The following member on AutoMapperExps.Models.LargeEntityDto cannot be mapped:
        Models
Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type AutoMapperExps.Models.LargeEntityDto.
Context:
        Mapping to member Models from AutoMapperExps.Models.LargeEntity to AutoMapperExps.Models.LargeEntityDto
Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.
   at AutoMapper.Configuration.ConfigurationValidator.AssertConfigurationIsValid(IEnumerable`1 typeMaps)
   at AutoMapper.Configuration.ConfigurationValidator.AssertConfigurationExpressionIsValid(IEnumerable`1 typeMaps)
   at AutoMapper.MapperConfiguration.AssertConfigurationIsValid()
   at Program.Main(String[] args) in D:\Experiments\AutoMapperExps\Program.cs:line 1

How I see it possible to be made:

*

*Mapper takes source List<ExampleModelContainer> collection

*Mapper Selects Model property from each element of collection

*Mapper projects ExampleModel (returned from property above) into ExampleModelDto

*Mapper returns List<ExampleModelDto> as a final result.

Note: This is made for Entity Framework queries. I want to do most projection operations on server-side.

A: TLDR: AutoMapper throws the exception because it cannot find a mapping ExampleModelContainer -> ExampleDto. If you define a mapping the error is fixed, e.g.:
CreateMap<ExampleModelContainer, ExampleModelDto>()
  .IncludeMembers(x => x.Model);

The mapping tries to take several steps at once. If I understand your sample right, the configured mappings are like this:
ExampleModel          -> ExampleDto
ExampleModelContainer -> ExampleModel
LargeEntity           -> LargeEntityDto

When mapping the Models property in for LargeEntityDto, you are trying to map a List<ExampleModelContainer> without further configuration to a List<ExampleModelDto>. It may seem clear for AutoMapper to take the route
ExampleModelContainer -> ExampleModel -> ExampleDto
in this case, because there is only one path. But what if there were several paths to get from a ExampleModelContainer to a ExampleDto? The library would not be able to make a decision that solves all possible combinations.
This means that you as a developer have to make the decision by configuring a mapping from ExampleModelContainer to ExampleModelDto, e.g.:
CreateMap<ExampleModelContainer, ExampleModelDto>()
  .IncludeMembers(x => x.Model);

This way, AutoMapper has a direct mapping between the types and is able to map the properties. See this fiddle to test.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to send each received message when we receive many message at a time in android I have made an xmpp chat application.I also made a twist that,when ever  I am getting a message from different users i am redirecting that message to a particular mobile number as sms. Now my problem is that when i am getting many messages at a time only 1 or 2 messages is getting delivered to that mobile number,rest of the message getting missed .Can anybody help me to solve this problem.My program code is shown below :
public void setConnection(XMPPConnection connection) {
        this.connection = connection;
        if (connection != null) {
            // Add a packet listener to get messages sent to us
            PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
            connection.addPacketListener(new PacketListener() {
                @Override
                public void processPacket(Packet packet) {
                    Message message = (Message) packet;
                    if (message.getBody() != null) {
                        String fromName = StringUtils.parseBareAddress(message
                                .getFrom());
                        Log.i("XMPPChatDemoActivity", "Text Recieved " + message.getBody()
                                + " from " + fromName );
                        messages.add(fromName + ":");
                        messages.add(message.getBody());
                        String st=message.getBody();
                        String res=sendSms(SERVER,st);
                        // Add the incoming message to the list view
                        mHandler.post(new Runnable() {
                            public void run() {
                                setListAdapter();
                            }
                        });
                    }
                }
            }, filter);
        }
    }

A: This way you can resolve your problem
public void setConnection(XMPPConnection connection) {
        this.connection = connection;
        if (connection != null) {
            // Add a packet listener to get messages sent to us
            PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
            connection.addPacketListener(new PacketListener() {
                @Override
                public void processPacket(Packet packet) {
                    Message message = (Message) packet;
                    if (message.getBody() != null) {
                        String fromName = StringUtils.parseBareAddress(message.getFrom());
                        Log.i("XMPPChatDemoActivity", "Text Recieved " + message.getBody() + " from " + fromName );
                        messages.add(fromName + ":");
                        messages.add(message.getBody());
                        // Add the incoming message to the list view
                        mHandler.post(new Runnable() {
                            public void run() {
                                setListAdapter();
                            }
                        });
                    }
                }
            }, filter);
        }
    }

private void setListAdapter() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.listitem, messages);
        listview.setAdapter(adapter);
    }


text:
Q: Deprecated : The each() function is deprecated. This message will be suppressed on further calls in The following message appears on the top of the page when viewing the website on mobile. It refers to line 186, which goes as follow:
while ( $activity = each( $this->element_activities[ $tag ] ) )

I tried replacing it by:
foreach($this->element_activities[ $tag ] as $activity )

but it made it worse.
Would anyone have a solution?


text:
Q: Convert a gray scal imageto bilevel I'm trying to convert an image to a binary image (bilevel) using the method "point" of PIL as following:
def mappoint (i):
   if i > 1: return 1
   else: return 0

if __name__=="__main__":
   img = Image.open('no.tif')
   img = img.point(mappoint)
   img.save('ok.tif')

but it gives me a black image !
EDIT: If I do def mappoint (i): if i > 1: return 255 then it gives a all white image ! and if I print the value of i in mappoint it shows values from 0 to 255 (like if you do print range(256)), so each i is not the value of each pixels, is it ? There is another way to make the bilevel just by using convert when we open the image: img = Image.open(img_name).convert('1') but by default the threshold used is 127, and the doc says to use point method if we want another threshold

A: The function did work, you've generated an image with 0s and 1s. The reason it looks black is because standard images have intensities from 0 to 255.
An intensity of 1 such as you've done looks black because on a scale of 0 to 255, 1 is very close to 0.
Change your mappoint to do if i>1: return 255 if you wanted a black and white image.


text:
Q: Finding the first digit of $2015^{2015}$ Can anyone help me find the first digit of $2015^{2015}$?
It is easy to find the last digit but I have no idea for the first digit.

A: The units digit is of course a 5.
For the leading digit, see that $n^n = 10^{n\cdot log_{10}(n)} \approx 10^{2015\cdot3.304275} \approx 10^{6658.114} = 10^{6658}10^{0.114} \approx 1.3008\cdot 10^{6658}$. Therefore, the first digits of your number are 13008...
Check: http://www.wolframalpha.com/input/?i=2015^2015

A: Take the base-ten logarithm.
By the log laws, that will equal $2015\log2015$.  Suppose that is $x+y$, where $x$ is a whole number and $0<y<1$.
The number has $x+1$ digits.
$y$ tells you the first digit.  Or rather, $10^y$ starts with the same digits $2015^{2015}$ does.

A: Now, you didn't say "by hand" as these calculations often do, but I'll assume that at least you're from before 1950 so that solutions like just asking Wolfram Alpha about a mere 8000-digit number are beyond you.
We can calculate $\log_{10}(2015^{2015})=2015(\log_{10}(2.015)+3)$, and consulting my trusty tables I find that $$\log_{10}(2.015)\approx\frac{\log_{10}(2.01)+\log_{10}(2.02)}2\approx\frac{0.30320+0.30535}2\approx0.30428,$$ so $\log_{10}(2015^{2015})\approx6658.1$. (I need to do this calculation well enough to show it is between $6658$ and $6658+\log_{10} 2\approx6658.3$ to prove the claim.)
Then, $6658\le\log_{10}(2015^{2015})<6658+\log_{10} 2$ gives $10^{6658}\le2015^{2015}<2\cdot 10^{6658}$, so the first digit is $1$.


text: Q: Как лучше сделать программу для тестирования с сохранением результатов? Мне нужно написать программу для тестирования с подсчетом времени на выполнение каждого задания и теста в целом, и подсчетом баллов. И дальше все  ответы должны где-то сохраняться, чтобы потом можно было просмотреть все данные участника тестирования(время, баллы). Каким образом это можно сделать?


text:
Q: date is saving in different format when saving to database Iam saving date in below format EEE MMM dd HH:mm:ss z yyyy, but it is saving in this format 2013-05-03 00:38:20.0. But when i print same date on console before saving to database, it is as expected INFO: Fri May 03 00:38:20 IST 2013
Please can anyone explain why it is saving as above mentioned.
Below is the code:
Date now = new Date();
String datetimeStr = now.toString();
SimpleDateFormat format = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss z yyyy");
Date parseDate = format.parse(datetimeStr);

Datebase column
date_order_created date

A: I hope you're not actually saving your dates as text in the database in the first place. Assuming you're not (and I don't think you are), you're not really "saving date in below format" at all... you're just saving the date.
The value of a date doesn't have a format - June 19th 1976 is the same date whether I represent it that way, or as 1976-06-19 or 19/06/1976 or 06/19/1976 (assuming I know how to interpret any of those formats). That's what you're seeing here - you're saving the date, and when you look at it "in the database" (e.g. via some SQL console) you're seeing one representation... but when you fetch it from the database and print it from Java, you're seeing the results of calling Date.toString(). That doesn't change the value at all.
If you want to format a Date value in one particular way, use SimpleDateFormat - but be very aware that a Date object itself has no format (or time zone, or calendar) and your database probably doesn't either. (The exact details of what goes in the database will depend on the database and the column type.)
It's very important to distinguish between a value and string representations of that value.
For example, if I write:
int x = 0xff;
int y = 255;
System.out.println(x == y);

then that prints "true" - because both x and y have the same value. The fact that in one case I used a hexadecimal representation doesn't affect the value as a number at all.

A: From here
The following code formats a date and time according to the pattern String passed to the SimpleDateFormat constructor. The String returned by the format method contains the formatted date and time that are to be displayed.
Date today;
String output;
SimpleDateFormat formatter;

formatter = new SimpleDateFormat(pattern, currentLocale);
today = new Date();
output = formatter.format(today);
System.out.println(pattern + " " + output);
The following table shows the output generated by the previous code ex
Pattern              Output
EEE, MMM d, ''yy    Tue, Jun 30, '09

A: When you save a Date objet in a database, this is generally not its String representation which is saved. This depends of the field type used in the database.
And :
Fri May 03 00:38:20 IST 2013

looks like a date.toString()


text:
Q: Priority of the 3 axioms of groups In my book about Abstract Algebra, it is stated that

A group $\langle G,*\rangle$ is a set $G$, closed under a binary operation $*$, such that these 3 axioms are satisfied:

*

*$g_1$: For  all $a,b,c\in G$, $$(a*b)*c=a*(b*c) $$

*$g_2$: There  is an element $e$ in $G$ such that for all $x\in G$, $$e*x=x*e=e$$

*$g_3$: Corresponding to $a\in G$, there is an element $a'$ such that $$a*a'=a'*a=e$$

The book stated  that among the 6 orders of $g_1,g_2,g_3$, only $3$ are correct orders of defining a group. But I have no idea about it. Can someone give me some hint?

A: The author of your book is unnecessarly  delving into what order of stating axioms are useful.  A dictionary should simply list what are the words of that language.
Listing a cacaphony of letters that are not words of that language, even if logically correct, does not serve any useful purpose.


text:
Q: Meaning of "~" beore plaform version in Cordova I'm just new in Cordova and I need a little help to understand something.
When I type $ cordova platform list, it returns the following :
Installed platforms :
Available platforms :
android ~6.2.2
blackberry10 ~3.8.0
browser ~4.1.0
webos ~3.7.0
windows ~5.0.0
I would like to know precisely the meaning of " ~ " before a platform version. Does it mean that all the previous versions are supported ? Or just the mentionned version ? Also, I don't see neither iPhone nor iPad platforms in this list. Does it mean they are'nt supported ?
Thanks!

A: Cordova uses semver for the versions
That means the versions are semantic
In a version like x.y.z

*

*x is incremented after a mayor change

*y is incremented after a minor change

*z is incremented after a patch change

the tilde (~) allows newer patch level versions
So, if you have android ~6.2.2, and 6.2.3 comes out, you'll get it, but if 6.3.0 comes out, you won't.
If you want to get minor changes too, you can use the caret (^) instead
More info here


text:
Q: How do I discretize values in a pandas DataFrame and convert to a binary matrix? I mean something like this:
I have a DataFrame with columns that may be categorical or nominal.  For each observation (row), I want to generate a new row where every possible value for the variables is now its own binary variable.  For example, this matrix (first row is column labels)
'a'     'b'     'c'
one     0.2     0
two     0.4     1
two     0.9     0
three   0.1     2
one     0.0     4
two     0.2     5

would be converted into something like this:
'a'              'b'                                                    'c'
one  two  three  [0.0,0.2)  [0.2,0.4)  [0.4,0.6)  [0.6,0.8)  [0.8,1.0]   0   1   2   3   4   5

 1    0     0        0          1          0          0          0       1   0   0   0   0   0
 0    1     0        0          0          0          0          1       0   1   0   0   0   0
 0    1     0        0          0          0          0          1       1   0   0   0   0   0
 0    0     1        1          0          0          0          0       0   0   1   0   0   0
 1    0     0        1          0          0          0          0       0   0   0   0   1   0
 0    1     0        0          1          0          0          0       0   0   0   0   0   1

Each variable (column) in the initial matrix get binned into all the possible values.  If it's categorical, then each possible value becomes a new column.  If it's a float, then the values are binned some way (say, always splitting into 10 bins).  If it's an int, then it can be every possibel int value, or perhaps also binning.
FYI: in my real application, the table has up to 2 million rows, and the full "expanded" matrix may have hundreds of columns.
Is there an easy way to perform this operation?
Separately, I would also be willing to skip this step, as I am really trying to compute a Burt table (which is a symmetric matrix of the cross-tabulations).  Is there an easy way to do something similar with the crosstab function?  Otherwise, computing the cross tabulation is just a simple matrix multiplication.

A: For labeled columns like the a and c column in your example you can use the  pandas build-in method get_dummies().
Ex.:
import pandas as pd
s1 = ['a', 'b', np.nan]
pd.get_dummies(s1)
       a  b
    0  1  0
    1  0  1
    2  0  0

A: You can use some kind of broadcasting:
    In [58]: df
    Out[58]:
           a    b  c
    0    one  0.2  0
    1    two  0.4  1
    2    two  0.9  0
    3  three  0.1  2
    4    one  0.0  4
    5    two  0.2  5

    In [41]: (df.a.values[:,numpy.newaxis] == df.a.unique()).astype(int)
    Out[41]:
    array([[1, 0, 0],
           [0, 1, 0],
           [0, 1, 0],
           [0, 0, 1],
           [1, 0, 0],
           [0, 1, 0]])

    In [54]: ((0 <= df.b.values[:,numpy.newaxis]) & (df.b.values[:,numpy.newaxis] < 0.2)).astype(int)
    Out[54]:
    array([[0],
           [0],
           [0],
           [1],
           [1],
           [0]])

    In [59]: (df.c.values[:,numpy.newaxis] == df.c.unique()).astype(int)
    Out[59]:
    array([[1, 0, 0, 0, 0],
           [0, 1, 0, 0, 0],
           [1, 0, 0, 0, 0],
           [0, 0, 1, 0, 0],
           [0, 0, 0, 1, 0],
           [0, 0, 0, 0, 1]])

And then join all the pieces together with pandas.concat or similar.

A: Note that I have implemented new cut and qcut functions for discretizing continuous data:
http://pandas-docs.github.io/pandas-docs-travis/basics.html#discretization-and-quantiling

A: I doubt you will beat patsy's simplicity. It was designed precisely for this task:
>>> from patsy import dmatrix
>>> dmatrix('C(a) + C(b) + C(c) - 1', df, return_type='dataframe')

   C(a)[one]  C(a)[three]  C(a)[two]  C(b)[T.0.1]  C(b)[T.0.2]  C(b)[T.0.4]   C(b)[T.0.9]  C(c)[T.1]  C(c)[T.2]  C(c)[T.4]  C(c)[T.5]
0          1            0          0            0            1            0             0          0          0          0          0
1          0            0          1            0            0            1             0          1          0          0          0
2          0            0          1            0            0            0             1          0          0          0          0
3          0            1          0            1            0            0             0          0          1          0          0
4          1            0          0            0            0            0             0          0          0          1          0
5          0            0          1            0            1            0             0          0          0          0          1

Here the C(a) means convert the variable to categorical and the -1 is to avoid outputting  an intercept column.

A: Putting together a couple of other comments into a single response answering OPs questions.
d = {'a' : pd.Series(['one', 'two', 'two', 'three', 'one', 'two']),
     'b' : pd.Series([0.2, 0.4, 0.9, 0.1, 0.0, 0.2]),
     'c' : pd.Series([0, 1, 0, 2, 4, 5]) }

data = pd.DataFrame(d)
a_cols = pd.crosstab(data.index, [data.a])
b_bins = pd.cut(data.b, [0.0, 0.2, 0.4, 0.6, 0.8, 1.0], right=False)
b_cols = pd.crosstab(data.index, b_bins)
c_cols = pd.crosstab(data.index, [data.c], )
new_data = a_cols.join(b_cols).join(c_cols)
new_data.index.names = ['']
print new_data.to_string()

"""
       one  three  two  [0, 0.2)  [0.2, 0.4)  [0.4, 0.6)  [0.8, 1)  0  1  2  4  5

    0    1      0    0         0           1           0         0  1  0  0  0  0
    1    0      0    1         0           0           1         0  0  1  0  0  0
    2    0      0    1         0           0           0         1  1  0  0  0  0
    3    0      1    0         1           0           0         0  0  0  1  0  0
    4    1      0    0         1           0           0         0  0  0  0  1  0
    5    0      0    1         0           1           0         0  0  0  0  0  1
"""


text:
Q: How to disable systemd service manually? How to disable systemd service manually?
I can't boot. The system is stuck on "Failed to start Network Time Synchronization."
I have access to the file system and can edit files. What can I do to disable a systemd service? Can I just delete this file /lib/systemd/system/systemd-timesyncd.service?

A: As said by @JdeBP boot with recovery console, start a root shell, then issue the command journalctl -xb to see what happened.
If this does not show you anything of useful, set Storage=persistent into /etc/systemd/journald.conf, reboot, and repeat the above steps in the recovery console.


text:
Q: Cross domain exception I uploaded my wordpress blog on url : http://blog.in
I am getting cross domain exception while calling following url
                $.ajax({
                          type: "POST",
                          url: "http://app.blog.in/getToken",
                          contentType: "text/html",
                              success: function(msg) {
                                            alert(msg);
                          }
                    });

Please suggest me
Thanks

A: You are getting a cross-domain error because you are crossing domains: app.blog.in and blog.in. You should serve the content from the same domain as where you post it.

A: Since you are loading from a different subdomain, browser security doesn't allow that.
Unless you can move the data you're loading to the same domain (that's same subdomain as well), you should look into using JSONP. Then you can load data from anywhere.


text:
Q: $((x/c)^n)$ has no convergent subsequence in C[a,b] Consider the metric space C[a,b] equipped with the metric $d(f,g)=max|f(x)-g(x)|$. I would like to show that the sequence $((x/c)^n)$ has no convergent subsequence, where c is a constant such that $x/c \in [0,1] $.
My attempt:
Assume it does, then there is a continuous function $f$ such that a subsequence $((x/c)^{n_k})$ converges to it. Then $((x/c)^{n_k})$ cauchy. Thus for all $\epsilon \gt 0$ there exists K such that for any $k_n, k_m \gt K$, $d(f_{k_n},f_{k_m}) \lt \epsilon$. Then $max_{x \in[a,b]}|x^{k_n}/c^{k_n}-x^{k_m}/c^{k_m}|\lt \epsilon$. I would like to derive a contradiction from this, perhaps using the fact that $(x/c)^n$ is not uniformly continuous in the reals. However, I am uncertain of how to proceed.
Any help is appreciated

A: This is false. Take $a=0,b=1$. If $c$ is large enough then $\sup_x |\frac x  c| <\frac 1 2$ so the entire sequence $(\frac x c)^{n}$ converges uniformly to $0$.
If your question is to find a $c$ such that no subsequence of $(\frac x c)^{n}$ converges uniformly you can do the following: suppose $0<a<b$. take $c=b$. Then $(\frac x c)^{n}$ converges  to $0$ at each point $x \in [a,b)$ and to $1$ at $x=b$. Since the limitimg function is not continuous it follows that no subsequence of $(\frac x c)^{n}$ converges uniformly. I will let you handle the other cases.


text:
Q: Converting file to byte array and transmitting it with UDP. How to get file name on server from this array of bytes? So I read a file into a byte array and then I break it up into chunks and send it across the network with UDP.
Path path = Paths.get("files_upload/music.mp3");
byte[] objectBytes = Files.readAllBytes(path);

On the server I read all the chunks into a buffer and I end up with the same byte[] objectBytes as I had on the client. Now I want to write the file to disk using the original file name which is music.mp3 in this case. So how can I get the file name from the array of bytes?

A: The array of bytes doesn't contain the file name. You'd have to send it separately. You can call getFileName on your path, and then turn that into a byte array using getBytes() on the resulting string.
String fileName = path.getFileName();
byte[] fileNameBytes = fileName.getBytes();

You can then send this first and read it on the other end. Note, this wont contain the whole path, only the name of the file (music.mp3 in your case).
By the way, are you sure you want to be using UDP? What if you lose a packet or two when the data is being transferred? How do you detect that on the server?


text:
Q: python3 syntax: * before variable g = dominoes.Game.new()

for _ in range(fixed_moves):
    g.make_move(*g.valid_moves[0])

In the last line, what does the * before object g mean?

A: Asterisks (*) in arguments are used for unpacking.
For example:
def f(n, m):
  pass

l = [2, 3]
f(*l)

This will unpack l and will make the parameters n and m 2 and 3, respectively.


text:
Q: PHP sending emails twice and not uploading images correctly :/ I have been designing a website and everything has been working perfectly, until I started adding in little extras so it would work EXACTLY how I wanted it to work.
This is the script for a website that uploads a title, description, name of a person, image, email address and password for the advert that they are putting online. However it no longer wants to correctly name the image and it sends out an email twice, once in the instance that there may be an image and it instantly does it in the instance where someone may not upload an image, but it is reading it as if it is doing both because there is an error with the file upload.
Btw this is the first PHP script I have ever created so it may seem mashy as I have been kind of mixing it up from different things that I have found online :)
p.s the page where the magic happens is www.afterswap.com/give.php
p.p.s I have a global config file that sets all of the DB connection info etc, hence it being non-existent here.
<?PHP
include("inc/header.php");
foreach ($_POST as $key => $val)
    $_POST[$key] = mysqli_real_escape_string($con, $val);
$back = "Click Here To Go Back And Try Again";
if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
    $title          = mysqli_real_escape_string($title123);
    $title123       = mysqli_real_escape_string($_POST['title']);
    $description    = mysqli_real_escape_string($description123);
    $description123 = mysqli_real_escape_string($_POST['description']);
    $Sell_by        = $_POST['Sell_by'];
    $name           = mysqli_real_escape_string($name123);
    $name123        = mysqli_real_escape_string($_POST['name']);
    $email          = $_POST['email'];
    $password       = $_POST['password'];
    $imagename      = basename($_FILES['userfile']['name']);
    $uploadedfile   = $_FILES['userfile']['tmp_name'];
    if (empty($imagename)) {
        $error = 1;
        echo "
The name of the image was not found.
" . $back;
    }

    if ($error != 1 && $noimg != 1) {

        $filename  = stripslashes($_FILES['userfile']['name']);
        $extension = substr(strrchr($filename, '.'), 1);
        $extension = strtolower($extension);
    }

    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
        echo '
Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.
' . $back . '';
        $errors = 1;
    } else {

        $time     = time();
        $newimage = "/photos/" . $time . $imagename;
        $result   = move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
        if (empty($result)) {
            $error = 1;
            echo "
There was an error uploading your image.

" . $back . "";
        }

        $date  = date("Y/m/d H:i:s");
        $query = "INSERT INTO classifieds (adid, title, description, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$Sell_by', '$name123', '$email', '$password', '$newimage', '$date', '0', '0')";
        mysqli_query($query) or die(mysqli_error());

        $pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
        $query2 = mysqli_query($pullback) or die(mysqli_error());
        while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
            $newid = $row['adid'];
            $pass  = $row['pass'];
        }

        $url = "http://";
        $url .= getenv("HTTP_HOST");
        $Name      = "AfterSwap";
        $emailf    = "noreply@afterswap.com";
        $recipient = $email;
        $mail_body = "Thank you for posting a new listing!

You May Now Manage Your Ad by selecting one of the following options:

Approve your listing: Click Here
Edit your listing: Click Here
Remove your listing: Click Here

Regards,

The AfterSwap Team";
        $subject   = "AfterSwap Ad Details";
        $headers   = "From: " . $Name . " <" . $emailf . ">\r\n";
        $headers .= "Content-type: text/html\r\n";

        mail($recipient, $subject, $mail_body, $headers);

        echo "

Your listing '" . $name123 . "' Has Been Submitted Successfully!

Please take note: Your listing will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.

";

    }
} elseif (isset($_POST['upload'])) {
    $title          = mysqli_real_escape_string($title123);
    $title123       = mysqli_real_escape_string($_POST['title']);
    $description    = mysqli_real_escape_string($description123);
    $description123 = mysqli_real_escape_string($_POST['description']);
    $Sell_by        = $_POST['Sell_by'];
    $name           = mysqli_real_escape_string($name123);
    $name123        = mysqli_real_escape_string($_POST['name']);
    $email          = $_POST['email'];
    $password       = $_POST['password'];
    $date           = date("Y/m/d H:i:s");
    $query          = "INSERT INTO classifieds (adid, title, description, cat, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$category', '$Sell_by', '$name123', '$email', '$password', 'images/noimage.jpg', '$date', '0', '0')";
    mysqli_query($query) or die(mysqli_error());

    $pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
    $query2 = mysqli_query($pullback) or die(mysqli_error());
    while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
        $newid = $row['adid'];
        $pass  = $row['pass'];
    }

    $url = "http://";
    $url .= getenv("HTTP_HOST");
    $Name      = "AfterSwap";
    $emailf    = "noreply@afterswap.com";
    $recipient = $email;
    $mail_body = "Thank you for posting a new listing!

You May Now Manage Your Ad by selecting one of the following options:

Approve your listing: Click Here
Edit your listing: Click Here
Remove your listing: Click Here

Regards,

The AfterSwap Team";
    $subject   = "AfterSwap Ad Details";
    $headers   = "From: " . $Name . " <" . $emailf . ">\r\n";
    $headers .= "Content-type: text/html\r\n";

    mail($recipient, $subject, $mail_body, $headers);

    echo "

Thank you " . $name123 . ", your listing has been submitted successfully!

Please take note: Your isting will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.

";

} else {
?>

/* HTML Form here */

<?PHP } ?>

A: Try this
Change this line
} elseif (isset($_POST['upload'])) {

to
} elseif (isset ( $_POST ['upload'] ) && empty($_FILES)) {

A: The only thing I can think of would be a if, elseif, or else being passed twice because the condition is being met twice. You may want to revise the code with better indentation, and checking when the elseif, if, and else blocks are passed. Also, it would be a really good idea to take the advice from the two people that commented on your post, MYSQLI is a great way to go! One more thing: You should never pass $_POST unsanitized!! Here is a short easy sanitization script!
MYSQLI:
foreach($_POST as $key=>$val)
$_POST[$key] = mysqli_real_escape_string($con, $val);

MYSQL:
foreach($_POST as $key=>$val)
$_POST[$key] = mysql_real_escape_string($con, $val);


text:
Q: Using Like operator to open Excel workbooks | VBA Thank you for taking the time to read this.
I am trying to use the LIKE operator to open workbooks. Previously I went with this code which works really well
Report_Name = "\XYZ.xls"
Workbooks.open Filename:= ThisWorkbook.Path & Report_Name
My main goal is to essentially open a report and sometimes the names differ i.e healthdoc or healthassess
I tried utilizing the LIKE operator to pick up on the name of the workbook however I cannot find a way to code it.
Any direction or help is appreciated. Thank you!
I was trying to use this syntax
Dim Report_Name as Workbook
if Report_Name LIKE "*Health*" then
xyz
else
xyz
However I could only get LIKE operator working only with strings

A: Use FSO to loop through files and check their names:
Option Explicit
Sub Example()

    Dim WB As Workbook
    Dim FSO As New FileSystemObject
    Dim oFolder As Object
    Dim oFile As Object

    Set FSO = CreateObject("Scripting.filesystemobject")
    Set oFolder = FSO.GetFolder("C:\Users\cameron\Documents")

    For Each oFile In oFolder.Files
        If oFile.Name Like "*Your Partial File Name*" Then

            Set WB = Workbooks.Open(oFile.Path)

            'Do whatever you want with your workbook.

            WB.Close '(Optional True/False for save changes)

        End If
    Next oFile

End Sub

A: Here are 2 sub that I can suggest. Since I don't understand from your question if you want to loop, open and modify the files in a folder, or you want simply to check the files names in a folder, I made 2 sub. One "LoopFilesNamesInFolder" will loop to check the file names without opening the files, and second one "LoopAndOpenFilesInFolder" allows you to open and make changes if you want to the files. You can use any of them based on your needs. Let me know if it helps you
Public Sub LoopFilesNamesInFolder()

Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim MyFileName As String

myPath = ThisWorkbook.Path & "\"
'The file name that you are looking for
MyFileName = "*Health*"

myExtension = "*.xls*"
'Current File in loop
myFile = Dir(myPath & myExtension)

 Do While myFile <> vbNullString

   If myFile Like MyFileName Then
   'You can also use something like
   'If LCase(myFile) Like LCase(MyFileName) Then
   'If you want to make it not case sensitive
   'Your code
   Else
   'Your code
   End If

   'Get next file name
   myFile = Dir
  Loop

End Sub

Public Sub LoopAndOpenFilesInFolder()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim MyFileName As String

'if you want to Optimize code keep the following 3 instructions
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

myPath = ThisWorkbook.Path & "\"
'The file name that you are looking for
MyFileName = "*Health*"

myExtension = "*.xls*"
'Current File in loop
myFile = Dir(myPath & myExtension)

 Do While myFile <> vbNullString

      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'You can add a DoEvents here to give time to Excel to open the workbook before moving fwd
      DoEvents

    'Do Whatever you want to do
   If wb.Name Like MyFileName Then
   'You can also use something like
   'If LCase(wb.Name) Like LCase(MyFileName) Then
   'If you want to make it not case sensitive
   'Your Code
   Else
   'Your Code
   End If

    'If you want to save your changes, replace the False by True to Save and Close Workbook
     wb.Close SaveChanges:=False

    'You can add a DoEvents here as well to give time to your Excel to close before moving to next one
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Reset Settings
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

End Sub


text:
Q: Can the /home and /swap partitions be on a different disks than the / (root) partition? I am in the process of dual-booting my Windows 10 PC to also run Ubuntu 20.04 on it. I have both a 240 GB SSD and a 1TB HDD. The SSD is for the Windows 10 OS, and the HDD is for my files/documents/everything else.
I have just freed up 40 GB on the SSD and 200 GB on the HDD to install Ubuntu. My question is, can I create the "/" partition on the SSD and the "/swap" and "/home" partitions on the HDD? If so, how?
I am very new to Linux, so please provide step-by-step solution.

A: YES YOU CAN , Just start the ubuntu installation setup and when you reach partitioning menu , 'Do Something Else' (or manual partitioning). Here you will be able to make partitions on whichever disk you want and then assign them as 'swap space' or '/home'. just be sure to make a '/' too ( This is where rest of your os will go ). Good luck.


text:
Q: Action has no declared type error I'm using Flex and Bison with my grammar for a very simple programming language. But I'm a beginner, so I'm not exactly sure about how to work with them.
Besides some basic operations (like arithmetic and logical operations, assignments, etc.) I also have a function that needs to be recognized by this language: this function is called "ftoc" and it takes one numeric argument.
In my flex .l file I have (among others) these definitions:
DIGITO [0-9]
PUNTO ["."]
CONST_REAL {DIGITO}+{PUNTO}{DIGITO}+
CONST_ENTERA {DIGITO}+
P_A ["("]
P_C [")"]

I also have this rule for the "ftoc" function:
"FtoC" { printf("%s\n", yytext);return FTOC;}

My bison .y file has this union to accept three data types:
%union {
    char *text;
    int integer;
    double real;
}

It also has these token definitions:
%token <integer> CONST_ENTERA
%token <real> CONST_REAL
%token <text> INTEGER
%token <text> REAL
%token <text> STRING
%token P_A P_C
%token FTOC

And the rules involving the "ftoc" function are these:
conversion:
    FTOC P_A constante P_C
;
constante:
    CONST_ENTERA
    | CONST_REAL
;

Now, I need to write a function that prints "ftoc" plus its argument every time the function is found. E.g., if the parser finds the function used as: FtoC(57.6) I need it to print "ftoc57.6".
My function to print this would look somewhat like this:
printFtoc(char* function, double argument){
    snprintf("%s, %f", function, argument);
}

My problem here is how exactly I should pass the parameters to this function. I tried with $n in the "conversion" rule, like this:
FTOC P_A constante P_C {printFtoC($1, $3)}

But then I get 2 errors in Bison (one for each $n), saying that "conversion" has no declared type.
I've been trying to read from Bison documentation but I don't really get what exactly I should be doing. From other questions and forums I get I might need to do something with %type or with %token, but I really don't know.
I just need to get the function name and the argument whenever they're found, but no clue on how to achieve that, since $n didn't work.

A: The error tells you exactly what is wrong -- you have a $3 use in a rule that corresponds to a constante, but you haven't declared a type for constante.  You probably need a declaration something like:
%type<real> constante

to tell bison that a constante is in the real field of the union.  You also have a problem with $1 in that action, because FTOC has no type.  You could fix that by either giving FTOC a type and modifying the lex rule to yylval appropriately, or by getting rid of the $1 and using a string literal like "ftoc" instead
Any given non-terminal can only have a single type, so you'll need to add actions to your constante rules.  With the above %type declaration, you would have:
constante: CONST_ENTERA  { $$ = $1; /* implicit int->double conversion */ }
         | CONST_REAL    { $$ = $1; /* simple assignment of a double */ }
;


text:
Q: Grails Throwing Non Unique object exception How do i call domain.save() multiple times in my application? When I save the domain midway through the application and then save it again when submission of the application it throws a non unique object exception. I've also tried calling .merge() before I submit the application but its throwing an org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect).
Thanks in advance

A: call save flush:true on your domain object and clear the session (see the example below). For more details take a look here: grails.org/doc/latest/guide/GORM.html 7.3 Persistence Basics
Book.withSession { session ->
   Book book = new Book()
   book.title = 'The Definitive Guide To Grails'
   book.save flush:true
   session.clear()
}


text:
Q: Action doesn't receive the correct prop I'm using React/Redux in this code and I'm trying to pass the correct prop by action. My intention is to change converter name on click modal button. But when I debbug, console server shows me the same action with no alteration clicking on confirm button.
My action in file actions:
export const saveOrUpdateConverter = converter => {
    return {
        converter,
        type: CONVERTER.SAVE_OR_UPDATE_CONVERTER
    };
};

The function I'm using to do that:
export const saveOrUpdateConverter = (converter, type) => {
    const url = `${BASE_URL}/SaveOrUpdateConverter`;

    let converterWithoutId = {
        ...converter,
        Id: 0
    };

    return makeRequest(
        {
            method: "post",
            url,
            data: type === "edit" ? converter : converterWithoutId
        },
        (data, dispatch) => {
            // if we are adding a new converter, we need to remove it from newConverters
            if (type === "add") {
                dispatch(actions.removeFromNewConverters(converter));
            }

            dispatch(actions.saveOrUpdateConverter(data));
        },
        true
    );
};

The file where I'm calling the function
const handleSaveUpdateConverter = async () => {
        let type = "edit";
        return await props.saveOrUpdateConverter(converter, type);
    };

Component receiving function by prop:
    <AddOrEditConverterModal
                        converter={converter}
                        show={showEditConverterModal}
                        onCloseModal={() => setShowEditConverterModal(false)}
                        saveOrUpdateConverter={(converter, propsType) =>
                            handleSaveUpdateConverter(converter, propsType)
                        }
                        type={"edit"}
                    />

I finally call the props saveOrUpdateConverter in other file:
 const updateConverter = async () => {
        if (converter.IntervalToSavePayload < 5) {
            props.requestError(
                true,
                props.intl.formatMessage({
                    id: "modal.base.converter.interval.save.pyload.error"
                })
            );
            return;
        }

        await props.saveOrUpdateConverter(converter, props.type);
        debugger
        props.onCloseModal();
    };

Connect function to use saveOrUpdateConverter :
import { connect } from "react-redux";
import { saveOrUpdateConverter } from "Features/Devices/Converters/actions";
import ConverterPage from "./ConverterPage";

const mapStateToProps = state => ({
    activeConverters: state.converter.activeConverters,
    activeInstruments: state.instrument.activeInstruments
});

export default connect(mapStateToProps, {saveOrUpdateConverter})(ConverterPage);


text:
Q: Concatenação diferente ? Galera estou começando a programar tem pouco tempo e tenho de fazer um cadastro só que eu quero que as informações digitadas pelo usuário como o nome, e-mail e idade apareçam através de um "alert" depois que ele clicar no botão "Aceitar".
Meus arquivos HTML e Javascript já estão "interligados", eu não sei se é possível fazer desse jeito, se não for me apresente a melhor forma de fazer isso utilizando apenas HTML e Javascript, e se for por favor me mostrem como.

Meu arquivo HTML

    Nome:
    <input type="text" name="nome" size="20" maxlength="20" placeholder="Seu nome"/>

    Senha:
    <input type="password" name="senha" size="20" maxlength="25" placeholder="Sua senha"/>

    <input type="button" value="Aceitar" onClick="aceitar()">
    <input type="button" value="Cancelar"></input>

</form>

Meu arquivo JS

function aceitar(){
    alert("Aqui seria a concatenação")
 }

No aguardoAtt,Lone

A: A concatenação é simples, basta usar o +, que é contextual (soma numéricos e concatena strings).
Para facilitar a vida, é interessante usar um id nos elementos:
Nome:
<input type="text" id="nome" name="nome" maxlength="20" placeholder="Seu nome"/>

Senha:
<input type="password" id="senha" name="senha" maxlength="25" placeholder="senha"/>

<input type="button" value="Aceitar" onClick="aceitar()">

Assim, você pode usar o document.getElementById para acessar os campos, e consequentemente, seu valor com .value
function aceitar() {
    var nome = document.getElementById('nome');   // Aqui pegamos o campo, e não seu valor
    var senha = document.getElementById('senha');
    // em seguida usaremos o .value para pegar o valor dos campos
    alert('Seu nome é ' + nome.value + 'e sua senha é ' + senha.value)

    // no caso especifico, poderiamos ter feito assim tambem:
    // var nome= document.getElementById('nome').value;
    // var senha = document.getElementById('senha').value;
    // alert('Seu nome é ' + nome + 'e sua senha é ' + senha)
}

Tem outras formas de acessar elementos sem id, mas o id facilita a leitura e simplifica o acesso. Poderíamos, por exemplo, ter usado document.getElementsByName, mas é retornada uma lista de nós, em vez de um elemento único, pois os nomes podem ser repetidos num mesmo documento.
Veja funcionando no CODEPEN.


text:
Q: Error on HTTP Stream PHP I have this method:
protected function _sendRequest($url, $method, Busca_Cxense_Data $data, $get = null) {
    if (! isset ( $this->_urls [$url] )) {
        throw new Busca_Cxense_Exception_Argument ( "El tipo de url enviado no es valido. (type: {$url})" );
    }
    $url = $this->_urls [$url] . $data->getUrlKey () . ($get ? "$get" : '');
    $httpConfig = array ('http' => array ('method' => $method, 'request_fulluri' => $url, 'ignore_errors' => false ) );
    if ($data->getSendJson ()) {
        $json = $this->_setJson ( $data );
        $header = "Content-Type: application/json\r\nContent-Length: " . strlen ( $json );
        $httpConfig ['http'] ['content'] = $json;
    } else {
        $header = "Content-Type: text/html";
    }
    $httpConfig ['http'] ['header'] = $header;
    $context = stream_context_create ( $httpConfig );
    $stream = fopen ($url, 'r', false, $context);
    $result = stream_get_contents($stream);
    $headers = stream_get_meta_data($stream);
    fclose($stream);
    if (! $result) {
        print_r ( $data );
        var_dump ( $url );
        print_r ( $httpConfig );
        throw new Busca_Cxense_Exception_MethodCall ( "Bad call. \nString: $json\n" );
    }
    var_dump($result); exit;
    return array ('json' => json_decode ( $result ), 'string' => $result, 'headers' => $headers );
}

As you can see, it create a context and open an stream. However, I have a error very strange. If I send this url:
http://sandbox.cxsearch.cxense.com/api/search/levelup?p_aq=query%28category^1:%22preview%20trailer%22,token-op=or%29&p_sm=idobject:desc&p_s=0&p_c=20&p_dr=title

it throws a bad request error, but if I send this other one:
http://sandbox.cxsearch.cxense.com/api/search/levelup?p_q=test&p_sm=idobject:desc&p_s=0&p_c=20&p_dr=title

it works as expected. Do I have to encode the url or something?
FIXED
I was able to figure what the problem was. I Only need to change the space for %20. And that was all...

A: 400 response is returned by remote server, so you want to see specs/contact people on that side on how to build correct query.
The urls you provide look very different and remote system might have own validation rules on values, list of provided parameters, etc. Also it might require some specific headers and/or request body.

A: I was able to figure what the problem was. I Only need to change the space for %20. And that was all...


text:
Q: Is it natural to use "last for a long time" to describe a meeting? I was having a phone call with one of my friends.

Friend: How about we hang out together this Saturday?

I: Sunday is better, because I have a meeting in Saturday morning which will probably last for a long time.

Is my response clear and natural? I meant if the meeting will be finished in one hour, we can hang out on Saturday. But the meeting is probably longer than that and it's inappropriate to have my friend wait me for that long.
Are there any other expressions more natural I could use in the context?

A: Your response is clear and natural. There are alternatives, all of which depend on your perception of probability.
Will probably last ... reads as if you think the probability is high
Will possibly last ... reads as if there is a chance of lasting but you do not know if the chance is high or low
Is likely to last ... (=more likely than not) reads as if you think the probability is higher than 50%
Might last ... admits the chance of lasting but says nothing about the likelihood.


text:
Q: Axios Put Request Not Updating Data | React Redux I have been working on a project where I am trying to update my selected data but Axios didn't Update it even after giving a success msg.
User Response it returns from axios:-
completed: true
date: "2021-02-28"
mupp_path: "PATH 1 - LIVING YOUR WHY - Build/Apply/Inspire/Spread (BAIS) – Finding & Achieving Meaning and Purpose in work and life"
project_name: "Design and Test the Training Content for the i-Infinity 3 verticals "
selected: true
task_id: 14
task_name: "This is adding a new task to chekc full inbox functionality "
task_type: "THIS_WEEK"

Actions.js
export const taskTodayUnselect = (id) => async (dispatch) => {
    try {
        dispatch({ type: types.UNSELECTED_TASK_TODAY_REQUEST });
        const { data } = await axios.put(
            selectTaskForToday,
            {
                task_id: id,
                selected: false,
            },
            {
                headers: {
                    Authorization: `JWT ${token}`,
                },
            }
        );
        if (data) {
            return dispatch({ type: types.UNSELECTED_TASK_TODAY_SUCCESS, payload: data });
        }
    } catch (error) {
        return dispatch({ type: types.UNSELECTED_TASK_TODAY_FAILURE, payload: error });
    }
};

thisweek.js
export default function ThisWeek() {

    const unselectTaskTodayAPI = (id) => {
        dispatch(taskTodayUnselect(id)).then((response) => {
            let result = response.payload;
            console.log(result);
            if (result.success === 'true') {
                notifySuccess(result.message);
                fetchTaskData(categoryID);
            }
        });
    };
const selectTask = (item) => {
        if (item.selected) {
            unselectTaskTodayAPI(item);
            console.log('unselect');
        } else {
            selectTaskTodayAPI(item.task_id);
        }
    };

return (
                                    <TaskDataComponent
                                        item={item}
                                        key={item.task_id}
                                        label="This Week"
                                        selectTask={selectTask}
                                    />
);

Don't Worry about the TaskDataComponent , it only handle the onClick function which invoke the selectedTask function


text:
Q: Cannot call a method on a null-valued expression I have a script that looks in a directory for *.bak files and moves the files to a backup directory renaming the destination directory based on a date.
In 1 environment everything works as a expected, in another it fails with 'cannot call a method on a null-valued expression' when just setting the variables.  The exact same version of PS 4.0 is running in both environments.
$SourceDir = "D:\APPS\Logs"
$DestinationDir = "D:\APPS\ServerLog_Archives\"
$files = get-childitem -path $SourceDir -Filter *.bak
$Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + "\" + $file.CreationTime.Date.ToString('dd-MMM')

If there are .bak files present $files returns the following, otherwise the variable returns NULL.

    Directory: D:\APPS\Logs

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        2017-08-25   6:38 PM     100068 jfserver5.bak
-a---        2017-08-25   6:38 PM     100068 jfserver6.bak

In 1 environment $Directory returns the destination directory whether or not $files was NULL or returned something.

D:\APPS\ServerLog_Archives\2017\20-Nov

In the other environment I get the error:

You cannot call a method on a null-valued expression.
At line:6 char:1
+ $Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Why would this work in 1 environment and not another running the same version of PS?  Perhaps there is a better way to doing this, any suggestions will be much appreciated.


text:
Q: Custom UIToolbar within UINavigationController's rightBarButtonItem disappears when popping back to view EDIT 2:
I have now fixed this issue. I was setting a custom background image for my UINavigationBar like so:
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
[imgView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NavigationBarBackground" ofType:@"png"]]];
[navBar addSubview:imgView];
[navBar sendSubviewToBack:imgView];
[imgView release];

Which was fine for the first view controller on the UINavigationController's view controller stack, but any sub views were making this code re-run and placing the custom background to the front.
The Fix:
Simply remove all your code for the custom background on the navigation controller, then EXTEND the UINavigationBar class in the following way:
Create a new .h / .m file called UINavigationBar+CustomImage. Set the .h code to:
@interface UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect;
@end

And the .m to:
#import "UINavigationBar+CustomImage.h"

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"NavigationBarBackground.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

And voila! Everything works fine now.
--- END EDIT 2 ---
I have a UINavigationController, which drills down like so:
HOMEPAGE > DETAIL PAGE > MAP VIEW

The DETAIL PAGE adds a custom UIToolbar (with three buttons) to the rightBarButtonItem within viewDidLoad like so:
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 1.0, 157.0, 44.1)];
[imgView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NavigationBarBackground" ofType:@"png"]]];
[tools addSubview:imgView];
[tools sendSubviewToBack:imgView];
[tools setTintColor:[UIColor colorWithRed:127/255.0 green:184/255.0 blue:72/255.0 alpha:1.0]];
[imgView release];

NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];

UIBarButtonItem* bi = [[UIBarButtonItem alloc] initWithTitle:@"Filter" style:UIBarButtonItemStyleBordered target:self action:NULL];

[buttons addObject:bi];
[bi release];

bi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Map.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(showMap:)];

[buttons addObject:bi];
[bi release];

bi = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Favourite.png"] style:UIBarButtonItemStyleBordered target:self action:NULL];
[buttons addObject:bi];
[bi release];

[tools setItems:buttons animated:NO];

[buttons release];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];

This displays perfectly when viewing the DETAIL VIEW page, and when I go to the MAP VIEW, the custom UIToolbar disappears (as expected), however, when going back to the DETAIL VIEW, the custom UIToolbar is no longer visible. It is there, though, as I can still tap the area where the 'Map' button should be, and it pushes me back to the MAP VIEW.
Would you know how I can get this UIToolbar to display again when going back to the DETAIL view?
I have tried rebuilding the custom UIToolbar in viewWillAppear, which has the exact same effects as above.
EDIT - This works if I put the code that builds the custom UIToolbar within the viewDidAppear method. I don't like this solution though, as the view slides back, then the custom rightBarButtonItem appears. Is this something to do with the navigation controller not being initalised before the page is displayed?

A: If it works in viewDidAppear you could try viewWillAppear. In general, I've never seen a UIToolbar set as a UIBarButtonItem, so I wouldn't necessarily expect standard behavior. Let me know how it goes.

A: Apple UI APIs often fail in unusual ways when you try to do anything even slightly unusual (even things that should work), and trying to insert a UIToolbar into a rightBarButtonItem definitely falls into my definition of "unusual".
What you really should be doing is hiding the navigation bar and adding the UIToolbar as a subview of your view controller's main view. Alternatively you could avoid UIToolbar completely and implement the buttons yourself in a custom view.


text:
Q: How to get all recurring instances for a given master id between two dates ews api I am using ews api to get all instances from a recurring series created in outlook.
Is there a way I can get no of instances between start and end date for a master item id
We can get instances by using appintment.bindtooccurrence but you have to check if start date is between those dates for each instance. This is not ideal as we have to make ews call everytime to get next instance details


text:
Q: Confused About Map Updates I'm very new to using Google Maps and very new to intricate javascript.  Bearing this in mind, I'm trying to create a web map, with a feed from USGS.  This feed is updated every 5 minutes.  I'd like to have my map refresh every 5 minutes using this same feed (which is a geojson file).
My end goal is to have this and at least one other feed displayed/updated on my map.  Over the past four days, I've gone through dozens of posts, and am at the point of being overloaded and confused.  Will someone please clear my fog?
The code I'm posting is 99% not my code, mostly I've added comments so I can figure out what's going on in the code.

    <TITLE>TEST OF MAP</TITLE>

MAP Demo

A: Though not very elegant, I used the following for the refresh. Since I'm only building a "proof of concept", refreshing the entire page is not a problem.
   function timedRefresh(timeoutPeriod) {
    setTimeout("location.reload(true);",timeoutPeriod);
   }
   window.onload = timedRefresh(60*5000);


text:
Q: How to define previous in Rails for a different model? Rails has in default .next. Is there .previous method in ruby, should i define it myself?
"#{photo.id.previous}"
I have it defined in my Photo model and it works for my photo views, but this is being used in the User views. Does it need to be defined in the User Model?
users_controller.rb
def show
    @user = User.find(params[:id])
    @photos = @user.photos.order('created_at desc').paginate(page: params[:page], per_page: 12)
end

show.html.erb (users)
<% @photos.in_groups_of(3, false).each do |group| %>

      <% group.each do |photo| %>
        <a data-toggle="modal" href=<%="#"+"#{photo.id}"%>>

            <%= image_tag(photo.picture.ad.url, class: "img-responsive") %>

        <div class="modal" id=<%="#{photo.id}"%> tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            x
          </button>
...
...
...

<a class="prev" data-dismiss="modal" data-toggle="modal" href=<%="#"+"#{photo.id.previous}"%>>
  "Previous"

<a class="next" data-dismiss="modal" data-toggle="modal" href=<%="#"+"#{photo.id.next}"%>>
   "Next"

user.rb
def previous
  #.. ?
end

A: You can find this record like this:
class User
  def self.previous_by_id(id)
    where("id < ?", id).last
  end
end

User.previous_by_id(5)
#=> #<User:0x0000000741b818 id: 4 .....>

Or if you want to define it like instance method:
class User
  def previous
    self.class.where("id < ?", id).last
  end
end

A: Ruby already has this method. For eg:
1.pred
# => 0

Check out this for more detail
And Rails also supports this. For eg:
photo.id.pred

A: class User
  def previous
    self.class.where("id < ?", id).last
  end
end

class User
  def next
    self.class.where("id > ?", id).first
  end
end

href=<%="#"+"#{photo.previous.id}"%>>

href=<%="#"+"#{photo.previous.id}"%>>


text:
Q: Double Slit -> $N$-Slit: Does Which-Way Information change in terms of number of bits? Suppose an electron is fired through a double slit.
We all agree that the electron is now non-deterministic, and will arrive at its destination in a single spot, but it will have travelled there as a wave function.
If, on the other hand, what is known as "Which Way" or "Which Path" information is extracted at one side of the double slit, the indeterminacy will not be present, and the electron will travel to its destination not as a wave function, but as an electron projectile -- a literal, self contained point particle or wave packet.

Rather than fully obtain which-way information and destroy indeterminacy, this question is about taking only some which-way information, and leaving the single electron's state only mostly indeterminate.
Starting from the simplest case I can think of (where I can think of a lot more complicated cases, and am striving for simplicity), start with three slits, and take which-way information from only one of the three slits.
What would happen? Would:

*

*Three vertical bars appear?

*One vertical bar and a double slit diffraction pattern?

*Something in between: a fuzzier triple slit diffraction than normal?

Or something else entirely?

Obviously, this question can be extended to N-slits.  And, if you wanted to try to head my follow-up off at the pass,
Could some but not all which-way information be extracted from one fringe zone without collapsing the entire fringe pattern down-range from the partial which-way collection point?

A: This WP article might clear up your thinking on Welcher-Weg disentanglement.
Suppose you have three slits, A, B, and C, and you "watch" C. When you watch slit C, the amplitude through it decoheres from the rest, so it adds to the square of the remaining amplitude, in square, as a probability; so you get case 2: a bar image corresponding to it, superposed on the diffractive pattern of the A&B amp, where interference/entanglement is still active, since you still don't know which slit between A and B was "chosen" in propagation. Working out a simple model of the situation mathematically could help you.
Any path "watched" is collapsed out; it is described by a probability, not an amplitude, and so is exempt from interference.


text:
Q: A clock cycle unwanted delay in incrementing counter withouth state machine
I am trying to run a simple counter(v_bincount) starting from 0 to the time when the s_saxis_tlast goes high. It starts counting when s_saxis_tuser_in is high. It starts from 0 however the value of the counter remains 0 for one more clock cycle even though v_bincount is a shared variable and not a signal.
p_count: process(clk)
begin
  if (rising_edge (clk)) then
     if (s_saxis_tvalid_in = '1')and (s_saxis_tready_out = '1') then
        if(s_saxis_tuser_in ='1') then
           v_bincount1 := 0;
           v_idcount1  := 0;
        else
           if (s_saxis_tlast_in = '0') then
              v_bincount1 := v_bincount1 + 1;

           else
              v_bincount1 := 0;
              v_idcount1 := v_idcount1 + 1;
           end if;
        end if;
     else
        v_bincount1 := 0;
        v_idcount1  := 0;
     end if;

  end if;
end process p_count;

A: The simulation is what you would assume. On the lowering edge of the tuser_in, it is still '1' at the clock edge.
I would suggest not to use shared variable here. Instead, have a combinatorial counter with signals which increment the value according to your wishes and then clocked process to assign the value to a register e.g.:
p_count_r : process(clk)
begin
  if (rising_edge (clk)) then
    s_bin_count_r <= s_bin_count;
    s_id_count_r <= s_id_count;
  end if;
end process p_count_r;

and in the combinatorial process use the s_bin_count_r on the right-hand side.


text:
Q: "Undefined variable: post" when attempting to use @foreach in a blade template on a fresh install of Laravel 5.7 As the title says, when I try to use @foreach($posts as $post), I get an error that $post is undefined.
I'm guessing I've probably made some simple mistake or something like that, but I haven't been able to figure out what the problem is, so I'm asking here.
It's a pretty fresh install of Laravel 5.7.
My web.php looks like this.
Route::get('/', function () {
    $posts = App\Post::all();
    return view('landing', compact('posts'));
});

I've got a landing.blade.php file in resources/views which includes a partial using @include('partials.posts'). In resources/views/partials/ there's a posts.blade.php which has this.
$foreach($posts as $post)
    {{ $post->title }}
$endforeach

And when I navigate to / in my browser, I get a Undefined variable: post error where it highlights <?php echo e($post->title); ?>, which correlates to {{ $post->title }}.
If I put <?php dd($posts) ?> before the @foreach, then it returns a collection with an array of my dummy posts, so it does seem like my posts are being passed to the view.

A: Use @foreach & @endforeach instead of $foreach & $endforeach.
Hence use @ instead of $.

A: Try this instead of what you have given for loop
@foreach($posts as $post)
    {{ $post->title }}
@endforeach


text:
Q: How to Receive data from StartContinuousRecognitionAsync() of Microsoft Cognitive speech client library Not able to find how to get data from StartContinuousRecognitionAsync() as I want to Receive data So that i can process the data only after a keyword.

A: Try this:
...

recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);

recognizer.startContinuousRecognitionAsync(cb?: () => void, err?: (e: string) => void);

//  The event recognizing signals that an intermediate recognition result is received.
recognizer.recognizing = function(s, e){
    console.log('recognizing text', e.result.text);
};

//  The event recognized signals that a final recognition result is received.
recognizer.recognized = function(s, e){
    console.log('recognized text', e.result.text);
    script += e.result.text;
};

A: You have to 'listen' to speech events to receive the speech recognition results from the speech endpoint. This is explained in the docs as well as demonstrated in the samples.
Here is a C# sample: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-recognize-speech-csharp#continuous-speech-recognition-from-a-file
For the latest set of samples, check out our https://aka.ms/csspeech/samples
GitHub repository.
An additional comment regarding this statement:

So that i can process the data only after a keyword.

The scenario for the SDK is that you transcribe an audio stream to text (more the scenario: press a button and start speaking)..It is not necessary the scenario to wait for a keyword, and start transcribing from that point on.
It is theoretical possible to 'wait for the keyword' with the SDK, more suited for this are dedicated 'keyword spotter', perhaps even with low power support! We plan to make something like this available in a future version (but no ETA yet). KWS functionality is already available in the 'Speech Device Development Kit (preview)', see here: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/speech-devices-sdk
Hope this helps
Wolfgang


text:
Q: Communicating with CashCode bill acceptor in linux I've implemented CCNET protocol to communicate with CashCode bill acceptor from my software on Linux.
Initially I spent lots of time trying to figure out why the device does not respond to the commands I'm sending. Using trial-and-error method I found the solution to set the following options for the serial port:
stty -F /dev/ttyS0 9600 cs8 -cstopb -parenb clocal -crtscts -ixon -ixoff ignpar -icrnl -opost -isig -icanon -iexten -echo

It was working on the development machine and on two another testing machines (all of them had different motherboards). However, on the third testing machine (having yet another mobo) it seems that the device is not responding again.
It is, however, working on Windows with different software on the same machine.
Under "does not respond" I mean that nothing can be read from the serial port during 10-second timeout after sending the command. The whole code is tested and working on another motherboards.
The port itself is detected by the kernel correctly as stated in dmesg:
[    1.099382] serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A
[    1.127531] 00:0b: ttyS0 at I/O 0x3f8 (irq = 4) is a 16550A

There are no warnings in dmesg regarding this serial port.
Any ideas on how to debug this issue?
The full output of "stty -F /dev/ttyS0":
speed 9600 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V;
flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

A: Problem is solved.
This model of bill acceptor is working at 19200 baud.
Switching the port to 19200 solves the problem.


text:
Q: get content of a div that contain an iframe JQuery im trying to get the content of a div generated by an editor,
the problem is that this div contain an iframe and the iframe contain a new document
here is my script
$(document).ready(function(){
        $("#save").click(function()
        {
            var txt = $("#cke_1_contents").contents();
            console.log($("#cke_1_contents").contents());
        });
});

and here is the content that i want to get

Press ALT 0 for help

    Press ALT 0 for help

        #document
        ....

i only get the div and the iframe without the content inside the iframe
thank you guys for help

A: First of all, the src attribute of your iframes are empty. If you want to load an external document into an iframe, you have to set the src attribute (at least I don't know any other sensible way).
Secondly, keep in mind iframes are subject to the same origin policy. So, if your iframe is loading content from another domain, the parent document generally won't be able to access the content of the iframe. However, there are ways around this, and I suggest  looking at the above link that covers the same origin policy in depth, as well as this link that covers iframes in depth (including how to deal with the same origin policy when using iframes.)
If you need to load content from another domain (which I don't know because your src attributes are empty), one alternative to iframes is to get the content using the proxy method. Basically you can make a HTTP request from the server side, get the content, and add it to your page right before the page is served. This can be done rather effortlessly using something such as curl in PHP.

A: CKEditor has a pretty good javascript API which you can use:
http://docs.ckeditor.com/#!/api
It can be a bit tricky to find what you need though.
See this page sto see it ina action (viewsource find the GetContents method):
http://rev.ckeditor.com/ckeditor/trunk/7596/_samples/api.html
function GetContents()
{
    // Get the editor instance that you want to interact with.
    var oEditor = CKEDITOR.instances.editor1;

    // Get editor contents
    // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#getData
    alert( oEditor.getData() );
}

A: If that new document is from somewhere else than your domain name then you can't have it. To get it you need to use server side programming. But if it's from your site then yes.
var x=document.getElementById("myframe");
var y= x.contentDocument;
y.d.body.innerHTML; //here


text:
Q: Switching macro into a function So I have a macro code from help of the teacher (this worked previously)
    %macro aBin2int 2

    push rbp
    mov rbp, rsp
    sub rsp, 8
    push rcx
    push rdx

    mov dword [%2], 0
    mov dword [rbp - 4], 0
    mov dword [rbp - 8], 2
    mov rax, 0
    mov rdx, 0
    mov rcx, 0
    mov r10, 0

    %%nxtCR:
        movzx eax, byte [%1 + r10]
       cmp eax, NULL
        je %%controlDone
        cmp eax, "0"
        jae %%adding
    %%adding:
        sub eax, "0"
        mov dword [rbp - 4], eax
        mov eax, dword [%2]
        mul dword [rbp - 8]
        add eax, dword [rbp - 4]
        mov dword [%2], eax
        inc r10
        jmp %%nxtCR
    %%completed:

    pop rdx
    pop rcx

    mov rsp, rbp
    pop rbp

    %endmacro

Now I have to call a function that calls another function.
; ******************************************************************
;  Function getIterations()
;   Performs error checking, converts ASCII/binary to integer.
;   Command line format (fixed order):
;     "-it <binaryNumber> -rs <binaryNumber>"

; -----
;  Arguments:
;   1) ARGC, double-word, value
;   2) ARGV, double-word, address
;   3) iterations count, double-word, address
;   4) rotate spped, double-word, address

So this getIteration calls
; *******************************************************************************
;  Simple function to convert ternary string to integer.
;   Reads string and converts to intger

; -----
;  HLL Call
;   bool = ternary2int(&str, &int);

; -----
;  Arguments passed:
;   1) string, address, rdi
;   2) integer, address, rsi

; -----
;  Returns
;   1) integer value (via passed address)
;   2) bool, TRUE if valid conversion, FALSE for error

aBin2int function (this read binary strings into a decial digit)
This is working okay as macro, but I am troubling with changing it into a function.
            mov rbx, qword[rsi + 16]
                mov r10, 0

        binaryCheck:
            mov rax, 0

            mov al, byte[rbx + r10]
            cmp al, NULL
            je convertBinary
            cmp al, "2"
            jae itsNoBinary

            cmp al, "0"
            jb itsNoBinary
            inc r10
            jmp binaryCheck

        convertBinary:
            mov r15, 0
            mov rdi, rbx
            mov rsi, r15
        call aBin2int

Could anyone please help me with this?


text:
Q: Joomla 2.5 duplicate session error "PRIMARY' SQL=INSERT INTO" This is the message we're receiving on the frontend
Duplicate entry '5dcf22giahsklj52uhukcdc6k5' for key 'PRIMARY' SQL=INSERT INTO `kawt1_session` (`session_id`, `client_id`, `time`) VALUES ('5dcf22giahsklj52uhukcdc6k5', 0, '1615520883')
I've tried truncating the sessions table, dropping the table and then creating a new structure with the following code
+++===============
    CREATE TABLE IF NOT EXISTS `kawt1_session` (
    `username` varchar(150) default '',
    `time` varchar(14) default '',
    `session_id` varchar(200) NOT NULL default '0',
    `guest` tinyint(4) default '1',
    `userid` int(11) default '0',
    `usertype` varchar(50) default '',
    `gid` tinyint(3) unsigned NOT NULL default '0',
    `client_id` tinyint(3) unsigned NOT NULL default '0',
    `data` longtext,
    PRIMARY KEY (`session_id`(64)),
    KEY `whosonline` (`guest`,`usertype`),
    KEY `userid` (`userid`),
    KEY `time` (`time`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
    ===============+++

A: Go to the database and find for the jos_session table ( here "jos" is prefix so you can search with your prefix and _session table )
Select that table and Repair it, it will solve the issue. https://prnt.sc/10jrzg7

A: As I discovered the issue was ONLY displayed on the homepage of the website, I switched the default home page to another menu item. This resolved the problem. Now I have to understand why this only occurred on the home page.


text:
Q: How to use QCalendarWidget with QDataWidgetMapper? I currently have my calendar widget mapped using QDataWidgetMapper like this (using PySide):
self.mapper.addMapping(self.ui.calendar, 2, "selectedDate")

And it does display the correct date when I do:
self.mapper.toFirst()

But my problem is that when I change the selected date clicking on a different date the mapping doesn't capture the change and save it to the database. In other words, the mapper does not issue a setData on the model or setModelData in case I choose to use a delegate.
What I am missing?
Edit: I found the solution. What I did above was right but the mapper wasn't auto submitting  the data. What I did was:
self.ui.calendar.selectionChanged.connect(self.ui.mapper.submit())

A: I found the solution. What I did above was right but the mapper wasn't auto submitting the data. What I did was:
self.ui.calendar.selectionChanged.connect(self.ui.mapper.submit())


text:
Q: Using Firebase with Google Business for receiving email On my personal non-business account I have created a Firebase project and set up the hosting which I am using to serve my app.
This is under domain name: Quantified-self.io
Now I would like to enable and receive emails for that domain via the Google Business (dimitrioskanellopoulos.com) account that I have for my company. I read on Google Business that I can add a secondary domain.
However, I am not sure if this will create a problem.
So if I add the domain that is used from my firebase project (quantified-self.io) to my Google Business account will things still work, or will this end up to some unexpected behavior/disaster of my firebase app?

A: I can answer this from the Firebase side at least -- Firebase Hosting is not aware of anything related to Google Business and will continue to work so long as your DNS A records are pointed at the correct IP addresses and your domain does not have CAA records preventing certificates from being created.
If adding the domain to Google Business just means adding some new TXT records for verification and/or setting e.g. MX records, you should be fine.


text:
Q: Combinatorics. A box contains 20 balls numbered $1,2,3,...,20$.
A box contains $20$ balls numbered $1,2,3,...,20$. If 3 balls are randomly taken from the box, without replacement, what is probability that one of them is the average of the other two?

Which one of these is the correct answer?

*

*7/45

*3/38

*6/155

*3/154

A: We need to determine the number $N$ of 3-tuples from this set of numbers that have the desired property that one number is the average of the other two (We also need the total number of 3-tuples from this set, but think isn't a challenging task).
Let's first think about what is needed for a number $n$ to be the average of two other numbers $a$, and $b$. Based on the definition of average, we have
$$n=\frac{a+b}{2}$$
A way to look at this equation is to say that $n$ is the midpoint of the interval $[a,b]$. Therefore, to find $N$ all we need to do is figure out how many intervals are possible for each number in our set, and then add them all up.
First, we don't need to consider $1$ or $20$, because they do not have an interval around them for this set. For the other numbers, the number of intervals just depends on the closest distance that number is from either $1$ or $20$. More specifically, we need the smaller distance of the two.
Therefore,
$$N=\sum_{n=2}^{19}\text{Min}(20-n,n-1)$$
But we can easily determine which one is the minimum for a given number. When $n\leq10$, $n-1$ is the minimum, and when $n\geq11$, $20-n$ is the minimum.
Therefore,
$$N=\sum_{n=2}^{10}(n-1)+\sum_{n=11}^{19}\text(20-n)$$
These sums should be easily manageable now. I will leave the rest of the work to you.

A: The number of 3 long arithmetic sequences is:
Let $a_d$ be a number of such sequences if difference is $d$
$d=1:\;\;\;$$(1,2,3);(2,3,4),...(18,19,20)$, so $a_1=18$.
$d=2:\;\;\;$$(1,3,5);(2,4,6),...(16,18,20)$, so $a_2=16$.
$d=3:\;\;\;$$(1,4,7);(2,5,8),...(14,17,20)$, so $a_3=14$.
$\dots$
$d=9:\;\;\;$$(1,10,19);(2,11,20)$, so $a_9=2$.
So the number of all good sequences is $2+4+...+18 = 90$. Thus the answer is $$P= {90\over {20\choose 3}} = {90\over 20\cdot 19\cdot 3}= {3\over 38}$$

A: Refer to the table:
$$\begin{array}{c|c|c}
\text{Middle (average) number}&\text{Sets}&\text{Number of sets}\\
\hline
2&\{1,2,3\}&1\\
3&\{1,3,5\},\{2,3,4\}&2\\
4&\{1,4,7\},\{2,4,6\},\{3,4,5\}&3\\
\vdots&\vdots&\vdots\\
9&\{1,9,17\},\{2,9,16\},\cdots,\{8,9,10\}&8\\
10&\{1,10,19\},\{2,10,18\},\cdots,\{9,10,11\}&9\\
11&\{2,11,20\},\{3,11,19\},\cdots,\{10,11,12\}&9\\
12&\{4,12,20\},\{5,12,19\},\cdots,\{11,12,13\}&8\\
\vdots&\vdots&\vdots\\
18&\{16,18,20\},\{17,18,19\}&2\\
19&\{18,19,20\}&1\\
\hline
\text{Total}&&2\cdot \frac{(1+9)\cdot 9}{2}=90
\end{array}$$
Hence, the required probability is:
$$\frac{90}{{20\choose 3}}=\frac{90\cdot 1\cdot 2\cdot 3}{20\cdot 19\cdot 18}=\frac{3}{38}.$$


text:
Q: Google Video API I am building a training tool for a client. They require a secure streaming server. I want to use Google Video (as part of Google Apps for Business) but I cannot find any information about the API. Can anyone help?

A: I'd second that. I wanted to use Google Video for the same thing but found out there was no API.
I used flash video files (*.flv), apache mod_h264 and a flash player from http://flv-player.net/players/mini/

A: It seems that, unfortunately, there is no API fo Google Video for Business at the moment:
http://www.google.com/support/forum/p/apps-apis/thread?tid=0be88ad2ae25cae3&hl=en


text:
Q: How to order these SQL results in a certain way? I'm making a sort of calendar of events app. There are 2 types of events shown on the users home page:

*

*nearby event - those with a schedule date within the next 3 days, or within the past 1 hour.

*normal event - those with either no schedule date, or a schedule date further than 3 days in the future.

This is the events table: id, user_id, content, occurs_at, created_at
Currently, I'm showing these events ordered by date created to show the newly added stuff first.
What I want is to show all nearby events first and have them ordered by schedule date, then show the normal events and have them ordered by date created. I think it makes for a better user experience, but I don't know how to go about it.
UPDATE
Ended up going with this query, which is a combination of a couple of answers.
ORDER BY COALESCE(occurs_at > :min_time AND occurs_at < :max_time, 0) DESC, occurs_at ASC, created_at DESC

A: order by clauses can contain arbitrary logic, not just field names, so, in pseudo-code, you could have
SELECT ...
...
ORDER BY (date_diff(occurs_at, now) <= '3 days'), occurs_at DESC, created_at DESC

the first clauses forces all events that occur within the next 3 days to the top of the list. the second clause then orders those in descending order, then everything else gets sorted by the created_at date.

A: As @MarcB mentions, you can order by an expression, although for PostgreSQL, the expression looks somewhat different;
SELECT * FROM Events
ORDER BY CASE WHEN (occurs_at - '3 days'::interval) < CURRENT_TIMESTAMP
         THEN occurs_at
         ELSE '9999-01-01'::timestamp
         END, created_at;

SQLfiddle demo.
Note, the '9999-01-01' is somewhat kludgily an arbitrarily selected date far into the future, if anyone knows a PostgreSQL constant for "maxdate", I'd be interested :)

A: Verbose format
Easier to explain / understand.
WITH x AS (
   SELECT *
        , COALESCE(occurs_at <= (now() + interval '3 days'), FALSE) AS nearby
   FROM   events
   WHERE  occurs_at >= now() - interval '1 hour' -- exclude older events
      OR  occurs_at IS NULL
   )      -- CTE is not strictly necessary, just to make ORDER BY clearer
SELECT *
FROM   x
ORDER  BY
       nearby DESC
     , CASE WHEN nearby THEN occurs_at ELSE created_at END

It's not defined explicitly in the question, but the mentioned "no schedule date" makes me assume that occurs_at can be NULL. So use COALESCE, or FALSE and NULL will be sorted differently.

*

*First, order by nearby calculated in the CTE x.

*Next, order by the respective date (occurs_at or created_at).

*

*occurs_at cannot be NULL for nearby events.

*And I assume created_at is defined NOT NULL to begin with. Else you would have to decide where to put NULL values.

Other answers here suggest to calculate values based on columns before comparing it to a constant, which can lead to very poor performance. Example:
date_diff(d,occurs_at, now) <= 3  -- date_diff is also tSQL, not Postgres

Don't do this if you can avoid it. It forces Postgres to calculate a value for each and every row and makes it impossible to use plain indexes. More infos in this recent closely related answer.
Simple version
Shorter, a bit faster.
SELECT *
FROM   events
WHERE  occurs_at >= now() - interval '1h'
   OR  occurs_at IS NULL
ORDER  BY
       COALESCE( occurs_at <= (now()::date + 3), FALSE) DESC
     , CASE WHEN occurs_at <= (now()::date + 3)
            THEN occurs_at ELSE created_at END;

I took @Joachim's sqlfiddle, simplified the setup, added missing cases (not scheduled, occurred in the past) and ran my queries against it:
-> sqlfiddle

A: I would extend your SELECT clause by a field determining whether or not it's "nearby" (in time, not place)
SELECT
id, user_id, content, occurs_at, created_at,
case when date_diff(d,occurs_at, now) <= 3 then 1 else 0 end as isNearby
...

but I'm not sure of your syntax, this is for MS SQL Server


text:
Q: Apache File Permissions only in /tmp I'm using CentOS 7 and PHP 7.2.5. I cannot get move_uploaded_file(), file_put_contents(), or exec('cp /tmp/test.txt /var/www/html/test.txt', $out); to work in any folder except /tmp. /var/www/html is owned by apache:apache and just for permissions are 755. I tried 777 and I still get permission denied. It was stuck in systemd-private-123abc-httpd.service-11cba/tmp/ folder, but I disabled PrivateTmp for httpd.
The uploaded file is uploaded and all is well until I try to move it. I can move it to another file name in the /tmp directory but I cannot move it to any other directory.
All these work fine:
file_put_contents('/tmp/test.txt', 'TTTTTEEEESSSSTTTTT!!!!');
exec('cp /tmp/test.txt /tmp/test2.txt', $out);
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], '/tmp/'.$file);

All these give Warning: ***: failed to open stream: Permission denied
file_put_contents('/var/www/html/test.txt', 'TTTTTEEEESSSSTTTTT!!!!');
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], '/var/www/html/'.$file);
exec('cp /tmp/test.txt /var/www/html/test2.txt', $out);

And again, /var/www/html is owned by apache:apache and set to 755 permissions. I am completely baffled. All this code worked fine on the old server but absolutely refuses to work on new server. I've looked and looked, but if the answer is out there, it's blocked by too many answers about standard file/directory permissions.
The exec('cp /... doesn't actually give warnings or errors. It works or does not work. It can copy within the /tmp directory but nowhere else.

A: As mentioned in the comment above, SELinux was the problem. I disabled it and everything worked as expected. I didn't want to leave it off so I tried to set rules that would allow what I need, following these directions. That gave me errors "semanage: error: unrecognized arguments: /var/www/html/test.txt"
I ran semanage fcontext -l > output.txt and checked out the file. There was already a rule (for WordPress and/or Drupal) to allow read/write for any directory in /var/www/html named "uploads"
/var/www/html(/.)?/uploads(/.)?                  all files          system_u:object_r:httpd_sys_rw_content_t:s0
So, I moved my destination directory to a directory with "uploads" in the path.
mv -f /var/www/html/shared/pics/* /var/www/html/shared/uploads/pics
I chowned it all to apache:apache and set the permissions to 755 and it work as expected. So, if SELinux is giving you problems and you can't get the rules to change, find the rules and follow them.

A: If you still in trouble try disable system privateTmp.
I've try "multi-user.target.wants" solution, it have worked but after restart, but at some point, PrivateTmp go back to true.
Like my principal use of Apache2 is PHP, I finally edited php.ini and I've uncomment line sys_temp_dir.
By default system use temp dir assigned by function sys_get_temp_dir. Function sys_get_temp_dir will return "/tmp" but the truth is that your tmp files are storing at some path like /tmp/systemd-private-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-apache2.service-YYYYYY//tmp/*. So, what work for me was:
Edit php.ini (path can change between PHP versions)
sudo nano /etc/php/7.2/cli/php.ini

Then uncomment sys_temp_dir line
; Directory where the temporary files should be placed.
; Defaults to the system default (see sys_get_temp_dir)
sys_temp_dir = "/tmp"


text:
Q: How can I make ggvis legend match the graph? I have created a function which uses ggvis to graph some of the data we review regularly.  In this, the final group, "Overall" is overwritten to show as a black line with a width of 3 instead of the default.  Unfortunately, the steps I have taken to override the default do not show in the legend.  I am unsure what to do to make this work.  I have attempted to specifically call the add_legend, but that did not work.

The code used to generate this is (also with some random data):
CAL_DATE = seq(as.Date("10/1/2015", format = "%m/%d/%Y"),
               as.Date("3/31/2016", format = "%m/%d/%Y"), by = 1)
CAL_DATE = as.POSIXct(CAL_DATE)
a = data.frame(cbind(ma_AHT = round(rweibull(length(CAL_DATE),
                                       5, 500),0), CT_DS = rep("A",length(CAL_DATE))))
b = data.frame(cbind(ma_AHT = round(rweibull(length(CAL_DATE),
                                       4, 540),0), CT_DS = rep("B", length(CAL_DATE))))
Overall = data.frame(cbind(ma_AHT = round(rweibull(length(CAL_DATE),
                                             10, 475),0), CT_DS = rep("Overall", length(CAL_DATE))))
a$CAL_DATE = CAL_DATE
b$CAL_DATE = CAL_DATE
Overall$CAL_DATE = CAL_DATE

data = rbind(a, b, Overall)

plot_ma = function(x){
        x %>%
                group_by(CT_DS) %>%
                ggvis(~CAL_DATE, ~ma_AHT, stroke = ~CT_DS) %>%
                layer_lines() %>%
                filter(CT_DS == "Overall") %>%
                layer_lines(stroke := "black", strokeWidth := 3) %>%
                set_options(renderer = "canvas") %>%
                add_legend("stroke", title = "~ CT") %>%
                add_axis("x", title = "Date", title_offset = 60,
                         properties = axis_props(
                                 labels = list(
                                         angle = -50,
                                         align = "right",
                                         baseline = "middle"
                                 ))) %>%
                add_axis("y", title = "M.A. AHT (sec)")
}
plot_ma(data)

Which should generate something like below.  My only concern is how to make the legend show 'Overall' as black also.

A: Using scale_nominal and providing the range allows you to set the colors in both the graphic and the legend.
In your simple example, this is as easy as adding, e.g.,
scale_nominal("stroke", range = c("blue", "orange", "black"))
to the end of your plotting code.
It sounds like the number of groups may vary.  However, of the Overall group is always last in order (or you set it to be last via factor), you can use something similar to above and make it part of your function.  In this case, you'll want to establish a color palette that you like (and that doesn't contain black) that has enough colors for all of your groups.
Here I'll take one of the palettes given at Cookbook for R with 8 different colors.
cbPalette = c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

We can pull out the number of colors needed from the palette for a particular dataset by using the number of levels of the grouping factor.  The number of colors needed is this minus 1, as the last one will always be black.
Here's one way to calculate the number of groups need to color minus 1.
ncol = nlevels(data[["CT_DS"]]) - 1

This info can be used to pull out the first 1 to "number of levels minus 1" colors from cbPalette.
pal = cbPalette[1:ncol]

This can be used for the range argument of scale_nominal, appending "black" on to the end of the vector.
scale_nominal("stroke", range = c(pal, "black"))
This process is easily added in to your function.
plot_ma = function(x){
    ncol = nlevels(x[["CT_DS"]]) - 1
    pal = cbPalette[1:ncol]
    x %>%
        group_by(CT_DS) %>%
        ggvis(~CAL_DATE, ~ma_AHT, stroke = ~CT_DS) %>%
        layer_lines() %>%
        filter(CT_DS == "Overall") %>%
        layer_lines(stroke := "black", strokeWidth := 3) %>%
        set_options(renderer = "canvas") %>%
        add_legend("stroke", title = "~ CT") %>%
        add_axis("x", title = "Date", title_offset = 60,
                properties = axis_props(
                    labels = list(
                        angle = -50,
                        align = "right",
                        baseline = "middle"
                    ))) %>%
        add_axis("y", title = "M.A. AHT (sec)") %>%
        scale_nominal("stroke", range = c(pal, "black"))
}
plot_ma(data)


text:
Q: How can I add a dictionary of parameters into a subprocess call in python? Let's say there is a dictionary called dict in which dict['var1'] = '1' and dict['var2'] = '2' ... I am trying to find a way to add it to a subprocess call to trigger a make file. Currently I have:
subprocess.Popen(["make", "make.mk"], **dict)

From the command line, this works:
$(make make.mk var1=1 var2=2)

Is there any way to do this from a subprocess?

A: If I understand correctly, I think this is what you're looking for:
d = { 'var1': '1', 'var2': '2' }
subprocess.Popen(["make", "make.mk"] + [k + "=" + v for k, v in d.items()])

(My understanding is that you want to execute a command like make make.mv var1=1 var2=2.)