text:
Q: Converting a float to a double to an integer I have to make a project that consists of calculating the amount of coins you need to form a number. You have quartes, dimes, nickels and pennies and you need to form a number with the least number of coins possible. The number you need to form is prompted to the user.
This is very simple in Python(I implement a function to do something quick):
def calculate_change(change):
    count = 0
    change*=100
    change = int(change)
    if change // 25 != 0:
        count = change // 25
        change = change % 25
    if change // 10 != 0:
        count += change // 10
        change = change % 10
    if change // 5 != 0:
        count += change // 5
        change = change % 5
    if change // 1 != 0:
        count += change // 1

    print count

calculate_change(73)

Now, to implement this in C, I'm having some troubles. I don't quite understand how to change the float the user prompted. I need to convert it first to double, multiply by 100 and then convert to an int but I'm having troubles with it.
This is what I wrote for that:
int main(void)
{
    float n;
    do
    {
        printf("Change you need: ");
        n = GetFloat();
    }
    while (n < 0);

    n = floorf(n * 100 + 0.5) / 100;

    int change = (int) n;
    change = change * 100;
    int count = 0;

    if (change / 25 != 0)
    {
        count = change / 25;
        change =  change % 25;
    }
    if (change / 10 != 0)
    {
        count = count + change / 10;
        change = change % 10;
    }
    if (change / 5 != 0)
    {
        count = count + change / 5;
        change = change % 5;
    }
    if (change / 1 != 0)
    {
        count = count + change / 1;
        change = change % 1;
    }

    printf("%d\n", count);

}

Is there something wrong with the conversion from floats to ints in C ? The program returns incorrect results (always 0) when user prompts a number between 0 and 1.
Thanks !

A: Problem
When n = 0.5,
floorf(n * 100 + 0.5) / 100 = floorf(50.5)/100 = 50/100 = 0.5

Hence, the statement
n = floorf(n * 100 + 0.5) / 100;

does not change the value of n. Now, when you execute:
int change = (int) n;

change is set to 0. That explains why you get 0 for most values of n between 0.0-1.0.
Solution
I would replace the following lines:
n = floorf(n * 100 + 0.5) / 100;

int change = (int) n;
change = change * 100;

with
n = floorf(n * 100 + 0.5);  // Just to make sure rounding occurs properly.
                            // Thanks to Mark Ransom.
int change = (int) n;

A: You are right that you need to multiply by 100 and then convert to an int, and that's what you're doing in the python code, but in your C code you are doing it backwards - first converting to an int and then multiplying by 100:
 int change = (int) n;
 change = change * 100;

That (int) cast truncates values to the next lowest integer, so values of n between 0 and 1 will always get set to 0.
Moving the multiplication by 100 ensures that you convert from dollars (e.g. 0.56) to a floating point representation of cents (e.g. 56.0) before converting to an integer of cents e.g. (56):
int change = (int) (n * 100);


text:
Q: What is it that is so hard about ES6 modules for Node? It seems like ES6 imports for Node have been a bugbear for a while. There is the --experimental-modules flag, or options like using Babel - but AFAIK ES6 modules still aren't supported in vanilla Node.js.
Meanwhile, ES6 modules are supported by all the major browsers.
Why is that the browsers have been able to implement them, but Node hasn't?

A: Essentially, it boils down to how to get two very different module systems to work together. CommonJS (CJS) Modules are dynamic and synchronously loaded, ES Modules are static, immutable and asynchronously loaded. But no one wants to break the Node ecosystem, meaning that we want to be able to load CJS modules from ES modules and vice versa, ideally without the user having to know which kind of modules a package uses. (Currently you can't load ES modules from CJS modules, that will require a new asynchronous loading function.) Some people also want to be able to publish packages with exports in both kind of module.
Browsers didn't have any kind of modules previously, so they didn't have to make ES modules cooperate with anything. They could just do a simple implementation.
Any module system across such different environments as browsers and Node is going to have some tricky edge cases. Even though with the --experimental-modules flag Node's ES Modules implementation is largely the same as a browser's, there are still differences. For example, browsers will only load from full URLs, but Node will load packages from node_modules with only a package name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delphi C++ Indy UDP Server BytesToString does not receive correct string? I am trying to receive UDP packets from a TUIO multi-simulator. But some of the data is missing.
https://www.tuio.org/?specification
void __fastcall TMain::UDPServerUDPRead(TIdUDPListenerThread *AThread, const TIdBytes AData,
    TIdSocketHandle *ABinding)
{
    UDPData->Lines->Add(BytesToString(AData));

    for (int i = 0; i < AData.Length; i++)
        UDPData->Lines->Add((char)AData[i]);
}

When I use BytesToString(), I only get the word "#bundle" as a string, but when use the second loop I get this:
#
b
u
n
d
l
e
/
t
u
i
o
/
2
D
c
u
r
,
s
i
a
l
i
v
e
4
/
t
u
i
o
/
2
D
c
u
r
,
s
i
f
f
f
f
f
s
e
t
?
ホ
9
>

ᅳ
/
t
u
i
o
/
2
D
c
u
r
,
s
i
f
s
e
q
#
b
u
n
d
l
e
/
t
u
i
o
/
2
D
o
b
j
,
s
a
l
i
v
e
/
t
u
i
o
/
2
D
o
b
j
,
s
i
f
s
e
q
#
b
u
n
d
l
e
/
t
u
i
o
/
2
D
c
u
r
,
s
a
l
i
v
e
/
t
u
i
o
/
2
D
c
u
r
,
s
i
f
s
e
q
With each character on a separate line, of course.
So, how can I get the correct data when I don't know the encoding? I am lost here and need really help.
Also, how can I send a similar bundle data with TIdUDPClient?

A: The UDP data you showed is mostly binary data with some textual elements inside of it.  As such, you should not be converting the entire AData to a single string with BytesToString(), since it is not entirely text to begin with (well, you could, using BytesToStringRaw(), or BytesToString() with IndyTextEncoding_8bit() as the encoding, but it wouldn't really help you much to do so).
You need to break up the data into its individual components, per the protocol specificiation that you linked to (which in turn is based on the Open Sound Control protocol). Only then can you process the components as needed.  That means you need to loop through the AData byte-for-byte, parsing each byte in context, per the protocol.
For example (this is, by far, not a complete implementation, but it should give you an idea of what kind of logic is involved):
struct OSCArgument
{
    char Type;
    Variant Data;
}

struct OSCBundleElement
{
    virtual ~OSCBundleElement() {}
};

struct OSCMessage : OSCBundleElement
{
    String AddressPattern;
    DynamicArray<OSCArgument> Arguments;
};

struct OSCBundle : OSCBundleElement
{
    TDateTime TimeTag;
    DynamicArray<OSCBundleElement*> Elements;

    ~OSCBundle()
    {
        int len = Elements.Length;
        for (int i = 0; i < len; ++i)
            delete Elements[i];
    }
};

int32_t readInt32(const TIdBytes &Bytes, int &offset)
{
    uint32_t ret = GStack->NetworkToHost(BytesToUInt32(Bytes, offset));
    offet += 4;
    return reinterpret_cast<int32_t&>(ret);
}

TDateTime readOSCTimeTag(const TIdBytes &Bytes, int &offset)
{
    int32_t secondsSinceEpoch = readInt32(Bytes, offset); // since January 1 1900 00:00:00
    int32_t fractionalSeconds = readInt32(Bytes, offset); // precision of about 200 picoseconds
    // TODO: convert seconds to TDateTime...
    TDateTime ret = ...;
    return ret;
}

float readFloat32(const TIdBytes &Bytes, int &offset)
{
    uint32_t ret = BytesToUInt32(Bytes, offset);
    offet += 4;
    return reinterpret_cast<float&>(ret);
}

String readOSCString(const TIdBytes &Bytes, int &offset)
{
    int found = ByteIndex(0x00, Bytes, offset);
    if (found == -1) throw ...; // error!
    int len = found - offset;
    String ret = BytesToString(Bytes, offset, len, IndyTextEncoding_ASCII());
    len = ((len + 3) & ~3)); // round up to even multiple of 32 bits
    offset += len;
    return ret;
}

TIdBytes readOSCBlob(const TIdBytes &Bytes, int &offset)
{
    int32_t size = readInt32(Bytes, offset);
    TIdBytes ret;
    ret.Length = size;
    CopyTIdBytes(Bytes, offset, ret, 0, size);
    size = ((size + 3) & ~3)); // round up to even multiple of 32 bits
    offset += size;
    return ret;
}

OSCMessage* readOSCMessage(const TIdBytes &Bytes, int &offset);
OSCBundle* readOSCBundle(const TIdBytes &Bytes, int &offset);

OSCBundleElement* readOSCBundleElement(const TIdBytes &Bytes, int &offset)
{
    TIdBytes data = readOSCBlob(Bytes, offset);
    int dataOffset = 0;

    switch (data[0])
    {
        case '/': return readOSCMessage(data, dataOffset);
        case '#': return readOSCBundle(data, dataOffset);
    }

    throw ...; // unknown data!
}

Variant readOSCArgumentData(char ArgType, const TIdBytes &Bytes, int &offset)
{
    switch (ArgType)
    {
        case 'i': return readInt32(Bytes, offset);
        case 'f': return readFloat32(Bytes, offset);
        case 's': return readOSCString(Bytes, offset);
        case 'b': return readOSCBlob(Bytes, offset);
        // other types as needed ...
    }

    throw ...; // unknown data!
}

OSCMessage* readOSCMessage(const TIdBytes &Bytes, int &offset)
{
    OSCMessage* ret = new OSCMessage;
    try
    {
        ret->AddressPattern = readOSCString(Bytes, offset);

        String ArgumentTypes = readOSCString(Bytes, offset);
        if (ArgumentTypes[1] != ',') throw ...; // error!

        for (int i = 2; i <= ret->ArgumentTypes.Length(); ++i)
        {
            OSCArgument arg;
            arg.Type = ArgumentTypes[i];
            arg.Data = readOSCArgumentData(arg.Type, Bytes, offset);

            ret.Arguments.Length = ret.Arguments.Length + 1;
            ret.Arguments[ret.Arguments.High] = arg;
        }
    }
    catch (...)
    {
        delete ret;
        throw;
    }

    return ret;
}

OSCBundle* readOSCBundle(const TIdBytes &Bytes, int &offset)
{
    if (readOSCString(Bytes, offset) != "#bundle")
        throw ...; // error!

    OSCBundle *ret = new OSCBundle;
    try
    {
        ret->TimeTag = readOSCTimeTag(Bytes, offset);

        int len = Bytes.Length;
        while (offset < len)
        {
            OSCBundleElement *element = readOSCBundleElement(Bytes, offset);
            try
            {
                ret->Elements.Length = ret->Elements.Length + 1;
                ret->Elements[ret->Elements.High] = element;
            }
            catch (...)
            {
                delete element;
                throw;
            }
        }
    }
    catch (...)
    {
        delete ret;
        throw;
    }

    return ret;
}

void __fastcall TMain::UDPServerUDPRead(TIdUDPListenerThread *AThread, const TIdBytes AData,
    TIdSocketHandle *ABinding)
{
    int offset = 0;

    if (AData[0] == '/')
    {
        OSCMessage *msg = readOSCMessage(AData, offset);
        // process msg as needed...
        delete msg;
    }
    else if (AData[0] == '#')
    {
        OSCBundle *bundle = readOSCBundle(AData, offset);
        // process bundle as needed...
        delete bundle;
    }
    else
    {
        // unknown data!
    }
}


text:
Q: Can't clone, can SSH. "Permission denied (publickey)." I cannot clone or push to a repository on my server.
I have a bare repo that is located is a directory user@host in directory home/user/test.git that I am trying to access via git clone. I used ssh-add <pathtokey> to add my ssh key. It asked me for the passphrase.  I can then ssh user@host successfully.
However if I then try to git clone ssh://user@host/~/test.git I get:
Cloning into 'test'...
user@host: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

also tried

*

*git clone ssh://user@host/home/user/test.git

*git clone user@host:home/user/test.git

*git clone user@host:/home/user/test.git
with the same result
I am guessing the git credential manager isn't picking up the keys?
On the server /var/auth/log says
Feb 20 02:25:36 xxxxx sshd[24674]: Connection closed by authenticating user XXXX x.x.x.x port 56433 [preauth]

*

*Git version: git version 2.30.1.windows.1

*Git Credential Manager: Git Credential Manager version 2.0.318-beta+44acfafa98 (Windows, .NET Framework 4.0.30319.42000)

*git config -l reports credential.helper=manager-core

*Tried both PowerShell and git bash shells, same result

*user has read, execute permissions to the repo

A: To add to @VonC's response
In git-bash things work as normal.
The normal flow of starting the ssh-agent (via eval 'ssh-agent'
), adding the key via ssh-add <path_to_key> enables git clone to work.
In PowerShell Core, or Cmd, via Windows-Terminal more work is required
the ssh-agent starts automatically (assuming you previously started the OpenSSH Authentication Agent service), adding the key works, and you can ssh after this, but git commands do NOT work, initially, but if you do
git config --global core.sshCommand C:/Windows/System32/OpenSSH/ssh.exe

This will replace the (default) ssh that comes with git-for-windows with the Windows10 implementation.
After this it should work fine in things other than git-bash. Confirmed in Powershell-Core, Command Prompt
See also:
https://gist.github.com/danieldogeanu/16c61e9b80345c5837b9e5045a701c99

A: The git credential manager is only involved for caching credentials (username/password) for HTTPS URL, not SSH.
Only the ssh-agent could be involved, for caching a possible passphrase, if the private key was defined with it.
I would try first using the full path, since ~ might not be interpreted by the remote shell, but the local (which has a different path for ~):
git clone ssh://user@host/home/user/test.git
# or
git clone user@host:/home/user/test.git

If not, in a git bash session, type:
export GIT_SSH_COMMAND='ssh -v'
git clone ...

The OP confirms in the discussion it works in a bash session:

In git bash, I started the ssh-agent,
added the key there, then it worked.


text:
Q: JSON Representation of a Backbone Model Forking a json file using fetch method triggers error in my code. Seems the response from the server is not right. Into the details, for the ads model below
//Advertisement model
App.Tasks.Model.Ads = Backbone.Model.extend({
    url: "ads/ads.json",
    intialize: function () {

    },
    Next: function () {
        var ads = this.get("ads");
        return ads[Math.ceil(Math.random(0, ads.legth) * 10)];
    }
});

how should the server response be when calling fetch(). Right now it is as below
{ads: ["1.png", "2.png", "3.png"]}

and doing this triggers the error callback
//Advertisement model
App.Tasks.Ads = new App.Tasks.Model.Ads();
App.Tasks.Ads.fetch({
    success: function (model, response) {
        console.log("Success", arguments);
    },
    error: function (model, response) {
        console.log("Error", arguments);
    }
});

A: Your server responds with an invalid JSON, the left part in a name/value pair must be a string, which means that ads should be wrapped in double quotes:
{"ads": ["1.png", "2.png", "3.png"]}

For the complete reference, check http://www.json.org/


text:
Q: putting X on an element to remove an element from
* list Currently, this is what i have

At the moment, the element can be dragged and dropped (at the moment, there is no listener to capture if it's dropped into a specified area)
HTML

JQUERY

Ideally, I would like to have this.

A) Can someone point me to the right direction as to how to put an X at the end of the element so that the user can click on the X to remove it from the list.
B) Or, show me how to drag an unwanted element and drop it outside the list area to remove it.

A: You will have to do some styling yourself. But here's an example:
# Example HTML

#Example CSS (you will have to do some styling yourself. You could for example use an image for the x or something)
#sortable .ui-state-highlight span {
    position: absolute;
    left: 2px;
    height: 10px;
    width: 10px;
    background-color: white;
}

# Untested, but this should be corret (tho, untested)
$('#sortable').on('click','.ui-state-highlight span',function () {
    $(this).parent().remove();
});


text:
Q: "can't find gem" error when trying to create a new rails 5.1.4 project rails new works fine. However, when I try to create a new rails project using rails _5.1.4_ new I get this error:
can't find gem railties (= 5.1.4) with executable rails (Gem::GemNotFoundException)

I'm using rbenv on Ubuntu 18.04
I'm running a rails 5.1.4 project on this PC, which works fine, just creating a new one doesn't work.

A: The error suggested that you don't have Rails 5.1.4 installed in your system. Try install it by gem install rails -v 5.1.4 and then rails _5.1.4_ new NewAPP again.


text:
Q: ng-submitted class is not added on sub form fiddle: https://jsfiddle.net/stevemao/zc6htcob/
a class ng-submitted should be added on the ng-form directive when hitting the Submit button. What am I missing?

A: Just take a look at this: https://github.com/angular/angular.js/issues/10071
It is a known issue and you can find several workarounds there.


text:
Q: ASP NET - C#: Access controls by Id In my ASP.Net project; I'm using C# as behind code.
One of my project functions creates some text boxes dynamically, according to user's needs. Each textbox has a different Id.
My question is how can I access those textboxes by Id?
Let say that were created 5 textboxes, how can I edit the code of specifically one of them?
Bellow is the actual code that I use to generate those textboxes:
int name_id = 1;
foreach (WebApplication5.ServiceReference1.ClientData client in Clients)
{
    TextBox1 = new TextBox();
    TextBox1.ID = name_id.ToString();
    TextBox1.Style["Position"] = "Absolute";
    TextBox1.Style["Top"] = y + "px";
    TextBox1.Style["Left"] = x + "px";
    TextBox1.Text = client.descricao;
    Form.Controls.Add(TextBox1);

    name_id++;
    x = x + 10;
    y = y + 10;
}

A: You can do this in code behind;
TextBox tb1 = (TextBox)FindControl(name_id)

A: TextBox tb = Form.FindControl(TextBox1.ID) as TextBox

Only like this, the reson why you can't access by ID directly is they absent at *.designer.cs.


text:
Q: JQuery selector for a non-option element with attribute named "selected" in IE8-IE9 Well I have an html table with some TRs something like these bellow

...

...

and there is a simple selector
var a=$("#"+tableId).find("[selected='TRUE']");
or
var b=$("#"+tableId + " tr[selected='TRUE']");

which in Firefox returns the TRs with selected='TRUE' but in MSIE 8-9 it returns nothing. I guess the problem is that the attribute "selected" is not supposed to be used by TRs and IE finds it invalid or something like this.. but the code bellow returns the value of the attribute selected..
var c=$("#" + tableId + " tr").first().attr('selected');

There is also something noticeable that this code works with JQuery 1.4.2 also in IE. By upgrading to JQuery 1.8.3 it works only in FF.
Changing the name of the attribute is a solution that I would like to avoid for some reasons.
The solution that I have in mind is a loop "for each tr, if selected='true' add tr in var a".
Is there a better suggestion?

A: First you have duplicate IDs which should be unique. Secondly you can select rows with tr[selected="true"]'
And instead of that attribute you should use data-selected so you have a valid markup.

A: I'll suggest to use .prop() instead with jq 1.8.3, but really not sure it can help you here:
var $trsSelected = $("#"+tableId).find('tr').filter(function(){return $(this).prop('selected')=='TRUE'});

var $trsNotSelected = $("#"+tableId).find('tr').filter(function(){return $(this).prop('selected')!='TRUE'});


text:
Q: Oracle SQL Automation with Jenkins and Git I have a remote Oracle SQL server with scripts updated in a git repository. I am trying to use Jenkins to run a job pull down the updated scripts after each commit and then connect to the Oracle SQL server and then run the scripts and then send out an email with a response. I have the email part down but I am having trouble figuring out how to do this or if it's possible. I'm not locked into Jenkins for this tasks so would be willing to use some other free service.
Currently I having issues connecting to the database and figuring out how to actually pull the updated scripts from the git repository

A: Jenkins should be able to handle your issue. If you want to pull changes after each commit to SCM, then you need to configure a webhook between your repository and Jenkins. The way you do this will vary depending on which provider you use. For example, if you use GitLab, then there is official documentation on how to integrate with Jenkins.
Alternatively, you could do this using the API without using webhooks. Refer to this answer for that.
Once you have the pulling part complete, you can move on running your scripts in SQL. For this, I recommend using sql plus. You can easily install it on your Jenkins host and use simple commands to interact with the Oracle database. For example, in order to deploy a file called script.sql, you would use:
sqlplus <username>/<password>@<DB_HOST>/<DB_SID> @<script.sql>


text:
Q: Windows service and Electron native windows app communication using window messages I have an windows service sending windows message such as HWND messages, i need to recieve these messages on the electron app and perform some action. How to achieve this?
The service finds a window by its name and postmessages to that window. But how does electron recieve that message?
Below is my service code
const int wm_app = 0x0400;
int openFile = 0x065;
IntPtr hwnd = FindWindow(IntPtr.Zero, "electron Browser window name");
PostMessage(hwnd.ToInt32(), (wm_app + openFile), 0, 0);

A: You can add a hook to the BrowserWindow to listen for the Windows message.
browserWindow.hookWindowMessage(0x465, (wParam, lParam) =>
    // Your function here
})


text:
Q: How to run custom codeunit when user uninstalls custom extension We have an extension that creates a Job Queue Entry to ensure that custom table values based on certain rolling dates stay in sync. The extension also creates some PermissionSets. When the extension is uninstalled, the Job Queue Entry needs to be deleted and the PermissionSets need to be removed from any users to which they were assigned.
The Codeunit class exposes a Subtype property but the non test values are only Normal, Insert and Upgrade. I was expecting an Uninstall and/or Unpublish Codeunit as well.
How do I detect a user extension uninstall so I can remove the items in question?

A: The feature you are looking for does not exist at the moment. It is on the product backlog as far as I know.
There are several issues on Github where people request the feature:
Issue 191
Issue 1271


text:
Q: NSNumber numberFromString not placed decimals I am trying to convert NSString to NSNumber and it seems to create a decimal point issue here.
NSString *str = @"515.51515";

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:str];
NSLog(@"Number here:%@",myNumber);
[f release];

& result print is
2015-03-01 08:09:28.353 myApp [57376:2086924] Number here: 515.5151499999999
Actual debug log picture here

but actually it should be 515.51515 rather 515.5151499999999.
I tried all comibination with f.usesSignificantDigits & f.maximumFractionDigits =10 but no luck.
please let me know How to fix this?

A: RMaddy is correct, floating point numbers will be a bit off.
Since an NSDecimalNumber is an NSNumber you can use:
NSNumber *number = [NSDecimalNumber decimalNumberWithString:@"515.51515"];

A: Try to use construction:
NSNumber *myNumber = [NSNumber numberWithFloat:[str floatValue]];

I think it should work correctly.


text:
Q: Unable to assign a Session variable value from within a Class file I am getting this error trying to assign a session value from within a Class file in VB, VS2012.
Object reference not set to an instance of an object.

I have tried both lines of code below and get the same error.
System.Web.HttpContext.Current.Session("dbTblName") = dbTblName

HttpContext.Current.Session("dbTblName") = dbTblName

The dbTblName variable is populated with a string value. the function class is called from a call into a web service.
Ah I think I am seeing it, there is no http here. Duh!

A: Its most likely because the HttpContext object which the Session belongs to is not accessible to you within this scope or context at the time of assignment.
Why not check if the HttpContext is available before assigning it. However if you can provide more information with regards to the class and where you are calling it then better help can be provided
UPDATE:
If you are calling this within a service a method attribute might be needed on the service object to enable the session object as this is not enabled by default:
[WebMethod(EnableSession = true)]
public void CallingMethod()
{

}


text:
Q: How to create a csv file format definition to load data into snowflake table I have a CSV file, a sample of it looks like this:
Image of CSV file
Snowpipe is failing to load this CSV file with the following error:

Number of columns in file (5) does not match that of the corresponding table (3), use file format option error_on_column_count_mismatch=false to ignore this error

Can someone advise me csv file format definition to accomodate load without fail ?

A: The issue is that the data you are trying to load contains commas (,) inside the data itself. Snowflake thinks that those commas represent new columns which is why it thinks there are 5 columns in your file. It is then trying to load these 5 columns into a table with only 3 columns resulting in an error.
You need to tell Snowflake that anything inside double-quotes (") should be loaded as-is, and not to interpret commas inside quotes as column delimiters.
When you create your file-format via the web interface there is an option which allows you to tell Snowflake to do this. Set the "Field optionally enclosed by" dropdown to "Double Quote" like in this picture:

Alternatively, if you're creating your file-format with SQL then there is an option called FIELD_OPTIONALLY_ENCLOSED_BY that you can set to \042 which does the same thing:
CREATE FILE FORMAT "SIMON_DB"."PUBLIC".sample_file_format
    TYPE = 'CSV'
    COMPRESSION = 'AUTO'
    FIELD_DELIMITER = ','
    RECORD_DELIMITER = '\n'
    SKIP_HEADER = 0
    FIELD_OPTIONALLY_ENCLOSED_BY = '\042' # <---------------- Set to double-quote
    TRIM_SPACE = FALSE
    ERROR_ON_COLUMN_COUNT_MISMATCH = TRUE
    ESCAPE = 'NONE'
    ESCAPE_UNENCLOSED_FIELD = '\134'
    DATE_FORMAT = 'AUTO'
    TIMESTAMP_FORMAT = 'AUTO';

A: If possible share the file format and one sample record to figure out the issue. Seems issue with number of column, Can you include field_optionally_enclosed_by option into your copy statement and try it once.

A: When the TAB character is unlikely to occur, I tend to use TAB delimited files - which, also - together with a Header -, make the source files more human-readable in case they need to be open for troubleshooting loading failures:
FIELD_DELIMITER = '\t'

Also (although a bit off-topic), note that Snowflake suggests files to be compressed: https://docs.snowflake.com/en/user-guide/data-load-prepare.html#data-file-compression
I mostly use GZip compression type:
COMPRESSION = GZIP

A (working) example:
CREATE FILE FORMAT Public.CSV_GZIP_TABDELIMITED_WITHHEADER_QUOTES_TRIM
    FIELD_DELIMITER = '\t'
    SKIP_HEADER = 1
    TRIM_SPACE = TRUE
    NULL_IF = ('NULL')
    COMPRESSION = GZIP
;


text:
Q: jQuery (or JS) decodes HTML character entity in string I am trying to dynamically populate a <select> element using jQuery and option values from an array of strings returned in a JSON response. One of the option values is Joe's Cafe which when decoded is Joe's Cafe. However, when I use the following code:
$.each(optionVals, function(idx, elem) {
    $('#restaurant').append('<option value="' + elem + '">' + elem + '</option>');
});

the corresponding option is not what I expect. I see this:
<option value="Joe's Cafe">Joe's Cafe</option>

instead of this:
<option value="Joe's Cafe">Joe's Cafe</option>

How do I prevent jQuery from decoding the HTML entity ' in the .append() operation? I checked the JSON response, and the HTML entity is intact. I checked the source after the options were loaded and the HTML entity has been decoded into the single quote '.

A:
How do I prevent jQuery from decoding the HTML entity ' in the .append() operation?

You can't, because it isn't.
jQuery is generating some HTML and then getting the browser to convert it to a DOM. It then appends that DOM fragment to the document DOM that represents the page.
When you examine the DOM using a DOM inspector (or when you use innerHTML to convert it to a string) you are serialising the DOM to HTML. At this point the browser does not know (because it hasn't kept track, because it doesn't need to) if the apostrophe in the DOM came from a literal apostrophe or a character reference for one. The algorithm it uses to decide how to represent the character uses the literal one (there is no point in it using a 5 character code when it can use 1 more readable character instead).
<option value="Joe's Cafe">Joe's Cafe</option> and <option value="Joe's Cafe">Joe's Cafe</option> are two different ways of writing exactly the same thing in HTML. Which you get should not matter.

It may be the same thing in HTML but it is completely different when stored in a database.

It sounds like you want the form to submit the string Joe's Cafe to the server.
<option value="Joe's Cafe">Joe's Cafe</option> would not do that.
That would require: value="Joe&#39;s Cafe"
Now you can achieve that by generating your DOM sanely instead of mashing strings together (because when you mash strings together, characters with special meaning in HTML get treated as having that special meaning).
$('#restaurant').append(
    $("<option />").val(elem).text(elem)
);

however your implication is that having raw apostrophes in the data is breaking your SQL.
That means you are vulnerable to SQL injection attacks and that the real solution is to fix this server side.
See How can I prevent SQL-injection in PHP? or look up how to use prepared statements to prevent SQL injection in whatever programming language you are using on server.

A: In order to avoid HTML entitites to be decoded, you can replace globally & by & in your strings:

var optionVals = ["Joe's Cafe"];
$.each(optionVals, function(idx, elem) {
    elem = elem.replace(/&/g, "&");
    $('#restaurant').append('<option value="' + elem + '">' + elem + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="restaurant"></select>


text:
Q: Is there a way to increment all fields in a Redis hash at once? I want to use Redis to cache a large amount of highly dynamic counters. In my case users are subscribing to sources and I want to cache each user's counter for that source. When a new item arrives at the source it's natural that the counters for all users subscribed to this source should be incremented by 1. Some sources have hundreds of thousands of subscribers, so it's important that this happens immediately.
However, Redis doesn't have a native method to increment all hash fields at once, only HINCRBY. Is there a solution for this?
While searching, I stumbled upon some threads where people wanted a bulk version of HINCRBY, but my case is different. I want to increment all fields in the hash.

A: Such operation should be achieved by using LUA script see:

*

*https://redis.io/commands/evalsha

*https://redis.io/commands/eval
You can use LUA script to "batch" couple of operations on a single hash


text:
Q: Should stubs be writtnen before or after unit tests? I was discussing this with a friend, and while intuitively it would seem to make no difference, I was wondering if anyone here might come up with a good reason to write the stub before or after the unit tests.

A: I think it doesn't really matter, as long as in the end you have both so the code compiles (or, in the case of interpreted languages, doesn't raise a method not found error).
However, since this is test-driven development, it makes sense to focus on these and write them first. Sometimes, even if I have a clear idea of how I want to structure my code, only while writing the tests do I realise that the API is useless and end up changing it. Writing the stubs after having written the tests makes this more easy.

A: If you are doing TDD, you will write your tests first and concurrently implement any required test infrastructure such as stubs so that you will be able to do state-based verification on the stubs after you exercise your test subject (also known as System Under Test or SUT).
Hard for me to envision writing stubs before the tests that will need them, but maybe that could work better for you--anyway, it can be difficult to grasp TDD as a style of working, so my advice is to keep at it and figure out what works best for you.
Personally, I hardly ever think of stubs anyway, as testing with mocks is they way I like to work (behavior-based verification rather than state-based). You don't mention what tools you are using; perhaps a good toolkit for mock objects isn't readily available for your tools (although I doubt you'd have trouble finding something for most languages now). Still, I can think of quite a few mock object libraries for, say, Java work and really I only have patience for one or two of them, so again it makes sense to experiment and discover what you like best.


text:
Q: MongoDB optimized way to select document count change timeline I want to select the progress of changing the number of documents for each day of the current week.
Users collection (very schematically): { _id, username (str), social (obj, default: null), createdAt (int timestamp) }

I need to select this data:
// Count of the new documents per each day. Example of the data I need:
{
  all: { // Social field is null
     timeline: [Monday: 1, Tuesday: 0, Wednesday: 4, Thursday: 26, Friday: 24, Saturday: 30, Sunday: 47]
  },
  social: { // Social field is not null
     timeline: [Monday: 0, Tuesday: 0, Wednesday: 2, Thursday: 8, Friday: 5, Saturday: 16, Sunday: 9]
  }
}

Better way will be if this was aggregator.
Here is my not optimized code:
    let obj = { all: { timeline: [] }, social: { timeline: [] } }

    const mondayStartTime = getMonday(new Date()).getTime();
    const weekDaysStartTime = getWeekDaysStartTime(mondayStartTime);

    const this_week_registered = await (
        await users_collection.find({ createdAt: { $gte: mondayStartTime } })
    ).toArray();

    for (let i = 0; i < weekDaysStartTime.length; i++) {
        obj.all.timeline.push(
            this_week_registered.filter((obj) =>
                obj.createdAt >= weekDaysStartTime[i] && weekDaysStartTime[i + 1]
                    ? obj.createdAt < weekDaysStartTime[i + 1]
                    : true,
            ).length,
        );

        obj.social.timeline.push(
            this_week_registered.filter((obj) =>
                obj.social && obj.createdAt >= weekDaysStartTime[i] && weekDaysStartTime[i + 1]
                    ? obj.createdAt < weekDaysStartTime[i + 1]
                    : true,
            ).length,
        );
    }

I need to make this in one query.


text:
Q: In context to executable compression, are compression softwares like 7ZIP/Winzip considered as executable packers? A packer is a tool that compresses an executable file and combine the compressed data with decompression code into a single executable. They are also used to obfuscate malwares. As per my understanding this can also be achieved by using compression softwares such as 7zip/winzip. The list of "Known executable compressors for Portable Executables" on this Wikipedia page does not include softwares such as 7Zip/Winzip.
So are these softwares in any way different from packers ?

A: Resolved!
In case of .zip compression user manually extracts the files from the archive whereas the packed executable is like a self extracting archive it contains both packed code and the code required to unpack it. It automatically unpacks itself when executed.


text:
Q: How do I add different classes to  in Javascript Hey I have two td elements in a table.
I want the have separate style classes for them. How do I do this?
This is my code:
table += "
";
  for(var i = 0; i < data.list.length; i++){
    table += "" + "
" + "" + value1 "	" + "" + value2 + "	" + "
";
  }
table += "
";

I have tried to simply add class in td element but that does not work.
Any ideas? I use Javascript to create the table.
So this does not work:
table += "
";
  for(var i = 0; i < data.list.length; i++){
    table += "" + "
" + "" + value1 "	" + "" + value2 + "	" + "
";
  }
table += "
";

A: You should be using single quotes inside double-quoted strings, like this
table += "
";
  for(var i = 0; i < data.list.length; i++){
    table += "" + "
" + "" + value1 "	" + "" + value2 + "	" + "
";
  }
table += "
";


text:
Q: Are there issues inherent to running dual 6-core processors on a 2009 Mac Pro vs a 2010? I'm shopping around for a pre-loved Mac Pro with dual 6-core "Westmere" processors. Finding a decently priced 2010 base model is a lot harder than finding a 2009 with upgraded processors.
In talking to Mac Pro refurbishers, some tell me that one should not upgrade a 2009 Mac Pro with the 6-core "Westmore" processors for reasons of it not being as stable as the 2010 Mac Pro 6-core machine. Some tell me that it will cause the fan to run all the time. Others say there's no problem at all upgrading a 2009 Mac Pro with dual 6-core "Westmere" processors.
My question is, are there any inherent problems or disadvantages to upgrading a 2009 Mac Pro with dual 6-core "Westmere" processors vs starting with a 2010 Mac Pro and doing the same? The later is harder to come by and thus more expensive.

A: Too long to be a comment, yet not conclusive enough to be an answer - but I'd like to throw in a couple of my experiences, even if I have no comparison.
I've never had a 'real' 5,1 but I do have a 3.46GHz Westmere upgraded 4,1.
To all intents & purposes everything except the front page of About this Mac considers it a 5,1.

I've always noticed a temperature discrepancy between the two processors - ref Mac Pro CPU temperature discrepancy - [which reached no solid conclusion] though it's never seemed to cause any problems, it just bothers my inner geek a bit.
I think the CPU fans always run a little fast, though again not enough to cause issues & it can be compensated by running the intake fans a little faster.
Intake at default 600

Intake at 800

Intake at 1000

I also had an issue with the Security update last year - Security update 2016-003 10.11.6 issues - [which again has no actual answer] I have no idea if it's related, but I ended up not having the update installed.
I have yet to dare attempt the recent 2017 security update. I might bite the bullet today & risk it.
It will run Sierra with no apparent issues, except that it's Sierra :/ [I really don't like that it breaks more than it fixes & it adds no user benefit for me.]


text:
Q: How should i license my application? I developed c# winform application which monitors database and I want to license it.
License will be concurrent based. Standart license 2 concurrent users, Premium users 5 concurrent users.
I want to check license in online. Which means that users need internet connection to use my application.
However this will be database monitoring tool and some companies may not allow internet connection.
I want to hear your thoughts. What do you think about this?

A: It seems that the classical serial number technique could be a solution here.
The technique is similar to what is used by Microsoft to activate a copy of Windows:

*

*During installation, the user is presented with a serial number prompt.

*If there is an internet connection, the setup application confirms the serial number by querying the licensing server.

*If no internet connection is available, the setup halts, shows a series of numbers and an offline unlock code prompt, and asks the user to call a phone number to get the offline unlock code from the series of numbers.
Depending on the serial number, the setup will be able to install either a standard version or a premium version of the app.

Make sure you understand that it will be possible to bypass any solution you'll implement. Companies such as Microsoft or Adobe wasted millions of dollars on anti-piracy measures; their products are still installed illegally all over the world.
It's up to you to decide how much money you are ready to spend on licensing. For many products, the best ROI would be achieved by a simple sentence explaining that if the companies are found installing illegal copies of software and/or having more users than allowed, they will be sued, and that, even if you don't have the means to detect the illegal behavior and/or are unable to sue your clients.


text:
Q: webdriver python how to "click" required button What I want is to use find element to click on the line "linked formlink" that has "Assigned" type.
But whatever I use the xpath, it return me " unable to locate the element".
Does any better way to sort out the required element and proceed click operation by using webdriver python?
element2 = driver.find_element_by_xpath("//a[@class='linked formlink'][]").click

the html
    INC1471130
    Assigned

A: To click() on the button with text as Assigned you can use the following line of code :
driver.find_element_by_xpath("//a[@class='linked formlink' and contains(@href,'incident.do?sys_id=')]//following::td[1]").click


text:
Q: Creating user's with batch apex which will invoke a trigger and a future method I have a trigger on user object which runs on the creation of new users of a particular profile and also has a future method called for assigning user some id's So my doubt is if I insert the user's via batch jobs will it violate governor limits?
Also, suggest a workaround if possible to streamline the process.
Note I have around 3000 users which need to be inserted.

A: You can Use static variable to turn off Trigger during batch processing: remember that statics are class members, not object instances. If You need trigger logic You can implement Your triger to process Users bulk-way to not shoot the limit, or You can turn of trigger with static  variable mentioned above and implement similiar logic in batch which has higher limits. If You need more explaination feel free to ask.


text:
Q: Invalid appId Bing Translate (WP7)
ArgumentException: Invalid appId Parameter name: appId :
  ID=3737.V2_Soap.Translate.30597BC0

I am getting the above error message everytime I try to run the translate service.
The error is pointing me to the below c# code for references.cs
public string EndTranslate(System.IAsyncResult result) {
                object[] _args = new object[0];
                string _result = ((string)(base.EndInvoke("Translate", _args, result)));
                return _result;
            }

I am using this on windows phone 7 and it had worked previously but now i am getting this error.

A: Actually, it is because of this.

Back in September 2011, we deprecated the use of Bing AppIDs for the
  Translator service. In reality, existing and new AppIDs continued to
  work until yesterday. We have now disabled the use of new Bing AppIDs:
  requests using a Bing AppID that has not been used with the Translator
  service before March 31, 2012 will be denied.
Please upgrade to the secure method of Azure Marketplace tokens.

I have the same error, I am working now to obtain that new token from Azure Translate.


text:
Q: @RequestParam name includes square brackets [] I am writing a feign client to consume an endpoint of a PHP API.
I need to call an endpoint which is like  :

www.myapp.com/number.php?number[]=1

My Feign Client looks like this:
@FeignClient(name = "testProxy", url = "${service.url}")
public interface NumberProxy {

    @RequestMapping(value = INumber.URL, method = RequestMethod.GET)
    public String getEvents(@RequestParam("numbers[]") Integer number);
}

The problems is number[].
If I see the feign log to check the GET URL, this is what I see.
GET [https://www.myapp.com/number.php?number[]={number[]}][1] HTTP/1.1

The number[] is not replaced by the actual value and that is what the API call is failing.
Is there a way to deal with this?
P.S.
I know that the PHP API should not have a query parameter like this, but it is what it is and I can not change that.
And I have also tried with List<Integer> for the number variable, but output is same.

A: Are we talking about a org.springframework.web.bind.annotation.RequestParam if so it shouldn't be the problem of square brackets. For me it works fine:
@RequestMapping(value = "/api/somepath", method = RequestMethod.POST)
  public void uploadData(
      @RequestPart("file") MultipartFile fileUpload, HttpServletRequest request,
      HttpServletResponse response, @RequestParam(name = "param[]") Integer number) {
  LOGGER.trace("paramValue=[{}]", number)
}

logs a value passed through a client
What if the problem is in parameter naming? In the first occurence you write numberS[] but further it named as number[]

A: You should name your parameter just as numbers without the brackets and change the type to a List:
@RequestMapping(value = INumber.URL, method = RequestMethod.GET)
public String getEvents(@RequestParam("numbers") List<Integer> number);


text:
Q: Theory behind partial least squares regression Can anyone recommend a good exposition of the theory behind partial least squares regression (available online) for someone who understands SVD and PCA?  I have looked at many sources online and have not found anything that had the right combination of rigor and accessibility.
I have looked into The Elements of Statistical Learning, which was suggested in a comment on a question asked on Cross Validated, What is partial least squares (PLS) regression and how is it different from OLS?, but I don't think that this reference does the topic justice (it's too brief to do so, and doesn't provide much theory on the subject).  From what I've read, PLS exploits linear combinations of the predictor variables, $z_i=X \varphi_i$ that maximize the covariance $ y^Tz_i $ subject to the constraints $\|\varphi_i\|=1$ and $z_i^Tz_j=0$ if $i \neq j$, where the $\varphi_i$ are chosen iteratively, in the order in which they maximize the covariance.  But even after all I've read, I'm still uncertain whether that is true, and if so, how the method is executed.

A: Section 3.5.2 in The Elements of Statistical Learning is useful because it puts PLS regression in the right context (of other regularization methods), but is indeed very brief, and leaves some important statements as  exercises.  In addition, it only considers a  case of a univariate dependent variable $\mathbf y$.
The literature on PLS is vast, but can be quite confusing because there are many different "flavours" of PLS: univariate versions with a single DV $\mathbf y$ (PLS1) and multivariate versions with several DVs $\mathbf Y$ (PLS2), symmetric versions treating $\mathbf X$ and $\mathbf Y$ equally and asymmetric versions ("PLS regression") treating $\mathbf X$ as independent and $\mathbf Y$ as dependent variables, versions that allow a global solution via SVD and versions that require iterative deflations to produce every next pair of PLS directions, etc. etc.
All of this has been developed in the field of chemometrics and stays somewhat disconnected from the "mainstream" statistical or machine learning literature.
The overview paper that I find most useful (and that contains many further references) is:

*

*Rosipal & Krämer, 2006, Overview and Recent Advances in Partial
Least Squares
For a more theoretical discussion I can further recommend:

*

*Frank & Friedman, 1993, A Statistical  View  of  Some  Chemometrics  Regression Tools

A short primer on PLS regression with univariate $y$ (aka PLS1, aka SIMPLS)
The goal of regression is to estimate $\beta$ in a linear model $y=X\beta + \epsilon$. The OLS solution $\beta=(\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top \mathbf y$ enjoys many optimality properties but can suffer from overfitting. Indeed, OLS looks for $\beta$ that yields the highest possible correlation of $\mathbf X \beta$ with $\mathbf y$. If there is a lot of predictors, then it is always possible to find some linear combination that happens to have a high correlation with $\mathbf y$. This will be a spurious correlation, and such $\beta$ will usually point in a direction explaining very little variance in $\mathbf X$. Directions explaining very little variance are often very "noisy" directions. If so, then even though on training data OLS solution performs great, on testing data it will perform much worse.
In order to prevent overfitting, one uses regularization methods that essentially force $\beta$ to point into directions of high variance in $\mathbf X$ (this is also called "shrinkage" of $\beta$; see Why does shrinkage work?). One such method is principal component regression (PCR) that simply discards all low-variance directions. Another (better) method is ridge regression that smoothly penalizes low-variance directions. Yet another method is PLS1.
PLS1 replaces the OLS goal of finding $\beta$ that maximizes correlation $\operatorname{corr}(\mathbf X \beta, \mathbf y)$ with an alternative goal of finding $\beta$ with length $\|\beta\|=1$ maximizing covariance $$\operatorname{cov}(\mathbf X \beta, \mathbf y)\sim\operatorname{corr}(\mathbf X \beta, \mathbf y)\cdot\sqrt{\operatorname{var}(\mathbf X \beta)},$$ which again effectively penalizes directions of low variance.
Finding such $\beta$ (let's call it $\beta_1$) yields the first PLS component $\mathbf z_1 = \mathbf X \beta_1$. One can further look for the second (and then third, etc.) PLS component that has the highest possible covariance with $\mathbf y$ under the constraint of being uncorrelated with all the previous components. This has to be solved iteratively, as there is no closed-form solution for all components (the direction of the first component $\beta_1$ is simply given by $\mathbf X^\top \mathbf y$ normalized to unit length). When the desired number of components is extracted, PLS regression discards the original predictors and uses PLS components as new predictors; this yields some linear combination of them $\beta_z$ that can be combined with all $\beta_i$ to form the final $\beta_\mathrm{PLS}$.
Note that:

*

*If all PLS1 components are used, then PLS will be equivalent to OLS. So the number of components serves as a regularization parameter: the lower the number, the stronger the regularization.

*If the predictors $\mathbf X$ are uncorrelated and all have the same variance (i.e. $\mathbf X$ has been whitened), then there is only one PLS1 component and it is equivalent to OLS.

*Weight vectors $\beta_i$ and $\beta_j$ for $i\ne j$ are not going to be orthogonal, but will yield uncorrelated components $\mathbf z_i=\mathbf X \beta_i$ and $\mathbf z_j=\mathbf X \beta_j$.

All that being said, I am not aware of any practical advantages of PLS1 regression over ridge regression (while the latter does have lots of advantages: it is continuous and not discrete, has analytical solution, is much more standard, allows kernel extensions and analytical formulas for leave-one-out cross-validation errors, etc. etc.).

Quoting from Frank & Friedman:

RR, PCR, and PLS are seen in Section 3 to operate in a similar fashion. Their principal goal is to shrink the solution coefficient vector away from the OLS solution toward directions in the predictor-variable space of
larger sample spread.  PCR and PLS are seen to shrink more heavily away
from the low spread directions than RR, which provides the optimal shrinkage (among linear estimators) for an equidirection prior. Thus
PCR and PLS make the assumption that the truth is likely to have particular preferential alignments with the high spread directions of the
predictor-variable (sample) distribution. A somewhat surprising result
is that PLS (in addition) places increased probability mass on the true
coefficient vector aligning with the $K$th principal component direction,
where $K$ is the number of PLS components used, in fact expanding the
OLS solution in that direction.

They also conduct an extensive simulation study and conclude (emphasis mine):

For the situations covered by this simulation study, one can conclude
that all of the biased methods (RR, PCR, PLS, and VSS) provide
substantial improvement over OLS. [...] In all situations, RR dominated
all of the other methods studied. PLS usually did almost as well as RR
and usually outperformed PCR, but not by very much.

Update: In the comments @cbeleites (who works in chemometrics) suggests two possible advantages of PLS over RR:

*

*An analyst can have an a priori guess as to how many latent components should be present in the data; this will effectively allow to set a regularization strength without doing cross-validation (and there might not be enough data to do a reliable CV). Such an a priori choice of $\lambda$ might be more problematic in RR.

*RR yields one single linear combination $\beta_\mathrm{RR}$ as an optimal solution. In contrast PLS with e.g. five components yields five linear combinations $\beta_i$ that are then combined to predict $y$. Original variables that are strongly inter-correlated are likely to be combined into a single PLS component (because combining them together will increase the explained variance term). So it might be possible to interpret the individual PLS components as some real latent factors driving $y$. The claim is that it is easier to interpret $\beta_1, \beta_2,$ etc., as opposed to the joint $\beta_\mathrm{PLS}$. Compare this with PCR where one can also see as an advantage that individual principal components can potentially be interpreted and assigned some qualitative meaning.

A: Yes. Herman Wold's book Theoretical Empiricism: A general rationale for scientific model-building is the single best exposition of PLS that I'm aware of, especially given that Wold is an originator of the approach. Not to mention that it's simply an interesting book to read and know about. In addition based on a search on Amazon, the number of references to books on PLS written in German is astonishing but it may be that the subtitle of Wold's book is part of the reason for that.

A: I recommend this lecture: https://www.youtube.com/watch?v=Px2otK2nZ1c by Prof Asada who explains that PLS consists of the follwoing three steps which are iterated for k times (when k components are used):

*

*finding the directions v,w which maximize the correlation E[(xv)(yw)]

*finding the parameter beta of the linear model $\hat{y} = \beta z$ (with z =xv) wich minimizes the squared residuals

*deflation (removing information used in the previous two steps by updating x and y)


text:
Q: Redux: Filter data & rewind to initial data state in Reducer? Let's say I have a large amount of JSON data that I want initially displayed on page load (working thus far) and the option to filter that data to show only a specific amount. When my FILTER_DATA action is dispatched, it checks the view property and executes helper functions to filter the array of data down to however much it is I need displayed.
However... if I'm updating the state with the filtered version of the data and let's say the user wants to go back to the ORIGINAL view (the entire data set), is there a way to rewind state to that point? I was considering re-dispatching the FETCH_DATA action to re-perform a GET request to fetch the data once again, but that seems obnoxious. Thoughts?
Below is my reducer:
Note: data on the initialState object is an empty array value until FETCH_DATA_SUCCESS dispatches and sets state.data to the JSON data fetched in a GET request.
const app = (state = initialState, action) => {
  switch(action.type) {
    case FETCH_DATA:
      return { ...state, error: '', loading: true };
    case FETCH_DATA_SUCCESS:
      return { ...state, error: '', loading: false, data: action.data, view: 'all' };
    case FETCH_DATA_FAILURE:
      return { ...state, error: action.error, loading: false };
    case FILTER_DATA:
      let data;
      if (action.view === 'week') {
        data = groupData(getLastWeek(state.data), action.view);
      } else if (action.view === 'month') {
        data = groupData(getLastMonth(state.data), action.view);
      } else if (action.view === 'all') {
        data = state.data;
      }
      return { ...state, error: '', loading: false, data: data, view: view };
  }
  return state;
}

Thanks.

A: There's two main options.  First, if you really do want to keep the "filtered" data directly in your state, you could store two copies: the "original" and the "filtered" versions.
The other approach, which I recommend, is to keep both the original data and the filtering criteria in your state, but don't actually modify the original data.  Instead, derive the filtering outside of the store as needed.  This is a great use case for "selector functions".  See Computing Derived Data for some examples.


text:
Q: first letter of every word -im getting the last word two times My problem is to input a string and get the third word of the sentence. That part is resolved. The second part is to get the first letter of everyword but for some reason im getting two times the last word of the sentence
def words():
    global sent
    sent=input('enter a sentence - ')
    word=sent.split()
    return sent.split()[2]
print (words())

def first_letter():
    word=sent.split()
    c=0
    for j in sent:
        if j==' ':
            c+=1
    num_words=c+1
    for k in range(0,num_words):
        frst_letter=word[k]
    return word[k]
print(first_letter())

I expect the program to give me the first letter of every word in the sentence

A: Try:
sent = "hello there, how do you do?"

def first_letter():
    word=sent.split()
    return [c[0] for c in word]
print(first_letter())

output
['h', 't', 'h', 'd', 'y', 'd']


text:
Q: User Specific Page in TODO List I am making a simple todolist application but while I am trying to create user specific pages, I am unable to add a new task probably beacause database is not getting all required datas(i.e. owner of the task).
models.py
 from django.db import models
 from django.contrib.auth.models import User

 # Create your models here.

 class value(models.Model):
     task=models.CharField(max_length=200)
     complete=models.BooleanField(default=False)
     created=models.DateTimeField(auto_now_add=True)
     owner=models.ForeignKey(User,on_delete=models.PROTECT)

     def __str__(self):
         return self.task

views.py
 from http.client import HTTPResponse
 from urllib import response
 from django.shortcuts import render,redirect
 from todo.models import value
 from django.http import HttpResponseRedirect
 from django.contrib.auth.decorators import login_required
 from django.contrib.auth.models import User
 # Create your views here.
 from .forms import TitleForm
 from django.urls import reverse
 from django.contrib.auth.models import User

def home(request):
    values=value.objects.all()
    form=TitleForm()
    if request.method=='POST':
         form=TitleForm(request.POST)
         if form.is_valid():
             new_data=form.save(commit=False)
             new_data.owner=request.user()
             new_data.save()
         return HttpResponseRedirect('/')
    context={'form':form,'values':values}
    return render(request,'home.html',context)

#update

def update(request,id):

    ggwp=value.objects.get(id=id)
    form=TitleForm(instance=ggwp)
    if request.method == 'POST':
          form=TitleForm(request.POST,instance=ggwp)
          if form.is_valid:
             form.save()
             return redirect('home')
    context={'form':form,}
    return render(request,'update.html',context)

#delete

def delete_data(request, id ):
    if request.method=="POST":
        ggwp=value.objects.get(id=id)
        ggwp.delete()
        return HttpResponseRedirect(reverse('deldata', kwargs={'id':id}))
    return redirect("/")

forms.py
from django import forms
from django.forms import ModelForm
from .models import value
from django import forms

class TitleForm(forms.ModelForm):
    class Meta:
       model= value
       fields='__all__'

urls.py(app)
from django.conf.urls import url
from django.urls import path
from . import views

urlpatterns=[
    path('',views.home,name='home'),
    path('delete/<str:id>', views.delete_data,name='deldata'),
    path('update/<str:id>',views.update,name='update')
]

home.html(main page)
<form method="POST">
  {% if user.is_authenticated %}
  Hello,{{user.username}}

  Logout
  {% else%}
  Register
  login
  {% endif %}
</form>

<form action="/" method="post" >
    {% csrf_token %}
    {{form.task}}
     <input class='btn btm-sm btn-info' type='submit' name='add' value="add" >
</form>

{% for val in values %}

    {% if val.complete == True %}
    <s>{{val}}</s>
    {% else %}
    {{val}}
    {% endif %}

    <form action="{% url 'deldata' val.id %}" method="POST" class="in-line">
        {% csrf_token %}
        <input class='btn btm-sm btn-danger' type="submit" name="delete" value="delete">
        Update
    </form>

 {% endfor %}

Home.html looks like this:
todo
When i want to add a task and click on add, nothing really happens. It only redirects back to same page but not data is inserted in database.
If there are problems in questions, I am really sorry!

A: Home.html :

  {% if user.is_authenticated %}
      Hello,{{user.username}}

      Logout
  {% else%}
      Register
      login
  {% endif %}

<form method="POST" >
    {% csrf_token %}
    {{form}}
     <input class='btn btm-sm btn-info' type='submit' name='add' value="add" >
</form>

{% for val in values %}

    {% if val.complete == True %}
    <s>{{val}}</s>
    {% else %}
    {{val}}
    {% endif %}

    <form action="{% url 'deldata' val.id %}" method="POST" class="in-line">
        {% csrf_token %}
        <input class='btn btm-sm btn-danger' type="submit" name="delete" value="delete">
        Update
    </form>

 {% endfor %}

*

*UPDATE1 : EXCLUDING USER IN FORM AND ADDING THE CURRENT USER IN VIEWS
#Do not add Owner into the model form fields
forms.py:
from django import forms
from django.forms import ModelForm
from .models import value
from django import forms

class TitleForm(forms.ModelForm):
    class Meta:
       model= value
       fields=['task', 'complete', 'created']

Views.py:
def home(request):
    values=value.objects.all()
    form=TitleForm()
    if request.method=='POST':
         form=TitleForm(request.POST)
         if form.is_valid():
             new_data=form.save(commit=False)
             new_data.owner=request.user
             new_data.save()
         return HttpResponseRedirect('/')
    context={'form':form,'values':values}
    return render(request,'home.html',context)


text:
Q: JavaScript is not storing HTML input value I am making a rock paper scissors game with HTML, CSS, and JS. I give the user two inputs where they can enter their name and the CPU's name. Then when they click play, I can store those values. As of now, I log them in console to see if it works. However, the input value is always empty despite me entering something. Any help would be greatly appreciated :)

let playerName = document.getElementById("player-name").value;
let cpuName = document.getElementById("cpu-name").value;
if (playerName === "") {
    playerName = "You";
}
if (cpuName === "") {
    cpuName = "CPU";
}

let play = document.getElementById("play").addEventListener("click", () => {
    console.log(playerName, cpuName);
});
    <input id="player-name" class="names" type="text" placeholder='Enter Your Name'>
    <input id="cpu-name" class="names" type="text" placeholder='Enter CPU Name'>
    <button id="play">Play</button>

A: You should get those value while onclick event:

let play = document.getElementById("play").addEventListener("click", () => {
   let playerName = document.getElementById("player-name").value;
   let cpuName = document.getElementById("cpu-name").value;
   if (playerName === "") {
     playerName = "You";
   }
   if (cpuName === "") {
     cpuName = "CPU";
   }
   console.log(playerName, cpuName);
});
    <input id="player-name" class="names" type="text" placeholder='Enter Your Name'>
    <input id="cpu-name" class="names" type="text" placeholder='Enter CPU Name'>
    <button id="play">Play</button>

A: Try this,

let playerName;
let cpuName;

let play = document.getElementById("play").addEventListener("click", () => {
playerName = document.getElementById("player-name").value;
cpuName = document.getElementById("cpu-name").value;
if (playerName == null) {
 playerName = "You";
}
if (cpuName == null) {
 cpuName = "CPU";
}
console.log(playerName, cpuName);
});
    <input value="" id="player-name" class="names" type="text" placeholder='Enter Your Name'>
    <input value="" id="cpu-name" class="names" type="text" placeholder='Enter CPU Name'>
    <button id="play">Play</button>


text:
Q: Create a jar file from command promt like eclipse export I have to make a jar from a shell something like this:

and the jar must look like this:

and if I try this from a command promt, with something like this:
jar cvfe xmlvalidator.jar * src/*.class
executed from XMLValidator folder, my jar is created like this:

and I have into src folder \com\ and \java_cup\ and the jar seems not to work.
Do you have any ideea how could I put com and java_cup folders into the root of the jar (from command line)? like eclipse does?
Thanks!


text:
Q: How to process particular thread as fast into multithread java? I am doing multithread processing for generating some products... i will create the products every 10 minutes..i have 2 threads .. first thread will wakeup every 10 minutes...
the second thread will generate products...
The problem is in second thread...because in second thread ,I will generate some product files(files created by bytes ,all files size will be 30 or 50 mb)..After creating product files,product will be generated by depending on those product files.The product files are created every 10 minutes(it should be created every 10 minutes)..but its taking time more than 10 minutes to create those product files...so can u pls anyone tell me the way to create the files as very fast?
public class Scheduler implements Runnable{
    Thread firstThread;
    public Scheduler() {
        firstThread = new Thread(this,"timer");
    }
    public void run() {

        do {
            if(wakeUptime) {//if wake up 10.00 correct time
                secondThread(wakeUptime);
                sleep(10mins);
            } else {
                // calculate next round of next ten mins...
                // if this process starts at 10.05A.M ,
                // it will sleep 5 mins
                // (round of time in 10 minutes(10minutes - 5 mins))
                // so sleep(5 mins)
            }

        } while(true);

    }

    secondThread(final string time) {
        Runnable r = new Runnable() {
            firstFunction(time);
            secondFunction(time);
        };
        Thread t = new Thread(r);
        try {
            t.start();
            t.join;//its getting very slow..how to make fast...
        } catch(Exception e) {
        }

    }

    firstFunction(String time) {

        // Here, files will be created every 10 minutes
        // total files size 40 or 50 mb...
        // files created by using bytes.
        // the problem is creating files taking more than 10 minutes...
        // so is there any method to create files very fast?

    }

    secondFunction(String time) {
        // generate product
    }

}

in the first method,the files will be created..the file size will be  40 or 50 mb...so its taking lot of time to create the files... the files are creating more than 10 minutes...Is there any method to create files as very fast?

A: First, i'm recommend to use power production ready sheduler - Quartz from Terracota, he has a trigger system where you can define misfire behavior. Second, of course optimize your code where you create files with productrs - there is no miracles in world, if you cat't create source data for function, you can't run you function with right result

A: You say "files created by using bytes" - are you writing one byte at a time to the file? Have you wrapped your FileOutputStream in a BufferedOutput stream? Doing so could make an order of magnitude or more improvement.
If you're using Java 5 or higher, you can use a ScheduledExecutor to run the second thread. This will probably be more reliable than reimplementing it on your own.


text:
Q: Why can't list unpacking be used for indexing a second list? … e.g. a[*b] where a and b are both lists and len(b) == 1
Using the simple example below:
a = [1,2,3,4]
b = [0]

a[*b]

Why does running the above raise an exception?
    a[*b]
      ^
SyntaxError: invalid syntax

A: Because that syntax is invalid.
Iterable unpacking is allowed in various circumstances – for example:

*

*Unpacking Argument Lists

*Assignment

*Comprehensions
… but not universally, and definitely not for indexing. In fact, it's unclear what your proposed syntax even means. Consider: what would a[*b] return if b were [1, 2]?


text:
Q: Center  inside a  Code: https://jsfiddle.net/z4udfg3o/
I want the divs "caixa" to be centered in the div "produtos". I was able to do it with exact values using margin-left. But I want it to be responsive for other screen sizes so I putted margin-left and margin-right as auto.
Image of desired format:

A:

section {
  padding: 2em 0;
  display: flex;
  justify-content: space-between;
  background: antiquewhite;
}

section:before, section:after {
  content: "";
}

div {
  width: 10em;
  height: 10em;
  background: silver;
}

A: Like This?

.produtos {
  width: 100%;
  height: 252px;
  background: gray;
  text-align: center;
}
.caixa {
  width: 250px;
  height: 250px;
  background: darksalmon;
  border: 1px solid #000;
  margin: 0 auto;
}

Temos os melhores produtos do mercado! Nossos competidores ajoelham-se perante a nossa qualidade!

Preços mais baratos do mercado! Promoções 24/7! Se houver ofertas mais baratas diga e fazemos promoção de 0.01€!

Nosso departamento de apoio ao cliente está ativo 24/7! Resolveremos todas as suas dúvidas!

Otherwise, i suggest you to have a look at flexbox

A: Do it like below:

#wrap {
    background: #e7e7e7;
    padding: 4px;
    text-align: center;
    width:100%;
}

#one, #two, #three {
     background: #ccc;
     display: inline-block;
     padding: 20px;
     width:20%;
}

I am div 1

I am div 2

I am div 2

A: try changing your css like below
.produtos
    {
        width: 100%;
        height: 252px;
        background: gray;
        text-align: center;
    }

.caixa
    {
        width: 250px;
        height: 250px;
        background: darksalmon;
        border: 1px solid #000;
        display: inline-block;
    }

A: Use this CSS:
.produtos {
    width: 100%;
    background: gray;
    margin-left: auto;
    margin-right: auto;
    display: inline-block;
}

.caixa {
    width: 27.1%;
    height: 250px;
    background: darksalmon;
    border: 1px solid #000;
    float: left;
    margin: 0 3%;
}

A: The following code sets the orange boxes as display: inline-block which causes them to follow the text flow, which is set to center in the parent container. This allows the boxes to flow depending on available screen space. On wide screens they're all side by side, on smaller ones they're arranged vertically.
I have also modified the HTML in order to get rid of newlines between the boxes. These newlines would cause margins otherwise.

.produtos
    {
        width: 100%;
        background: gray;
        text-align: center;
    }

.caixa
    {
        vertical-align: top;
        width: 250px;
        height: 250px;
        background: darksalmon;
        border: 1px solid #000;
        display: inline-block;
    }

Temos os melhores produtos do mercado! Nossos competidores ajoelham-se perante a nossa qualidade!

Preços mais baratos do mercado! Promoções 24/7! Se houver ofertas mais baratas diga e fazemos promoção de 0.01€!

Nosso departamento de apoio ao cliente está ativo 24/7! Resolveremos todas as suas dúvidas!

A: you should balance the width of both divs. "caixa" and  "produtos".
I think using % will be responsive for other screeen size too.
Fiddle
Hope Fiddle link help you .

A: There are different ways, but if the boxes are to contain an image or something, then you will need a fixed aspect ratio, that can be accomplished like this:

.wrapper{float:left; width:100%; background-color:deeppink;}
.lil-box{float:left; width:22%; margin:0 5.665%; background-color:bisque;}
.tight-fit{float:left; width:100%; margin-top:100%;}

A: I hope it works for you. I added each div class row for each to so you can set the padding in classemphasized text row.

.produtos
    {
        width: 100%;
        height: 252px;
        }

.caixa
    {
        width: 33%;
        height: 100%;
        background: darksalmon;
        border:1px solid red;
        float: left;
    }
  .row{
        height:100%;
        padding:0 20px;
}

Temos os melhores produtos do mercado! Nossos competidores ajoelham-se perante a nossa qualidade!

Preços mais baratos do mercado! Promoções 24/7! Se houver ofertas mais baratas diga e fazemos promoção de 0.01€!

Nosso departamento de apoio ao cliente está ativo 24/7! Resolveremos todas as suas dúvidas!


text:
Q: DOM tree based JavaScript template engines I am looking for a new Javascript template engine to replace old jQuery Template for my client side templating needs.
I'd prefer approach where the template engine deals with DOM trees instead of text strings and later dumps the content of the cooked string into innerHTML. This is better performance wise and I find DOM manipulation more proper way of constructing more of DOM tree.
What options I do have for Javascript template engine which would directly create DOM trees instead of being text based engines? I like Mustache.js's logicless approach, but it seems to operate on strings only. Native jQuery integration would also be a nice feature.

A: Distal
http://code.google.com/p/distal

A: soma-template is a new one.
Pure DOM manipulation, a lot of features, natural syntax, fully extensible with other libraries such as underscore.string, function calls with parameters, helpers, watchers. Capability to update only some nodes if needed, templates inside the DOM itself.
http://soundstep.github.com/soma-template/

A: Transparency:
https://github.com/leonidas/transparency/
PURE:
http://beebole.com/pure/documentation/
Plates
https://github.com/flatiron/plates
Why all this:
http://blog.nodejitsu.com/micro-templates-are-dead

A: This is good comparison about 7 famous JS template engine: http://blog.stevensanderson.com/2012/08/01/rich-javascript-applications-the-seven-frameworks-throne-of-js-2012/

A: I've recently created DOM templating engine inspired by PURE and Transparency.
It supports loops, conditions and much more.
Take a look at doc: http://code.meta-platform.com/metajs/components/template/
Don't be affraid that MetaJS is big library, templating lib can be used standalone.
Short example:
HTML:

Define template:
var tpl = Meta.Template(document.getElementById('tpl'), {
    "ul#tasks li": $__repeat("tasks", {
        ".task":        "task",
        ".due-date":    $__date("d. m. Y", "due_date"),
        "@":            $__attrIf("completed", "complete")
    })
});

Render template:
tpl({
    tasks: [
        {
            task: "Write concept",
            due_date: new Date(2015, 3, 22, 0, 0, 0, 0),
            complete: true
        }, {
            task: "Consult with customer",
            due_date: new Date(2015, 3, 25, 0, 0, 0, 0),
            complete: false
        }
    ]
});

Result:

            Write concept
            22. 3. 2015

            Consult with customer
            25. 3. 2015

A: Take a look at Monkberry DOM template engine.
It is really small (just 1,5kB gzipped), dependency free library, server compiling, one-way data binding, and it's dramatically fast!
Here example of template and generated code:

{{ title }}

    {{ text }}

Will generate:
var div = document.createElement('div');
var h1 = document.createElement('h1');
var p = document.createElement('p');

div.appendChild(h1);
div.appendChild(p);

   ...

view.update = function (data) {
  h1.textContent = data.title;
  p.textContent = data.text;
};

Monkberry supports if, for and custom tags. And has a lot of rendering optimizations.
Templates can be rendered on server with webpack, browserify or cli.

*

*monkberry.js.org

A: dna.js is a templating engine that clones DOM elements (https://dnajs.org).
Example template for a book:

Featured Books

Title:  {{title}}

Author: {{author}}

Call to insert a copy of the template into the DOM:
dna.clone('book', { title: 'The DOM', author: 'Jan' });

Resulting HTML:

Featured Books

Title:  The DOM

Author: Jan

Fiddle with a sample "To-Do Application":
https://jsfiddle.net/uLrc7kmp

dna.js was created precisely to avoid constructing and passing around string templates (I'm the project maintainer).

A: Free MIT-licensed jQuery DNA Template with superpowers (you can re-apply the changed data to the same HTML structure to update UI on any data change...)
https://github.com/webdevelopers-eu/jquery-dna-template/

A: What sort of sugar are you looking for? The raw DOM api always worked fine for me. If you are really adopting this idea that the templating engines are no good in terms of performance, don't use innerHTML if you want to efficiently build up a DOM tree. What I tend to do is just create elements manually using document.createElement. My templates are created by writing helper functions that create collection of nodes and populate them with the data by setting the .innerText property. I can then cache the references to nodes which I wish to refer to frequently so that I don't have to traverse the DOM tree to find these nodes again.


text:
Q: Exclude Current and Sticky Post On a single Post page I have a side bar displaying up to three other, related posts. How can I exclude both Sticky Posts and the Current post?
I know how to exclude the Current post and how to exclude Sticky Posts by using post_not_in in a WP_Query, see code example below. But I guess you can not use post__not_in twice in the same query. Any suggestions?
$current_post_ID = get_the_ID();

        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'order' => 'DESC',
            'orderby' => 'date',
            'posts_per_page' => 3,
            'post__not_in' => get_option( 'sticky_posts' )
            'post__not_in' => array($current_post_ID)
        );

A: The post__not_in is an array() and uses post ids (numbers only).
There is no need to use it twice, use it like that:

//First build the array of excluded posts
$excluded_posts = array_push(get_option( 'sticky_posts' ) , $current_post_ID);

//Then use it in the option
'post__not_in' => array( $excluded_posts )
Note the array_push() PHP function, this will add the current post to the end of the sticky posts array, which is then passed to 'post__not_in' option.

A: <?php

                      $sticky =array(get_option('sticky_posts'));

                       // (add post id on sticky_posts option like ex. 485,458,256)

                      $current_post_ID = get_the_ID();
                      array_push($sticky,$current_post_ID);

                        $args = array(
                            'post_type' => 'post',
                            'post_status' => 'publish',
                            'order' => 'DESC',
                            'orderby' => 'date',
                            'posts_per_page' => 3,
                            'post__not_in' => array($sticky)
                        );
                        query_posts($args);

                        while ( have_posts() ) : the_post(); ?>

                    <!-- add your code which to display hear -->

                    <?php
                        endwhile;
                        wp_reset_query();
                    ?>


text:
Q: Makeglossaries and Perl warning: Unescaped left brace in regex is deprecated, passed through in regex I'm trying to run Makeglossaries. However, I get this warning message in the log file:
Processo iniciado: makeglossaries.exe "document-glossario"

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\\\@input{ <-- HERE (.+)\.aux}/ at C:\Users\user_001\AppData\Roaming\MiKTeX\2.9\scripts\glossaries\makeglossaries line 634.

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\\\@newglossary\s*\{(.*)\}{ <-- HERE (.*)}{(.*)}{(.*)}/ at C:\Users\user_001\AppData\Roaming\MiKTeX\2.9\scripts\glossaries\makeglossaries line 643. Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\\\@newglossary\s*\{(.*)\}{(.*)}{ <-- HERE (.*)}{(.*)}/ at C:\Users\user_001\AppData\Roaming\MiKTeX\2.9\scripts\glossaries\makeglossaries line 643. Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\\\@newglossary\s*\{(.*)\}{(.*)}{(.*)}{ <-- HERE (.*)}/ at C:\Users\user_001\AppData\Roaming\MiKTeX\2.9\scripts\glossaries\makeglossaries line 643.

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\\\@xdylanguage\s*{([^}]+)}{ <-- HERE ([^}]*)}/ at C:\Users\user_001\AppData\Roaming\MiKTeX\2.9\scripts\glossaries\makeglossaries line 674. Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\\\@gls\@codepage\s*{([^}]+)}{ <-- HERE ([^}]*)}/ at C:\Users\user_001\AppData\Roaming\MiKTeX\2.9\scripts\glossaries\makeglossaries line 680.

Processo concluído normalmente

I have make a google search, it seems a script glossary "bug" using this new perl 5.22 version. However, I have no idea how to fix it. If anyone could help, please.

ActivePearl Version 5.22.1.2201

TeXstudio Version is 2.10.8

Output PDF file seens ok.
Original LaTeX test code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{glossaries}

\makeglossaries

\newglossaryentry{latex}
{
    name=latex,
    description={Is a mark up language specially suited
    for scientific documents}
}

\newglossaryentry{maths}
{
    name=mathematics,
    description={Mathematics is what mathematicians do}
}

\title{How to create a glossary}
\author{ }
\date{ }

\begin{document}
\maketitle

The \Gls{latex} typesetting markup language is specially suitable
for documents that include \gls{maths}.

\printglossaries

\end{document}

Results ok


text:
Q: Variable is empty with jQuery I would like to run a code only if the date of my task is not empty. But currently, the code is running with a empty date. Can you explain me where is my error ?
var date = '<%=@task.date%>'
if( date != null){
  $('.sn_date').html('<%=@task.date.strftime("%d %b")%>')
}

A: First case:

if @task.date is nil or empty, .present? will return false, else true. In any conditions your var date will be boolean.
Second case:

in this case your var date will be string, does not matter what will return @task.date, nil or string date. And now in js you should verify if var date not empty string if (!!date) {}.
if date = '' => !!date return false
if date = 'date' => !!date return true

A: Have you tried validating with Ruby then dumping out your JS if the date is present?
<% if (@task.date.present?) %>
 $('.sn_date').html('<%=@task.date.strftime("%d %b")%>')
<% end %>

A: you can validate with " " empty, something like that if (date != ""){
your sentence.... }


text:
Q: Null Pointer When Access Data Structure Located Within Android Service I have a service running in my Android application which contains a HashMap that I would like to use in an Activity.  So I bound the service to my activity and created a link between to two in order to use the data structure.
This is how I did it so far:
Activity (relevant code):
private ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        imService = ((IMService.IMBinder) service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        imService = null;
        Toast.makeText(ViewFlipperTest.this,
                R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }
};

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bindService(new Intent(ViewFlipperTest.this, IMService.class),
            mConnection, Context.BIND_AUTO_CREATE);
                 .
                 .
                 .
}
protected void onResume() {
    super.onResume();
    bindService(new Intent(ViewFlipperTest.this, IMService.class),
            mConnection, Context.BIND_AUTO_CREATE);
}

private void getMap(ViewFlipper flipper2) {

    Map<Integer, internalChatObj> tempMap = imService.getMapwData();
   }

Service (relevant code):
public class IMService extends Service implements IAppManager{
                .
                .
                .

public Map getMapwData(){
    if(getNumberOpenChats()>0){
        return openChatMapwData;
    }
    else
        return null;

}
}

Each time I try and run the method getMap(), I get a null pointer.  I even put a check to see if the imService was null and it was null each time.  It seems that it is trying to obtain the data from the Service but the binding to the service is null, is that right?  I have a check in the Service to send null if the map is empty, so that shouldn't be a problem.
Any help?
Edit based on Will's tips
New code
private ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        imService = ((IMService.IMBinder) service).getService();
        dialog.dismiss();
    }

    public void onServiceDisconnected(ComponentName className) {
        imService = null;
        Toast.makeText(ViewFlipperTest.this,
                R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }
};

public void onCreate(Bundle savedInstanceState) {
    dialog = ProgressDialog.show(getApplicationContext(), null,"Loading..", true, false);
}

Edit II
IMBinder Class (Seems standard, no?)
public class IMBinder extends Binder {
    public IAppManager getService() {
        return IMService.this;
    }
}

Is it necessary to have IMService.this instead of this?

A: It really seems like a timing issue; you shouldn't call the getMap function unless you are certain the imService variable exists, which is after a call to onServiceConnected.


text:
Q: Unable to send SMS before shutting down device I'm developing an app which needs to send an SMS if / when the device shuts down.
In order to receive the action I'm using android.intent.action.ACTION_SHUTDOWN and android.intent.action.QUICKBOOT_POWEROFF actions, and it works perfectly well. In fact, the method I'm using to send the SMS is also working (as I have used it multiple times in other apps).
The problem I'm facing is that when I receive the SHUTDOWN action the telephony service is already off, so the SMS is unable to be sent and it remains queued waiting for a retry.
Is there a way to prevent / turning on again the telephony service in order to send my SMS?
In case it's not possible, is there another action similar to the SHUTDOWN event which I can use instead?

A:
Is there a way to prevent / turning on again the telephony service in order to send my SMS?

You are welcome to make your own customized build of Android that sends an SMS message as part of its shutdown process. Then, you can try to package that customized build of Android into a custom ROM for a particular piece of hardware.
If you are asking whether an app can do that on arbitrary hardware, the answer is no.

is there another action similar to the SHUTDOWN event which I can use instead?

You can ask the user to tap on something related to your app (e.g., a Notification) before shutting down the device.
Otherwise, I am not aware of some other event that not only tells you that the device is shutting down but also lets you block that shutdown process until you decide it is time to proceed (e.g., after sending an SMS, after forcing a ransomware payment).


text:
Q: Read one character at a time from istream input This code is supposed to store a very long user typed number using a custom data structure (type of stack) as a substitute to arrays or STL containers. I'm trying to overload >> operator so that
LongInt int1;
cin>>int1;

will work.
My code:
istream& operator>> (istream& input, LongInt& number) //class name is LongInt
{
    char c;
    int a;
    while (input>>c){ // read one number at a time
        a=c-'0'; // converting the value to int
        number.stackli.push(a); // pushing the int to the custom stack
    }

    return input;
}

should terminate after the user typed his number and pressed enter, but instead results in an infinite loop. Commenting out the two lines inside the loop still results in an infinite loop. Any suggestions on how to fix this would be highly appreciated.

A: Because (input >> c) will always be true as long as input is in good state, say, not closed, hence the infinite loop.
Even you don't have anything input, the loop is "blocked" instead of "ended".
To consume just a part from the input stream instead of whole, you'll need something like:
while(input >> c) {
    if(c<='0' || c>='9') {
        // "c" is not the character you want, put it back and the loop ends
        input.putback(c); break;
    }
    ...
}


text:
Q: How to convert markdown to HTML in Golang with adding section tag I have the markdown below
## Hello
### This is a test message
Ligisnfmkdfn

And I use the GO module gomarkdown to convert markdown to HTML with CommonExtensions and AutoHeadingIDs parser and I got the result are

Hello

This is a test message

Ligisnfmkdfn

How can I get the result like using markdown-it-header-sections in nodejs

Hello

This is a test message

Ligisnfmkdfn

A: Here's a moderately complete solution:
package main

import (
    "fmt"
    "io"
    "regexp"
    "strings"

    "github.com/gomarkdown/markdown"
    "github.com/gomarkdown/markdown/ast"
    "github.com/gomarkdown/markdown/html"
)

// levels tracks how deep we are in a heading "structure"
var levels []int

func hasLevels() bool {
    return len(levels) > 0
}

func lastLevel() int {
    if hasLevels() {
        return levels[len(levels)-1]
    }
    return 0
}

func popLevel() int {
    level := lastLevel()
    levels = levels[:len(levels)-1]
    return level
}

func pushLevel(x int) {
    levels = append(levels, x)
}

var reID = regexp.MustCompile(`\s+`)

// renderSections catches an ast.Heading node, and wraps the node
// and its "children" nodes in
...
 tags; there's no
// real hierarchy in Markdown, so we make one up by saying things like:
// - H2 is a child of H1, and so forth from 1 → 2 → 3 ... → N
// - an H1 is a sibling of another H1
func renderSections(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
    openSection := func(level int, id string) {
        w.Write([]byte(fmt.Sprintf("
\n", id)))
        pushLevel(level)
    }
    closeSection := func() {
        w.Write([]byte("
\n"))
        popLevel()
    }

    if _, ok := node.(*ast.Heading); ok {
        level := node.(*ast.Heading).Level
        if entering {
            // close heading-sections deeper than this level; we've "come up" some number of levels
            for lastLevel() > level {
                closeSection()
            }

            txtNode := node.GetChildren()[0]
            if _, ok := txtNode.(*ast.Text); !ok {
                panic(fmt.Errorf("expected txtNode to be *ast.Text; got %T", txtNode))
            }
            headTxt := string(txtNode.AsLeaf().Literal)
            id := strings.ToLower(reID.ReplaceAllString(headTxt, "-"))

            openSection(level, id)
        }
    }

    // at end of document
    if _, ok := node.(*ast.Document); ok {
        if !entering {
            for hasLevels() {
                closeSection()
            }
        }
    }

    // continue as normal
    return ast.GoToNext, false
}

func main() {
    lines := []string{
        "## Hello",
        "### This is a test message",
        "Ligisnfmkdfn",
    }
    md := strings.Join(lines, "\n")

    opts := html.RendererOptions{
        Flags:          html.CommonFlags,
        RenderNodeHook: renderSections,
    }
    renderer := html.NewRenderer(opts)

    html := markdown.ToHTML([]byte(md), nil, renderer)

    fmt.Println(string(html))
}

When I run that, I get:

Hello

This is a test message

Ligisnfmkdfn

I say it's moderately complete because it's smart enough to deal with input like this:
lines := []string{
    "# H1α",
    "## H2A",
    "## H2B",
    "## H2C",
    "### H31",
    "#### H4I",
    "## H2D",
    "# H1β",
    "## H2E",
}

and it produces:

H1α

H2A

H2B

H2C

H31

H4I

H2D

H1β

H2E

But I haven't rigorously tested this, so I'm not sure where it might not meet expectations.


text:
Q: How to aggregate two nested arrays for two different outputs of single collection? My desired outcome is check common ids and their count between friends. One is closed friends count and another one is normal friends count.
Here data is the list of my friends and user is me.
async function uinfo(data, user){
  const arr = []
    for (const i of data) {
      await Profile.aggregate([{"$match": {"_id": {"$in": [user, i._id]}}}, {"$unwind": "$list.closedFriends"}, {"$group": {_id: "$list.closedFriends.id", count: {$sum: 1}}}, {$match: {count: 2}}, {$project: {_id: 1}}], function(err, result){
          if(result.length >= 1){
            i.cfcount = result.length
          }
          else{
            i.cfcount = 0
          }
      })
      await Profile.aggregate([{"$match": {"_id": {"$in": [user, i._id]}}}, {"$unwind": "$list.friends"}, {"$group": {_id: "$list.friends.id", count: {$sum: 1}}}, {$match: {count: 2}}, {$project: {_id: 1}}], function(err, result1){
          if(result1.length >= 1){
            i.fcount = result1.length
          }
          else{
            i.fcount = 0
          }
      })
      arr.push(i)
    }
    console.log(arr)
    return await Promise.all(arr)
}

By performing two separate queries i am getting proper result but i want to combine these two queries.
One more problem with above one is, output of result1 is not giving promised output for last fetching(or matching).
Edit:-
{ "_id" : 1, "friends" : [2,3,4], "closedFriends":[5,6,7] }
{ "_id" : 2, "friends" : [ 1,3,5 ], "closedFriends" : [4,6,7] }

In the above database the common friends between 1 and 2 is 3 and closedFriends are 6 and 7. The desired output is cfcount is 2 and fcount is 1 along with ids.
Edit2:-
{ "_id" : 1, "friends" : [{id:1, name:'john', score:0}, {id:2, name:'john', score:0}, {id:3, name:'john', score:0}], "closedFriends":[{id:8, name:'john', score:0}, {id:4, name:'john', score:0}, {id:5, name:'john', score:0}] }
{ "_id" : 2, "friends" : [{id:2, name:'john', score:0}, {id:7, name:'john', score:0}, {id:3, name:'john', score:0} ], "closedFriends" : [{id:1, name:'john', score:0}, {id:9, name:'john', score:0}, {id:8, name:'john', score:0}] }

Here along with count I want to include filed 'name' and 'score' in aggregated output.

A: The aggregation framework can replace all your Javascript calculations (your for loop counting), and thus eliminate o(2n) aggregational computations you did, into only one o(1).
function uinfo(data, user){
    let mainUser = db.Profile.findOne({_id: user});
    let userIds = Array.from(data, user => user.id);
    return Profile.aggregate([
    {$match: {'_id': {$in: userIds}}},
    {
        $project: {
            '_id' : 1,
            'fcount': {
                $size: {
                    $setIntersection: [
                        mainUser.friends,
                        '$friends',
                    ]
                }
            },
            'cfcount': {
                $size: {
                    $setIntersection: [
                        mainUser.closedFriends,
                        '$closedFriends',
                    ]
                }
            }
        }
    },
    ])
}


text:
Q: What values can the process $X_n$ take when $P(Y = k) = a_k = 0$ for $k \geq 2$
A newspaper uses one ton of newsprint every day. It buys its newsprint from a local distributor. This ditributor supplies the newsprint in one-ton rolls at the cheapest price, but unfortunatley its deliveries are erratic. Hence, the number of rolls of newsprint in the newpaper warehouse varies randomly. If on a particular day, there are no rolls in the warehouse, the newspaper buys and uses a rold from an emergency supplier. Let $Y_n$ be the number of rolls received from the local distributor on day $n$. The supply arrives in the evening, whereas the one tone is consumed in the morning. Let $X_n$ be the number of rolls in the warehouse at the beginning of day $n$ before the one ton demand has to be satisfied and the supply for day $n$ has arrived. Thus $X_{n=1} = X_n - 1 + Y_n$ if $X_n>0$ and $X_{n+1} = X_n$ is $X_n = 0$.
Suppose that the random variables $\{Y_n, n \geq 0\}$ are idependent of $X_{0}$. Besides, suppose that they are naturally independent and identically distributed and $P(Y_n = k) = a_k, k = 0,1,...$.

*

*Suppose $a_k = 0$ for $k \geq 2$ and $X_0 \in \{0, 1\}$, what values can the process $X_n$ take in this situation?

From my transition matrix, I said if we are only looking at the values for when $i, j$ are $0$ and $1$, we would get the little $2 \times 2$ matrix of the whole one step transition matrix and so this would just be
$$\pmatrix{a_0 & a_1 \\ a_0 & a_1}$$
and so the only values that $X_n$ can take in this situation are $a_0$ and $a_1$. But in the answers it says it should be $0$ and $1$. Why is this?

A: If you just look at your recursions then this should yield the solution.
If $X_0=0$ then $X_n = 0$ for all $n$ -> let's call this the absorbtion.
So we analyze the case that $X_0=1$.
Then
$$
X_{n+1} = X_n - 1 + Y_n
$$
Consider $n=0$ if $Y_0 = 0$ then $X_1 = 1 - 1 + 0 = 0$ and we are caught in $0$ due to the absorption.
If $Y_0=1$ then $X_1 = 1 - 1 + 1 = 1$ and we are back in the case $X_1 = 1$. Because $Y$ can only take the values $0$ or $1$ (all other probabilities are zero). Then we can continue this reasoning for the transition from $X_1$ to $X_2$ and finally for $X_n,n\ge 0$ this concludes the proof.