text:
Q: Why does wait for element_to_be_clickable work but presence_of_element_located does not I am trying to select a radio check box on a page after it loads. I have tried 3 different ways. Two work and one does not, but I don't understand why. The one that does not work is the one I would like to use.
The below code works with no issues.
wait=WebDriverWait(driver, 30)
el = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="stops-1"]')))
el.click()

The below code works with no issues.
wait=WebDriverWait(driver, 30)
time.sleep(15)
driver.find_element_by_xpath('//*[@id="stops-1"]').click()

The below code gives the following error.
"in until raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: "
wait=WebDriverWait(driver, 30)
el = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="stops-1"]')))
el.click()

The page loads in about 10 - 15 seconds and the radio is present and I assume clickable because the other methods worked but this one does not.
Any help would be appreciated
below is the link to the sight I am trying to work with
https://www.expedia.com/Flights-Search?flight-type=on&mode=search&trip=roundtrip&leg1=from%3AAlbuquerque+%28ABQ+-+Albuquerque+Intl.+Sunport%29%2Cto%3ANew+York+%28NYC+-+All+Airports%29%2Cdeparture%3A4%2F24%2F2021TANYT&options=cabinclass%3Aeconomy&leg2=from%3ANew+York+%28NYC+-+All+Airports%29%2Cto%3AAlbuquerque+%28ABQ+-+Albuquerque+Intl.+Sunport%29%2Cdeparture%3A4%2F25%2F2021TANYT&passengers=children%3A0%2Cadults%3A1%2Cseniors%3A0%2Cinfantinlap%3AY&fromDate=4%2F24%2F2021&toDate=4%2F25%2F2021&d1=2021-04-24&d2=2021-04-25


text:
Q: can't connect to ec2 anymore - Permission denied (publickey) - but was working yesterday I've already tried all previous answers to previous similar questions here. None worked.
Until yesterday I could login normally to my EC2 instance, today I can't, using the same key. The server did not restart, and is using the same DNS. I've tried already using the IP or the server address.
Have also tried everything on http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html
It all started with my mysql going down. I logged in fixed, created a backup and was trying to copy the backup thru SCP. But started getting permission denied, than SSH also started receiving permission denied. The blog still up and running, but I can't log in to the server nor copy the backup file.
Using the command:
ssh -vvv -i "key.pem" ec2-user@ec2-52-67-93-144.sa-east-1.compute.amazonaws.com

I get:
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to ec2-52-67-93-144.sa-east-1.compute.amazonaws.com [52.67.93.144] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "key.pem" as a RSA1 public key
debug1: identity file key.pem type -1
debug1: identity file key.pem-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH*
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "ec2-52-67-93-144.sa-east-1.compute.amazonaws.com" from file "/Users/pedroisrael/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/pedroisrael/.ssh/known_hosts:13
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-rsa,ssh-dss-cert-v01@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ssh-ed25519
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: kex_parse_kexinit: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5-etm@openssh.com
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug2: mac_setup: found hmac-md5-etm@openssh.com
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 128/256
debug2: bits set: 517/1024
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 96:ba:5c:04:98:ea:b7:d3:0d:1f:d8:01:4c:23:d1:d6
debug3: load_hostkeys: loading entries for host "ec2-52-67-93-144.sa-east-1.compute.amazonaws.com" from file "/Users/pedroisrael/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/pedroisrael/.ssh/known_hosts:13
debug3: load_hostkeys: loaded 1 keys
debug3: load_hostkeys: loading entries for host "52.67.93.144" from file "/Users/pedroisrael/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /Users/pedroisrael/.ssh/known_hosts:13
debug3: load_hostkeys: loaded 1 keys
debug1: Host 'ec2-52-67-93-144.sa-east-1.compute.amazonaws.com' is known and matches the RSA host key.
debug1: Found key in /Users/pedroisrael/.ssh/known_hosts:13
debug2: bits set: 509/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: key.pem (0x0), explicit
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: key.pem
debug1: read PEM private key done: type RSA
debug3: sign_and_send_pubkey: RSA bb:c8:d5:38:c8:87:74:30:be:05:0c:8c:52:77:77:9c
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

Have no idea on how to proceed! Can someone help? My goal is connect to the server normally again. Or at least copy the backup file to create a new instance if necessary.

A: Launch a new instance, prepare everything (mysqld..). Stop old instance, detach the volume and attach it to new instance. Restore backup.
This involves some downtime, but it can be pretty short. If you are unsure about detach/attach/mount procedure, try it first with some other instances.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing Multiple Fields From a SOQL Query Using FORMAT() The Setup
I've got a horrible feeling I'm being rather dumb and can't see the wood for the trees here, but how do you get more than one field returned when using the SOQL FORMAT() function?
The documentation suggests that it can be used in conjunction with other fields:

The FORMAT function supports aliasing. In addition, aliasing is required when the query includes the same field multiple times. For example:
SELECT Id, LastModifiedDate, FORMAT(LastModifiedDate) formattedDate FROM Account

Yet they neglect to mention what the Type of data the query returns. Because it's using an alias you'd expect something akin to an AggregateResult but the compiler indicates that the type is a list of the object in question.
Experimenting
I've tried running the following code using execute anonymous to see what's going on:
// Case 1: the `Amount__c` field as a regular field plus an aliased version
List<Transaction__c> t = (List<Transaction__c>)[select Id, Amount__c, Format(Amount__c) amt from Transaction__c];
System.debug(t);

// Case 2: the `Amount__c` field using `FORMAT()` with no alias
t = (List<Transaction__c>)[select Id, Format(Amount__c) from Transaction__c];
System.debug(t);

// Case 3: the `Amount__c` field not using `FORMAT()` for the sake of my sanity
t = (List<Transaction__c>)[select Id, Amount__c from Transaction__c];
System.debug(t);

The three corresponding output lines are:

DEBUG|(Transaction__c:{amt=£42.00}, Transaction__c:{amt=£80.00}, Transaction__c:{amt=£33.00})
DEBUG|(Transaction__c:{Id=a0724000006iAz4AAE, Amount__c=42.00}, Transaction__c:{Id=a0724000006iAyzAAE, Amount__c=80.00}, Transaction__c:{Id=a072400000NEoOhAAL, Amount__c=33.00})
DEBUG|(Transaction__c:{Id=a0724000006iAz4AAE, Amount__c=42.00}, Transaction__c:{Id=a0724000006iAyzAAE, Amount__c=80.00}, Transaction__c:{Id=a072400000NEoOhAAL, Amount__c=33.00})

So in case 1 I get the formatted value but nothing else, in case 2 the formatting is nowhere to be seen, and in 3 I get what I'd expect (still sane).
Where it gets really interesting is the variable assignment lines that are included in the logs. These seem to show vectors where the fields are all available, so for case 1, I see this:

VARIABLE_ASSIGNMENT [1]|t|{"s":1,"v":[{"s":2,"v":{"Id":"a0724000006iAz4AAE","Amount__c":42.00,"amt":"£42.00"}},{"s":3,"v":{"Id":"a0724000006iAyzAAE","Amount__c":80.00,"amt":"£80.00"}},{"s":4,"v":{"Id":"a072400000NEoOhAAL","Amount__c":33.00,"amt":"£33.00"}}]}|0x2f4c8335

I've tried assigning to List<Object> and List<SObject> with no success, and took a wild stab with Map<String, Object> with no luck. I find it hard to believe that case 1 is functioning as designed, so what am I missing? Am I missing something obvious or does this appear to be a platform bug?
A Hacky Workaround - Not an Answer
Through some crazy gymnastics I can get a Map<String, Object> representing the full results which is enough for my particular use case right now, but it doesn't really answer the question:
List<Object> o = (List<Object>)JSON.deserializeUntyped(JSON.serialize([select Id, Amount__c, Format(Amount__c) amt from Transaction__c]));
for(Object obj : o)
{
  Map<String, Object> sobj = (Map<String, Object>)obj;
  System.debug(sobj);
}

16:27:21:009 USER_DEBUG [5]|DEBUG|{Amount__c=42.00, Id=a0724000006iAz4AAE, amt=£42.00, attributes={type=Transaction__c, url=/services/data/v37.0/sobjects/Transaction__c/a0724000006iAz4AAE}}

A: It looks to me that this FORMAT() documentation fails to mention that the formatted value can only be obtained using a get of the alias. This produces the expected result for the formatted values and confirms that the type returned by FORMAT is String:
Contact c = [
        select Name, FORMAT(Birthdate) bb, FORMAT(CreatedDate) cc
        from Contact
        where Birthdate !=null
        limit 1
        ];
System.debug('>>> ' + c.Name + ' ' + c.get('bb') + ' ' + c.get('cc'));
System.debug('>>> ' + (c.get('bb') instanceof String));

I get a "duplicate field selected" error if I also include the raw Birthdate field in the query.
PS
Be aware though that there are other gotchas - see LaceySnr's comment about using get('Id') failing if using the the SObject type. Bizarrely though using the SObjectField type works around the problem:
SObject c = [
        select Id, Name, FORMAT(Birthdate) bb, FORMAT(CreatedDate) cc
        from Contact
        where Birthdate !=null
        limit 1
        ];
System.debug('>>> ' + c.get(Contact.Id) + ' ' + c.get(Contact.Name) + c.get('bb'));

(Maybe the underlying implementation is a decorator that fails to forward the get(String) but does forward the get(SObjectField)?)


text:
Q: Anchor send value to Mapped Servlet - pass parameter I have a menu with several categories of books.
When I click on a menu item I want to have a servlet query a database and return the results.
I don;t want to have repeated code, so it'd be nice to just use one servlet, but somehow have the servlet identify which link in the menu was clicked and perform the appropriate actions.
Is the only way to do this by submitting a form?
Also, I should mention that despite being horrible practice, I will be targeting a different frame for the results.

A: No, you don't need a form submit. Parameters are passed by links using a query string:
Novels
Science Fiction
...

A: This post is may be old. But here is my answer.

You can create a link like this in jsp page.
 Add New Book

 List All Books

And call your controller like this.
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getServletContext().getContextPath()+request.getServletPath();

        try {
            switch (action) {
            case "/new":
                showNewForm(request, response);
                break;
            case "/insert":
                insertBook(request, response);
                break;
            case "/delete":
                deleteBook(request, response);
                break;
            case "/edit":
                showEditForm(request, response);
                break;
            case "/update":
                updateBook(request, response);
                break;
            default:
                listBook(request, response);
                break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

This is for a servlet that keeps as the startup page.

You can update the href attribute according to the url pattern of the servlet.


text:
Q: String problem wheather it is pel or not pel String pelindrome or not. There is no syntax error but y it is showing wrong output
Output it is showing:
Noob
Is pel

#include<iostream>
#include<string.h>
int main()
{
  char i[]="noop";
  court<<i<<endl;
  (i==strrev(i))?cout<<" pel": cout<<" not pel";
  cout<<endl;
  return 0;
}


text:
Q: How do I extend a model class to another model? I am trying to extend a class to another class that will collect them as a list.
model:
public class Brand
    {
        public int BrandId { get; set; }
        public string Name { get; set; }
        public string Guid { get; set; }
        public float Rating { get; set; }
        public string Industry { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Postal { get; set; }
        public string CountryCode { get; set; }

        public virtual Snapshot Snapshot { get; set; }
    }
public class Snapshot
{
        public int ID { get; set; }
        public string Guid { get; set; }
        public int CompanyID { get; set; }
        public string CompanyName { get; set; }
        public string Email { get; set; }
        public DateTime DateTimeSent { get; set; }
        public string Subject { get; set; }
        public string Html { get; set; }
        public string Image { get; set; }
        public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
    {
        public Brand Brand { get; set; }
        public List<Snapshot> SnapshotItems { get; set; }

    }

controller:
public ActionResult Index(string brandGuid)
    {
        BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
        Brand brand = GetBrand(brandGuid);
        viewModel.Brand = brand;
        List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
        viewModel.SnapshotItems = snapshot;

        List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
        viewModelList.Add(viewModel);

        return View(viewModelList.AsEnumerable());
    }

private Brand GetBrand(string brandGuid)
{
    Brand brand = new Brand();
    string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
    MySqlConnection dbConn = new MySqlConnection(dbConnString);
    dbConn.Open();
    MySqlCommand dbCmd = new MySqlCommand();
    dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
    dbCmd.Connection = dbConn;
    MySqlDataReader dbResult = dbCmd.ExecuteReader();
    if (dbResult.Read())
    {
        brand.Guid = dbResult["brand_guid"].ToString();
        brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
        brand.Industry = dbResult["industry_name"].ToString();
    }
    dbResult.Close();
    dbConn.Close();

    return brand;
}

private List<Snapshot> GetBrandSnapshots(int brandId)
{
    string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
    MySqlConnection dbConn = new MySqlConnection(dbConnString);
    dbConn.Open();
    MySqlCommand dbCmd = new MySqlCommand();
    dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
    dbCmd.Connection = dbConn;
    MySqlDataReader dbResult = dbCmd.ExecuteReader();
    List<Snapshot> snapshots = new List<Snapshot>();
    while (dbResult.Read())
    {
        snapshots.Add(new Snapshot
        {
            SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
            Subject = dbResult["subject"].ToString(),
            DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
            Image = dbResult["image"].ToString(),
            Email = dbResult["email"].ToString(),
            ContentType = dbResult["content_type"].ToString(),
            Type = dbResult["type"].ToString()
        });
    }
    dbResult.Close();
    dbConn.Close();

    return snapshots;
}

edit
FIXED
The issue was the VIEW was not referencing the ViewModel as an IENumerable<>. FACEPALM.
@model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
@{
    ViewBag.Title = "Index";
}
@foreach(var item in Model)
{
    @item.Brand.Guid;
    for(int i = 0; i< @item.SnapshotItems.Count; i++)
    {
        @item.SnapshotItems[i].Subject<br/>
    }
}

That resolved the issue.
Thank you both experts for the insights... i took both advice and came to this solution.

A: you are doing wrong, it is a list.
you cannot add element this way. Create object and add that object in list by calling Add()
do like this to add items in it:
List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
    while (dbResult.Read())
    {
        BrandEmailList brandSnapshots = new  BrandEmailList (); // create an object
        brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
        brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
        brandSnapshots.DateTimeSent = dbResult["date_sent"];
        brandSnapshots.Subject = dbResult["subject"].ToString();
        brandSnapshots.Image = dbResult["image"];

       brandSnapshotsList.Add(brandSnapshots); // add it in list
    }

EDIT:
List is a generic thing, you don't need to create a class for it. you can just instantiate a list and add items in it.
why are you doing like that you can do it this way simply:
List<Snapshot> brandSnapshotsList = new List<Snapshot>();
        while (dbResult.Read())
        {
            Snapshot brandSnapshots = new  Snapshot(); // create an object
            brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
            brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
            brandSnapshots.DateTimeSent = dbResult["date_sent"];
            brandSnapshots.Subject = dbResult["subject"].ToString();
            brandSnapshots.Image = dbResult["image"];

           brandSnapshotsList.Add(brandSnapshots); // add it in list
        }

A: Building on what Ehsan Sajjad did, looking at public IEnumerator<Snapshot> BrandEmails, i believe what you look for looks more like this:
public class Snapshot
{
    public int ID { get; set; }
    public string Guid { get; set; }
    // ...
}

public class BrandEmailList : List<Snapshot>
{
}

You need not even create a new type for your brand email list, you can use List<Snapshot> directly.
public ViewResult Whatever() {
    var brand = GetBrand(brandName);
    var brandSnapshots = GetBrandSnapshots();

    return View(brand, brandSnapshots);
}

private Brand GetBrand(string brandName)
{
    try
    {
        var brand = new Brand();
        brand.Name = brandName;
        // database stuffs ...
        return brand;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private List<Snapshot> GetBrandSnapshots()
{
    // ...
    // DB stuffs -- that *really* should not be in the controller anyways.
    // ...

    var snapshots = new List<BrandEmailList>();
    while (dbResult.Read())
    {
        // object initializer syntax
        snapshots.Add(new Snapshot {
            ID = Convert.ToInt32(dbResult["snapshot_id"]),
        Guid = dbResult["snapshot_guid"].ToString(),
        DateTimeSent = dbResult["date_sent"],
        Subject = dbResult["subject"].ToString(),
        Image = dbResult["image"],
        });
    }
    return snapshots
}

As a side note, mixing database access into controller methods can be a bad idea. It does not have to be, but it can be. Generally, fetching data from the database happens at a different "level" than serving a MVC result. MVC controller don't have the "purpose" to talk to a database, that work can/should be delegated to a dedicated type. Compare the single responsibility principle part of the SOLID principles.


text:
Q: Correct SQL Statement returns correct row that represents front month expiry contract I have a SQL server 2008 R2 database of trade records for several equity options, each at one minute intervals, and each minute contains records for several expiry. e.g.,
Symbol, TradeDate, Expiry, Open, High, Low, Close
AMZN, 4/01/2009 9:31:00, 4/17/2009, 8, 10, 9, 8.5
AMZN, 4/01/2009 9:31:00, 5/17/2009, 10, 11, 10, 11
AMZN, 4/01/2009 9:31:00, 6/18/2009, 12,13,12,12
GOOG, 4/01/2009 9:31:00, 4/17/2009, 8, 9, 7, 7.5
AMZN, 4/01/2009 9:32:00, 4/17/2009, 8.2, 8.9, 8.3, 8.5
AMZN, 4/01/2009 9:32:00, 5/16/2009, 3, 4, 4, 4
...
AMZN, 4/20/2009 9:31:00, 5/16/2009, 8.5, 9, 8.75, 8.75
AMZN, 4/20/2009 9:31:00, 6/18/2009, 9, 10, 9, 9.2

In options there is always a notion of the front month contract. For this problem, define the front month contract to be: If there are TradeDate entries less than the expiry date for that contract, that is the front month. Else, the front month is the next months contract. So for example, in the data above, on 4/01/2009, the AMZN front month is the contract that expires on 4/17/2009. However, when we move to TradeDate 4/20/2009, the front month is the 5/16/2009 contract since the 4/17/2007 contract expired over the weekend.
What is the SQL statement that would always return all the correct rows giving the "front month contract" based on what the TradeDate is?

A: From what you have described. The following query should do it. A self join :
SELECT T1.Symbol, T1.TradeDate, T1.Expiry, MIN(T2.expiry) AS FrontMonrhContract, T1.Open, T1.High, T1.Low, T1.Close FROM <TABLE> T1, <TABLE> T2 WHERE T1.TradeDate <= T2.Expiry GROUP BY T1.Symbol , T1.TradeDate, T1.Expiry

But it will not work if there is no entry for a trade of the FrontMonth Contract.
What i would feel better is that you either hand input a list of Expiries or compute them based on some rule, like last Friday of the month or something like that (if there is a rule). So that you do not risk miscalculating the front month if there is no trade for the frontMonth contract.
Better still do it in your application instead of SQL, as SQL is not meant for such work. In your application it would be a simple comparison with a list of expiries.
I have reduced execution time of a charting function which worked on data from a sqlite database by over 90% by doing such computations in the application itself instead of SQL.
Update:
Try the following query. It assumes the table name to be TRADES.
SELECT
    T1.Symbol,
    T1.TradeDate,
    T1.Expiry,
    MIN(T2.expiry) AS 'FrontMonrhContract' ,
    MIN(T1.[Open]) AS 'Open',
    MIN(T1.[High]) AS 'High',
    MIN(T1.[Low]) AS 'Low',
    MIN(T1.[Close]) AS 'Close'
FROM
    TRADES T1, TRADES T2
WHERE T1.TradeDate <= T2.Expiry AND T1.Symbol = T2.Symbol
GROUP BY T1.Symbol , T1.TradeDate, T1.Expiry

I just built a sample table with the data you provided in the question and this query works as expected on that data set. For note I have SQL Server 2005
Update 2:
To optimize the execution of the query, try adding an Index with the three GROUP BY columns Symbol, TradeDate, Expiry in that order.
I created a query execution plan and over 60% time is for resolving the GROUP BY, and after adding this index in my sample db it was completely gone.


text:
Q: Optimising a code in C++11 For a given positive integer y(y > 1), if we can find a largest integer k and a smallest positive integer x, such that x^k=y, then the power of y is regarded as k.
Calculate the sum of the power of the integers from a to b. (2<= a <= b <=10^18)
For each test case, there is one line containing two integers a and b.
End of input is indicated by a line containing two zeros.
Time limit: 11s
I made this code:
#include <iostream>
#include <cmath>
using namespace std;
int main (void)
{
    long long i,j,count;
    while (1)
    {
        cin>>i>>j;
        count = 0;
        if ( i!= 0 && j != 0 )
        {
            if ( i > 1 && j > 1 )
            {
                while ( i <= j )
                {
                    long long temp = -9999;
                    long long x = 2L;
                    long long k = 0L;
                    while ( temp != i )
                    {
                        temp = pow(x,k);
                        if ( temp > i )
                        {
                            x++;
                            k = 0;
                        }
                        else if ( temp == i )
                        {
                            break;
                        }
                        else
                            k++;
                    }
                    count = count + k;
                    i++;
                }
             cout<<count<<"\n";
            }
        }
        else if ( i == 0 && j == 0 )
            break;
    }
    return 0;
}

Basically, from 2 to till the number is obtained for which I have the required condition satisfied, I calculate the numbers. This is exceeding the time limit. Any better approach?
Thanks! :)
Edit:
#include <iostream>
#include <cmath>
using namespace std;
int main (void)
{
    long long i,j,count;
    while (1)
    {
        cin>>i>>j;
        count = 0;
        if ( i == 0 && j == 0 )
            break;
        else
        {
            if ( i > 1 && j > 1 )
            {
                while ( i <= j )
                {
                    long long x = 2;
                    long long k = 1;
                    long long temp = 1;
                    while ( temp != i )
                    {
                        temp = temp*x;
                        if ( temp > i )
                        {
                            x++;
                            k = 1;
                        }
                        else if ( temp == i )
                        {
                            break;
                        }
                        else
                            k++;
                     }
                    count = count + k;
                    i++;
                }
            cout<<count<<"\n";
            }
    }
}
return 0;

}
Made the changes. Need further optimization. Any suggestions?

A: That kind of problem isn't solved by hacking code together. It is solved by thinking about the problem. What if I give you the numbers a = 2 and b = 10^18: How many numbers will you be examining? I get about 10^36. That should make it clear that there is some way that you can find by thinking that is a lot lot faster (because no computer in the world can do 10^36 calculations, and doing 10^18 calculations will keep a decent computer busy for a year).
Let's go directly at the case a = 2, b = 10^18. Almost all those numbers have power = 1. About a billion have power = 2. There are only about a million numbers with power >= 3, and you can find all of them very quickly. That should be enough of a hint.
Think about it: If your computer had an instruction that calculates the power of a number x in one nanosecond, and you added the power of the numbers from 2 to 10^18, how long would that take? So it's obvious that this is not the solution.

A: As this seems to be homework, I won't give you an implementation, just a few tips:

*

*In the while loop, instead of using pow(x, k) for each iteration, you should use the fact that x^(k+1) = x^k * x (initialize temp cleverly and then multiply it by x on each iteration)

*Your two ifs are redundant, you can simply remove if ( i!= 0 && j != 0 ) and leave the inner if

*To make your code cleaner and easier to read, you should declare functions. In this case, a function to compute the sum of the powers of X would isolate the inner while loop.

*You should check the validity of the input (2<i<j<10^18)

Have you also tried to write on a paper what two or three iterations of the algorithm would be?
Hint: http://www.trans4mind.com/personal_development/mathematics/series/sumGeneralPowersNaturalNumbers.htm


text:
Q: Insert statement not inserting value for one field So I'm working on some SQL for a program I am developing, and I am having an odd issue that I've never really seen before.  Here is the query that's giving me trouble:
insert into [db].[dbo].[table] (JobNum, JobSeq, OperationNumber, WorkCenter,
 ResourceGroup, Material, MaterialQuantity, MaterialCost, LbrHoursPerPiece,
 ExtendedDescription, PreviousMaterial, UniqueID)
values ('J000001234', 1234, 123, 'UFAN', 'FANASSY', '12345678',
 4, 50, 1, 'DESC', '', '')

I then do a select from the same table:
SELECT * FROM [db].[dbo].[table]
where JobNum = 'J000001234'

And this is what is returned:

For some reason, even though I give it a value of 50, the MaterialCost field is showing NULL, and I can't figure out why when everything else is being inserted properly.  Here is the table design, just in case:

Any thoughts?
EDIT:  I want to point out that while this is a query I'm using in .NET code, for now I am only testing it in SQL Server Management Studio.
Also, a commenter asked for the create query, so:
...
CREATE TABLE [dbo].[table](
[JobNum] [nvarchar](20) NOT NULL,
[JobSeq] [int] NOT NULL,
[OperationNumber] [int] NULL,
[WorkCenter] [nvarchar](6) NULL,
[ResourceGroup] [nvarchar](30) NULL,
[Material] [nvarchar](30) NULL,
[MaterialQuantity] [decimal](18, 8) NULL,
[MaterialCost] [decimal](18, 5) NOT NULL,
[LbrHoursPerPiece] [decimal](10, 5) NULL,
[ExtendedDescription] [nvarchar](300) NULL,
[PreviousMaterial] [nvarchar](300) NULL,
[UniqueID] [varchar](200) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING ON
GO

ALTER TABLE [dbo].[Table] ADD  CONSTRAINT     [DF_Table_MaterialCost]  DEFAULT ((0.00)) FOR [MaterialCost]
GO

EDIT 2:  So I took the CREATE TABLE query and used it to create another table, tableTEST, that is identical to the trouble table.  When executing the same query on the TEST table, it worked fine.  I also want to point out that the MaterialCost field that isn't getting the right data was added to the table much later after initially creating it.

A: In the end, I was able to solve the problem without ever discovering the root cause.  The MaterialCost field was added to the table much later after it already had a fairly large amount of data, so there was obviously something odd going on there.
To fix my problem, I created a copy of the original table, copied all of the data over to the new table, and dropped the original.  After doing that, the insert statement worked properly.  So like I said, it works now, but I don't really have any details on the root cause, other than that field being new.

A: Remove allow nulls on that column and see if the program raises an exception. I am sure it would. some where your code is not putting a value into that column.

A: Check for a triggers, something could be removing your value if it doesn't fit a business rule.


text:
Q: URL patterns for GET I want to define url pattern for the below url and read these parameters in views
http://example.com/user/account?id=USR1045&status=1

I tried
url(r'^user/account/(?P<id>\w+)/(?P<status>\d+)/$', useraccount),

In Views
request.GET ['id']
request.GET ['status']

but it is not working, please correct me.

A: django url patterns do not capture the query string:

The URLconf searches against the requested URL, as a normal Python
  string. This does not include GET or POST parameters, or the domain
  name.
For example, in a request to http://www.example.com/myapp/, the
  URLconf will look for myapp/.
In a request to http://www.example.com/myapp/?page=3, the URLconf will
  look for myapp/.
The URLconf doesn't look at the request method. In other words, all
  request methods – POST, GET, HEAD, etc. – will be routed to the same
  function for the same URL.

So, with that in mind, your url pattern should be:
url(r'^user/account/$', useraccount),

In your useraccount method:
def useraccount(request):
    user_id = request.GET.get('id')
    status = request.GET.get('status')

    if user_id and status:
        # do stuff
    else:
        # user id or status were not in the querystring
        # do other stuff

A: Querystring params and django urls pattern are not the same thing.
so, using django urls pattern:
your url:
http://example.com/user/account/USR1045/1

urls.py
url(r'^user/account/(?P<id>\w+)/(?P<status>\d+)/$', views.useraccount)

views.py
def useraccount(request, id, status):


text:
Q: JavaFX Coloring XYChart.Series I am trying to style my JavaFX Area-Chart, but can't find any way to set color to specific series. I know, that I can style via CSS, but i want to do it in the code also.
How can i do that?
1.) How to set a color to Area-Chart with Inline Styles?
Thank you for your help.
@Jose:
I done it before like this, but it does not work for me!
@Override
    public void start(Stage primaryStage)
    {
        final AreaChart<String, Number> areaChart = new AreaChart<>(new CategoryAxis(), new NumberAxis());

        ObservableList<XYChart.Data<String, Integer>> xyList = FXCollections.observableArrayList(
            new XYChart.Data<>("P1", 30),
            new XYChart.Data<>("P2", 40),
            new XYChart.Data<>("P3", 30));
        XYChart.Series series = new XYChart.Series(xyList);
        areaChart.getData().addAll(series);

        Button button = new Button("Change style");
        button.setOnAction(new EventHandler<ActionEvent>()
        {

            @Override
            public void handle(ActionEvent arg0)
            {
                int redColor = 0, greenColor = 127, blueColor = 195;
                double opacity = 0.3;
                areaChart.setStyle("CHART_COLOR_1: rgb(" + redColor + "," + greenColor + "," + blueColor + "); "
                    + "CHART_COLOR_1_TRANS_20: rgba(" + redColor + "," + greenColor + "," + blueColor + "," + opacity + ");");

            }
        });

        VBox root = new VBox();
        root.getChildren().addAll(button, areaChart);
        Scene scene = new Scene(root, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

A: This answer does not work in Java 7, because the default CSS stylesheet is Caspian, not Modena.
In Caspian these constants for the main color palette are not defined: CHART_COLOR_1, CHART_COLOR_1_TRANS_20,...
So if you want to apply inline styling one way to do it is by finding the series with a lookup and apply your styling to symbols, lines and/or areas, based on their CSS selectors. For instance:
@Override
public void start(Stage primaryStage) {

    final AreaChart<String, Number> areaChart = new AreaChart<>(new CategoryAxis(), new NumberAxis());

    ObservableList<XYChart.Data<String, Integer>> xyList = FXCollections.observableArrayList(
        new XYChart.Data<>("P1", 30),
        new XYChart.Data<>("P2", 40),
        new XYChart.Data<>("P3", 30));
    XYChart.Series series = new XYChart.Series(xyList);
    areaChart.getData().addAll(series);

    Scene scene = new Scene(areaChart, 400, 300);
    primaryStage.setScene(scene);
    primaryStage.show();

    int redColor = 0, greenColor = 127, blueColor = 195;
    double opacity = 0.3;

    for(Node symbol : areaChart.lookupAll(".default-color0.chart-area-symbol")){
        symbol.setStyle("-fx-background-color: rgb(" + redColor + "," + greenColor + "," + blueColor + "), white; ");
    }
    Node line = areaChart.lookup(".default-color0.chart-series-area-line");
    line.setStyle("-fx-stroke: rgb(" + redColor + "," + greenColor + "," + blueColor + "); ");
    Node area = areaChart.lookup(".default-color0.chart-series-area-fill");
    area.setStyle("-fx-fill: rgba(" + redColor + "," + greenColor + "," + blueColor + "," + opacity + "); ");
}

EDIT
The above solution will work up to 8 series.
For any number of series this other approach will work too:
    int numSeries=10;
    final int[] redColor = new int[numSeries];
    Arrays.fill(redColor, 0);
    final int[] greenColor =new int[numSeries];
    Arrays.fill(greenColor, 127);
    final int[] blueColor = new int[numSeries];
    Arrays.fill(blueColor, 195);
    double opacity = 0.3;

    for(int i=0; i<numSeries; i++){
        for(Node n : areaChart.lookupAll(".series"+i)){
            n.setStyle("-fx-background-color: rgb(" + redColor[i] + "," + greenColor[i] + "," + blueColor[i] + "), white; "
                    + "-fx-stroke: rgb(" + redColor[i] + "," + greenColor[i] + "," + blueColor[i] + "); "
                    + "-fx-fill: rgba(" + redColor[i] + "," + greenColor[i] + "," + blueColor[i] + "," + opacity + "); ");
        }
    }

A: You can use this:
chart-series-area-line series<i> default-color<j>

Where  is the index of the series and  is the series' color index
as specificated in css reference this the same you can use with setStyle function of your areaChart
you can use this:
Node line = areaChart.lookup(".default-color0.chart-series-area-line");
line.setStyle("-fx-stroke: rgb(" + redColor + "," + greenColor + "," + blueColor + "); ");


text:
Q: Test is not read a value of a properties file I'm developing an app (Java) and there is a test that it fails me. This mistake is because I want to read a value that it's in a properties file, but this value is null however If I execute my app skipping the tests, it works ok, it reads the value of the properties file without problem, Do I have to do something different to read this property in test package?
My test class
@Test
public void shouldBeControllerInitial() {

   String index = initController.init();

   assertEquals("Should be same to the index, it's main page", INDEX,
                index);
}

My controller class
@Controller
@RequestMapping(value = "/")
public class InitController {

    @Value("${path.index}")
    private String index;

    @RequestMapping(method = RequestMethod.GET)
    public String init() {

        return index;
    }

}

My config class
@Configuration
@PropertySource("classpath:/path.properties")
public class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

error message
java.lang.AssertionError: Should be same to the index, it's main page
expected:<index> but was:<null> ...

Can anyone help ?

A: As we have only test's body and not a whole source file, so I can only suggest:

*

*check that in test you are injecting initController and didn't creating it with new

*ensure that test uses your Config (you should have annotation like this: @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = Config.class)


text:
Q: Phing Failtask if Esc is pressed . It's possible ? I've got a  Phing buildfile with some tasks.
Problem is I don't have one way to quit de script if something goes wrong, right now, my only possibility is to close cmd and open cmd again.
What I want is abort the execution of the task by pressing "esc".
Any idea ?
Thanks

A: You shouldn't kill a Phing build script while it's running, because it might leave things in a bad state. Instead the script should check for an indicator to quit at key points in the script.
You can create a temp file at the start of the script. During execution check that the file still exists, and if it has been deleted by the user abort the build script.
At the start of your script create a temp file.
    <touch file="delete.me"/>

Then at different points in your script check that it still exists.
    <if><not><available file="delete.me"/></not><then><fail message="User aborted build script." /></then></if>

You can now abort a script at anytime by deleting the delete.me file.
Alternatively, you can prompt for a user to continue the script using the InputTask.
    <input propertyName="cont" defaultValue="n" promptChar="?" validArgs="y,n">Continue</input>
    <if><equals arg1="${cont}" arg2="n"/><then><fail message="User aborted build script."/></then></if>

The above will block execution of the script until a user presses Y to continue.
If you're performing file operations or SQL commands that take a long time to execute, then it's best to let them finish first before aborting the script. Pressing ctrl+c should only be done if you suspect the script is doing something wrong.


text:
Q: gRPC handling metadata (headers) end-to-end I have service (gRPC) which I define by protobuf and the service has one method to call.
I want to call the method and pass a header (as we usually do with rest) using clientStub of gRPC service but I couldn't find how to usually to do in gRPC. I decided to do it via ClientInterceptor and put my ClientInterceptor to ClientStub.
public class ClientHeadersInterceptor implements ClientInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientHeadersInterceptor.class);

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
        return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                headers.put("test", "test");
                headers.put("test1", "test");
                super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
                    @Override
                    public void onHeaders(Metadata headers) {
                        LOGGER.info("header received from server:" + headers);
                    }
                }, headers);
            }
        };
    }
}

So I need these values of headers in my business logic. I mean how to get these values in impl Service of gRPC?
I solved this by creating ServerInterceptor which gets all values of metadata and put in Context.
@GRpcGlobalInterceptor
public class ServeInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall,
                                                                 Metadata metadata,
                                                                 ServerCallHandler<ReqT, RespT> serverCallHandler) {
        Context current = Context.current();
        current = Context.current()
                    .withValue("test", metadata.get("test"))
                    .withValue("test1", metadata.get("test1"));

        return Contexts.interceptCall(current, serverCall, metadata, serverCallHandler);
    }

}

Then, finally, when I put everything in Context I use the context wherever I need to get these values.
String testValue = Context.key("test").get();
String test1Value = Context.key("test1").get();

So is it really the only way to get in your service metadata (headers) from a client?


text:
Q: Topos Without point, from the point of view of logic I am a little troubled by the following "paradox" :
Let $X$ be a non trivial (Grothendieck) topos without Set points.
We want to look at this situation from the point of view of logic: $X$ classifies some geometric theory $T$. The assumption on $X$ means that $T$ is consistent but has no model in Set. This is not in contradiction with Gödel's theorem because the theory $T$ might not be a "finitary first order theory".
We have been able to prove that $X$ doesn't have points, hence we have a proof (using boolean logic and possibly the axiom of choice) that the theory $T$ doesn't have any model.
Let now $Y$ be a Boolean topos with internal axiom of choice. It should be possible to apply the previous proof in the internal logic of $Y$, and then prevent $T$ to have any model in $Y$... But this is not the case: Barr's covering theorem implies there is a topos $Y$ that cover $X$ and hence which has a $T$-model.
Can someone explain me why this is not working ? Or give an example where $T$ and $Y$ are explicit?

A: Here is a concrete example of a consistent geometric theory that has no model in $\mathbf{Set}$ but does have a model in a Boolean Grothendieck topos.
Our base theory $T$ is an expansion of the theory of linear orders with a constant $c_q$ for each rational number $q$. In geometric form, the base axioms are:
$$x = y \lor x \lt y \lor y \lt x$$
$$x \lt y \land y \lt z \Rightarrow x \lt z$$
$$x \lt x \Rightarrow \bot$$
together with the axioms $c_q \lt c_r$ for all pairs of rationals $q \lt r$.
In addition to the above, we add an axiom which says that the $c_q$'s form a dense subset
$$x \lt y \Rightarrow \bigvee_q (x \lt c_q \land c_q \lt y).$$
A model of $T$ is a linear order with a countable dense subset isomorphic to $\mathbb{Q}$. In other words, models of this theory in $\mathbf{Set}$ are, up to isomorphism, subsets of $\mathbb{R}\cup\lbrace\pm\infty\rbrace$ that contain $\mathbb{Q}$. In particular, models of this theory all have size at most $2^{\aleph_0}$.
Now expand the theory further to a theory $T_I$ by adding new constants $d_i$ for each $i$ in the set $I$, together with the axioms $d_i \lt d_j \lor d_j \lt d_i$ when $i, j$ are distinct elements of $I$. If $|I| \gt 2^{\aleph_0}$ then our new theory $T_I$ has no model in $\mathbf{Set}$. However, in the Grothendieck topos for adding $I$ many Cohen reals side by side (see below) this theory does have a model since $2^{\aleph_0} \geq |I|$ in that topos. So this is a consistent geometric theory that has a model in some Boolean Grothendieck topos but no model in $\mathbf{Set}$.
(The Grothendieck topos for adding $I$ many Cohen reals side-by-side is obtained by imposing the double-negation topology on the poset category of finite partial functions $I\times\omega\to2$. Note that the double-negation topology is always Boolean. This is not the Barr cover for the classifying topos of $T_I$ but it's perhaps easier to understand what it looks like.)


text:
Q: Twitter bootsrap model fade on clicking link_to but black fade appears on the modal I try to fade modal on clicking the link but black fade appear on the modal popup following is my code of modal and link
clicking on the following link modal fade
 <%= link_to 'New Trade','#myModal', :class => 'btn',:style => 'float:right;', :role => 'button', :data =>{ :toggle => 'modal', :keyboard => true, :backdrop => true } %>

And following is modal code

    <%= simple_form_for @trade_category, :url => create_trade_category_path(@trade_category), :html => { :class => 'form_height'} do |f| %>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

New Trade Category

          <%= f.input :name,:lable => false, :autofocus => true, :placeholder =>"Trade category name", :class=> 'input-block-level' %>

        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <%= f.submit "Create Trade category", :class=> "btn btn-primary" %>

    <% end %>

And I got the following out put

CSS are as under
.modal-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1040;
  background-color: #00000}
.modal {
  position: fixed;
  top: 10%;
  left: 50%;
  z-index: 1050;}

A: problem solved in application file the parent div navbar position is fixed so I remove the position fixed and now it is working fine.


text:
Q: Mobile Map disappears on navigation I'm using Qooxdoo 3.0 and started work on a mobile app, but my OpenLayers map disappears after I navigate to a new page and then try to go back to the map page. It works fine on a desktop, but not on the iPad that I'm testing it on. It almost seems that the map gets pushed behind the page on the show command. Is there a way to move it back up to the top or maybe there is something else happening?  Here is the code:
  // Initialize both pages
  var mapPage =  meddv2.page.Maps.getInstance();
  var controlPanel = meddv2.page.ControlPanel.getInstance();

  // *** show the map page *** - map does not appear
  controlPanel.addListener("back", function() {
      mapPage.show({reverse:true});

  // *** I thought this may help which calls map.updateSize() in the map class
      mapPage.redrawMap();
    }, this);

  // Show the Control Panel
  var controlPanelButton = new qx.ui.mobile.navigationbar.Button("Control Panel");
  controlPanelButton.addListener("tap", function(){
      controlPanel.show();
  }, this);
  mapPage.getLeftContainer().add(controlPanelButton);

  // Add the pages to the page manager.
  var manager = new qx.ui.mobile.page.Manager(false);
  manager.addDetail([
    mapPage,
    controlPanel
  ]);

  //Show the map page on load
  mapPage.show();

Thanks for your help!

A: On which device does this behavior occur?
What kind of Map do you use? OpenLayers? Google Maps?
You could try redraw that map on page "start" event.
Might be a rendering bug, please try following CSS statement in your "styles.css":
* {
  -webkit-backface-visibility:hidden;
}

It that helps, you have to find out, which div element needs the fix.
These are the styles I applied in qx.Mobile Maps demo. This may help you prevent the rendering bug.
#osmMap {
  -webkit-transform: translate3d(0,0,0);
}

#osmMap > div {
  -webkit-box-flex: 1;
  -moz-box-flex: 1;
  box-flex: 1;
}

.olMapViewport {
  position:static !important;
}


text:
Q: How to update Swift dependencies in Xcode After I create a new swift package with dependencies I call swift package generate-xcodeproj. If my dependencies have a new version I call swift package update. The new version of my dependency gets downloaded and built but Xcode now has a bad reference to the old version of the dependency. I can call swift package generate-xcodeproj again but this will remove any custom targets I have setup.
How do I update my swift dependencies and my Xcode project without deleting my custom targets?

A: I just stumbled upon this question and found that the solution to "How to update swift dependencies in Xcode" has probably changed now that Swift Packages have been around for a few years.
For me, the solutions was to simply go to File -> Swift Packages -> Update to Latest Package Versions.

A: Many of the problems with packages not updating are because the swift package version rules limit the automatic package updates to the current major version only, i.e v3.3.1 of a package will update to v3.4.0, but will not update automatically to v4.0.1. Therefore using the update options in Xcode does not necessarily get the latest major version of a package.
To resolve, Open the project from the project panel, select the project (not the targets), then select the "Swift Packages" tab. Double click on the package you want to update and change the minimum version to the next major version.

A: I had an issue with CryptoSwift using Xcode 12.5. My version was 1.3.1 and the issue was fixed in 1.4.0.
I tried :

*

*updating by File -> Swift Packages -> Update to Latest Package Versions.

*xcodebuild -resolvePackageDependencies

But both did not work.
I manually went and changed target -> Swift packages -> Version rules
and Xcode automatically installed the newer version and I was out of my error.

A: - Update a single dependency using Xcode
This method will save a lot of resources and time. Because it won't force other packages to redownload.
Double click on the package in the tab you mentioned and change the version to anything else. It will then recheck the remote repo. The benefit of doing this is to only update the selected package. (Also, it's better to have the current using version be set in the package.)

- Update ALL dependencies using Xcode
From File -> Swift Packages -> Update to Latest Package Versions

 Single package with GUI (Xcode 12 and above)
Right-click on the package from the left navigation pan and select Update Package

note that you will see Xcode saying update all packages but it will update only the selected one

A: Instead of trying to preserve your changes to generated project, you can manage dependencies in a separate project, like CocoaPods does.
When starting new project:

*

*create Xcode project for your app MyApp.xcodeproj

*save as a workspace MyApp.xcworkspace

*create package for your dependencies

mkdir MyDeps && cd MyDeps
swift package init --type library

*add dependencies to Package.swift

*generate Xcode project for the dependencies package

swift package generate-xcodeproj

*add generated project MyDeps.xcodeproj to your workspace MyApp.xcworkspace

*add target MyDeps.framework to Linked Frameworks of your app MyApp.xcodeproj
With this setup you can freely update dependencies in Package.swift and regenerate dependent project as needed.

A: If the library is used by a particular target, the library won't be updated to the latest version, at least in my case (Xcode 14.2).
I was using OneSignal which requires to add a target (OneSignalNotificationServiceExtension) which depends on the OneSignal library in the "Frameworks and libraries".
So:

*

*remove the required lib voice from the dependency in the extension,

*update the library with right click -> "update package"

*re-add to the extension the updated library in the "Frameworks and libraries"

Screenshot of which row to delete to let the library update properly (remember to read later).


text:
Q: How can I implement an assignment operator in a class template?` I thought my problem was answered by this, but I can't get the following to compile:
#include <string>

template<class C>
class tKeySet {
  protected:
    bool set;
    static const std::string key;
};

template<class C, typename T>
class tKeySetType : private tKeySet<C> {
  protected:
    T m_val;
};

template<class C>
class tKeySetString: private tKeySetType<C, std::string> {
  public:
    tKeySetString<C>& operator=(const std::string &str) {
        this->set = true;
        this->m_val = str;
        return *this;
    }
};

class foo : private tKeySetString<foo> { };
template<> const std::string tKeySet<foo>::key = "foo key";

int main(void) {
    foo f;

    f = std::string("foo");

    return 0;
}

How can I make the assignment operator in tKeySetString<C> work with std::string?

A: foo privately inherits from tKeySetString<foo>, which means that operator= will not be part of its public interface.
You can bring it in by writing
public:
    using tKeySetString::operator=;

in the definition of foo.


text:
Q: How to trigger "play" in a HTML5 video with hidden controls on IE8 with modernizr I managed to play a HTML5 video using video-js on IE8 with help of Modernizr, now the problem is that I want to have the video controls hidden and trigger "play" with a link on the page.
I have a solution that works fine anywhere but ie8 and ie7.
Any ideas please?

    <video id="example_video_1" class="video-js vjs-default-skin" preload="none" width="640" height="264" poster="http://video-js.zencoder.com/oceans-clip.png" data-setup="{}">
    <source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />
    <source src="http://video-js.zencoder.com/oceans-clip.webm" type='video/webm' />
    <source src="http://video-js.zencoder.com/oceans-clip.ogv" type='video/ogg' />
    <track kind="captions" src="captions.vtt" srclang="en" label="English" />
</video>

play

A: The issue your encoutnering is that your code:
$('video').get(0).play();

Will only work with the native HTML5 player. Since IE7/8 both don't support the HTML5 <video>element, they will both see the Flash fallback provided by Video.js.
You should take a look at the Video.js API. Instead of your above code, perhaps try:
myPlayer = _V_('example_video_1');

$('.play').click(function(){
    myPlayer.play();
});


text:
Q: Bayes network probability question I'm looking at this problem as I review for an exam and I would appreciate it if anyone can give me work/answers to Pr(c), Pr(b), Pr(b,c) and Pr(c,d) so I can check my solutions, and use the work to figure out how I was off if so.

so far i have gotten
Pr(c) = Pr(c|a)*Pr(a) + Pr(c| !a)*Pr(!a) = .48
Pr(b) = Pr(b|a)*Pr(a) + Pr(b| !a)*Pr(!a) = .56
not 100% sure or if these are correct or how to proceed when it comes to the next 2

A: What you have done so far for the calculation of $p(b)$ and $p(c)$ is correct:
$$p(c) = p(c|a)\,p(a) + p(c|\neg a)\,p(\neg a) = 0.48$$
$$p(b) = p(b|a)\,p(a) + p(b|\neg a)\,p(\neg a) = 0.56$$
For the calculation of $p(b,c)$, notice that $$p(b,c)=p(b,c,a)+p(b,c,\neg a)=p(b,c|a)\,p(a)+p(b,c|\neg a)\,p(\neg a)$$
Since $b$ and $c$ are independent given $a$ we have that $$p(b,c)=p(b|a)\,p(c|a)\,p(a) + p(b|\neg a)\,p(c|\neg a)\,p(\neg a)=0.24$$
Finally, we proceed similarly for the calculation of $p(c,d)$. Notice that $$p(c,d)=p(c,d,b) + p(c,d,\neg b)$$
We know from before that $p(b,c)=0.24$ and thus $$p(c,d,b)=p(d|b,c)\,p(b,c)=0.192$$
We can calculate $p(\neg b, c)$ the same way we did for $p(b,c)$ (giving also 0.24) and thus $$p(c,d, \neg b)=p(d|\neg b,c)\,p(\neg b,c)=0.144$$
Therefore, $p(c,d)=0.336$.

*

*Note: double-check results in calculations.


text:
Q: How to use X509 certificate with the Nest Elastic Client I am currently upgrading from Elastic Search 1.7 to 5.2. I know there is no upgrade path, which is fine. One problem we had originally is with Nest and ElastiSearch.Net there was no way to attach an X509 certificate as it only had the ability to use Basic Authentication. To get around that we made copies of the existing github repos and modified the code directly to allow it. This ultimately is what kept us from upgrading for so long since we couldn't just use the nuget packages, because we now had custom code.
Now that we are upgrading I'm trying to find out if this was ever remedied. Or, at the very least are there any hooks that we can use to get the ElasticClient(in Nest) or the ElasticLowLevelClient (in ElasticSearch.Net) to take in a certificate and pass it on when making the call.
Another option, is to use a PUT request to create the Index on initial creation, which is where we are needing the certificate.  The issue we have there is we require the use of the AutoMap method since we have some custom attributes added on our models, and need those to go in on Index creation. I'm not sure if there is a way to generate that result of AutoMap for a given model to JSON, and just use a webclient to attach the certificate.
Let me know if you need anymore details.

A: It's possible to customise the connections that both NEST and Elasticsearch.Net use all the way back to 1.x. This is done by providing your own implementation of IConnection to the ConnectionSettings instance that is passed to the ElasticClient constructor.
First create your custom IConnection; it's easiest to derive from HttpConnection
public class HttpConnectionWithClientCertificate : HttpConnection
{
    protected override HttpWebRequest CreateHttpWebRequest(RequestData requestData)
    {
        var request = base.CreateHttpWebRequest(requestData);
        // add the certificate to the request
        request.ClientCertificates.Add(new X509Certificate("path_to_cert"));
        return request;
    }
}

then pass this to ConnectionSettings
var node = new Uri("http://localhost:9200");
var connectionPool = new SingleNodeConnectionPool(node);
var connection = new HttpConnectionWithClientCertificate();
var settings = new ConnectionSettings(connectionPool, connection);
var client = new ElasticClient(config);


text:
Q: How to display video and audio in HTML preview in Visual Studio Code When I use the HTML5 video and audio tags in my code, video and audio appears when I load the file in a browser. They also appear when I use a HTML preview package in Atom, however, they appear greyed-out and are not interactive when I use Visual Studio Code and a HTML preview extension there.
At the bottom of the preview in Visual Studio Code, is a message:
Some content has been disabled in this document

When I hover over the message I see a tooltip
Potentially unsafe or insecure content has been disabled in the HTML Preview. Change the HTML preview security setting to allow insecure content or enable scripts.

I found the "HTML: Change Preview Security Settings" option in the Command Palette, however, changing the security settings caused no change. The video and audio are still greyed-out.
I'm new to Visual Studio Code and the preview not being an authentic version of what will be in the browser is annoying.
in Visual Studio Code
in Atom
Has anyone else come across this issue and does anyone know why this is?

A: I know it is a bit too late but had the same issue. The security settings menu appears in a very right hand corner of the main window and has 3 dots as an icon. Click on the menu to open html preview security options. See attached pix.

A: Disable the change preview settings.

A: You can put your file in your Visual Studio Code framework. Then it will work...

A: i faced the same problem today and after some research i got solution
Reasons why it's grayed may be due to following reason:
you wouldn't have the saved audio,image or video in the folder where your html code is saved.
Solution:
make sure to save your file(code) and data(audio,image or video) in same folder.
use live server for output.


text:
Q: AngularJs ng-repeat with track by not updated I have ng-repeat with track by clause (to optimize performance). I also have a custom directive which I use to process every tr:
<tr ng-repeat="item in Products track by item.Id"
    on-row-rendered="rowRendered">

app.directive('onRowRendered', function($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            debugger;
            $timeout(function() {
              scope.$emit(attr.onRepeatDone, element);
            });
          }
        }
    };
});

It works nice during the loading time (when Products are set first). But when model is changed (e. g. one of the items is updated) onRowRendered's link method is not called (I put debugger call there to check it out) while bindings are updated and html is correctly rerendered.
I expected AngularJs to call it at least for those items that were updated. Was I wrong in my expectations? What should I do instead?

A: Today I've been digging into the code of the ngRepeat controller and I'm sorry to say, but this code won't work for the items that are being updated because the ngRepeat controller won't destroy the scope of the updated items, it will update the scope properties though ($index, $first, $last, etc), but it won't destroy the scope unless the item needs to be removed.
Your code would only work if all the scopes of all the items of the repeat were being destroyed and recreated every time that you make a change to the collection, but that is not how the ngRepeat controller operates.
But you may want to try this instead:
    .directive('onRowRendered', function($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            scope.$watch('item', function(){
                $timeout(function() {scope.$emit(attr.onRowRendered, element);});
            }, true);
          }
        }
    });

This should $emit every time that an item is added or changed.
Example


text:
Q: Ruby on Rails Simple Forms Error I'm a Ruby and Ruby on Rails beginner, started 2 days ago.
I'm trying to build a basic app for the first time and I get this error when I try to use simple_forms gem.
Before I show you the code I want to specify that if I delete the simple_forms code, it works, it redirects me to /orders/new page and it display the HTML page.
This is my error:
NoMethodError in Orders#new
Showing /home/ubuntu/workspace/app/views/orders/_form.html.erb where line #2 raised:
undefined method `amazonurl' for #
My code:
routes.rb
Rails.application.routes.draw do

resources :orders

root 'orders#index'

end

orders_controller
class OrdersController < ApplicationController
    def index
    end

    def new
        @order = Order.new
    end

    def create
        @order = Order.new(order_params)
    end

    private
    def order_params
        params.require(:order).permit(:amazonurl, :dname, :daddress, :dphone)
    end
end

Migration
class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|

      t.string :amazonurl
      t.text :dname
      t.text :daddress
      t.text :dphone

      t.timestamps null: false
    end
  end
end

Form ( _form.html.erb)
<%= simple_form_for @order  do |f| %>
  <%= f.input :amazonurl %>
  <%= f.input :dname %>
  <%= f.input :daddress %>
  <%= f.input :dphone %>
  <%= f.button :submit %>
<% end %>

And my new.html.erb file

New Order

  <%= render 'form' %>

Thank you very much, I hope we figure it out!

A: First try sudo gem install simple_form, then rails g simple_form:install. Hope it helps


text: Q: ydn.db valuesByIndex method support on windows universal In my cordova application I was using ydn.db. Method values was working fine. Now replaced it with valuesByIndex, which now fails. Does anybody know if ydn.db valuesByIndex method id fully supported on windows phone 10?


text:
Q: MySQL changing system date doesn't have the expected results I'm building a date specific PHP script.
This script will perform a specific task when its Sunday. I've written my PHP code and I'm trying to test it. Since it's not Sunday today, I set my system date to last Sunday. The thing is that my MySQL query doesn't return the expected results
SELECT date FROM schedules WHERE name='someName' AND date >= (CURDATE() - INTERVAL 3 DAY )

The query above will return the records of the current date plus and minus 3 days.
Here is an example of the output I get:
2015-11-26
2015-11-29
2015-11-30
2015-12-04
2015-12-02

The result that I need is:
 2015-11-26
 2015-11-29

Another query:
SELECT date FROM schedules WHERE name='someName' AND date >= (CURDATE() -  3 )

The query above will return all the dates that are 3 days older than the current date not including the last 3 days of the current date.
I only want it to return the last 3 days of the current date.

A: I'm trying to understand the output you want. So you want to get dates that are no more than 3 days prior to the current date and nothing in the future.
So on '2015-12-04' the result would be:
2015-12-04
2015-12-03
2015-12-02
2015-12-01

So maybe the BETWEEN Clause will do the trick
SELECT date FROM schedules
WHERE name='someName'
  AND (date BETWEEN (CURDATE() - INTERVAL 3 DAY ) AND CURDATE() );


text:
Q: Angular : how to display a login page by default I am working on a springboot/angular(version 11.2.7) application. I want to display the login page on startup
Here is the index.html page
<!doctype html>

  <meta charset="utf-8">
  <title>Frontend</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

Here is the LoginComponent
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import {LoginService} from "./login.service";

@Component({
  selector: 'app-root',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {

  public formGroup: FormGroup;
  public error: boolean = false;

  private credentials = {username: '', password: ''};

  constructor(private formBuilder: FormBuilder, private loginService: LoginService, private http: HttpClient, private router: Router) {
  }

  ngOnInit() {
        this.formGroup = this.formBuilder.group({
          username: ['', Validators.compose([Validators.email, Validators.required])],
          password: ['', Validators.compose([Validators.required])]
        });
  }

  login() {
  this.credentials.username = this.formGroup.get('username').value;
  this.credentials.password = this.formGroup.get('password').value;
    this.loginService.authenticate(this.credentials, () => {
        this.router.navigateByUrl('/homepage');
    });
    return false;
  }

}

Here is the app.module.ts file
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LoginComponent } from './login/login.component'
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpsInterceptor } from './http.interceptor';
import {ReactiveFormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    ReactiveFormsModule,
AppRoutingModule
  ],
  providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpsInterceptor, multi: true } ],
  bootstrap: [LoginComponent]
})
export class AppModule { }

Here is the AppRoutingModule
import { Routes, RouterModule } from '@angular/router';
import {LoginComponent} from "./login/login.component";
import {NgModule} from "@angular/core";

const routes: Routes = [
  {
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  },
  {
    path: 'login',
    component: LoginComponent
  }
  ];

@NgModule({
  imports: [RouterModule.forRoot(routes,
      { enableTracing: false })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Here is the Spring controller
package com.example.commission.controllers;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Map;

@RestController
// we allow localhost:4200 for testing purposes
@CrossOrigin(origins = "http://localhost:4200")
public class HelloController {

    @RequestMapping(value = "/message", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, String> index() {
        return Collections.singletonMap("message", "Greetings from Spring Boot!");
    }

}

but when I browse http://localhost:8080/, I have the error message in the console
ERROR Error: The selector "ng-component" did not match any elements
    Angular 24
        selectRootElement
        locateHostElement
        create
        bootstrap
        _moduleDoBootstrap
        _moduleDoBootstrap
        bootstrapModuleFactory
        invoke
        onInvoke
        invoke
        run
        scheduleResolveOrReject
        invokeTask
        onInvokeTask
        invokeTask
        runTask
        drainMicroTaskQueue
        promise callback*scheduleMicroTask
        scheduleTask
        scheduleTask
        scheduleMicroTask
        scheduleResolveOrReject
        then
        bootstrapModule
    zUnb main.ts:11
    Webpack 6
        __webpack_require__
        0
        __webpack_require__
        checkDeferredModules
        webpackJsonpCallback
        <anonymous>

UPDATE
I change the following
  bootstrap: [AppComponent]
})
export class AppModule { }

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [HttpClient]
})
export class AppComponent implements OnInit{

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {

And app.component.html

        <router-outlet></router-outlet>

UPDATE 2
I changed the routing
const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },

  // otherwise redirect to home
  { path: '**', redirectTo: '' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes,
      { enableTracing: false })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

For incremental purpose AuthGuard return false and redirect towards login page
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

//import { AuthenticationService } from '@app/_services';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(
    private router: Router
    //,private authenticationService: AuthenticationService
  ) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
/*    const currentUser = this.authenticationService.currentUserValue;
    if (currentUser) {
      // logged in so return true
      return true;
    }*/

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false;
  }
}


text:
Q: Gradle: Override exclude config made in a plugin I'm developing a Liferay 7.2 theme (WAR-style) using Liferays "Gradle Theme Builder". I configured it to generate CSS source maps, too. This works fine, except that the original SCSS files are not deployed with the theme WAR file -- the source maps, on the other hand, are deployed. In the end, the DevTools in the browser ask the server for about 200 non-existent SCSS source files, which I cannot assign by hand to a local file (it looks like Firefox and Chrome removed that feature a while ago; and no matter how much I play with local files and workspaces in the DevTools, I cannot get the browser to recognize the local files as "these are the sources I'm looking for!").
I tried to configure the gradle war task to include those scss files in the resulting WAR, but:
The Theme Builder is a gradle plugin which configures the war task programmatically and sets an exclude to **/*.scss (see the sources here). Changing that plugin is out of question, so how can I override that exclude in my build.gradle?
Alternatively, I tried to run a second war task after the first, with the intention of adding those scss files to the existing WAR file (having the added benefit of a different task to run if I want a "theme development build"):
task fragmentWAR(type: War) {
    group 'build'
    description 'Prepares a war with scss files'
    dependsOn war

    from('build/buildTheme') {
        include '**/*.scss'
        exclude '**/.sass-cache'
    }
}

task fragmentDeploy {
    group 'build'
    description 'Goes to war with scss files'
    dependsOn += fragmentWAR
    dependsOn += deploy
}

deploy.mustRunAfter(fragmentWAR)

But that messes up the WAR file: some files are now created twice in the WAR, others are missing completely.
In the end, I need a way to deploy the scss files along with the transpiled css and the css source maps into my testing server. Has anybody got any idea how to circumvent that exclude configured by the theme builder plugin -- or any other idea that might help me here?

A: Have you tried using the generator-liferay-theme NPM module instead of the Gradle Theme Builder plugin? Use v9.x of generator-liferay-theme for Liferay 7.2.
See
https://github.com/liferay/liferay-js-themes-toolkit and
https://github.com/liferay/liferay-js-themes-toolkit/tree/master/packages/generator-liferay-theme for more details.
When I generate my theme using this module, I see that both .scss and .css.map are files included in my theme .war file.
Hope it helps.


text:
Q: Whyt Jquery ajax post does'nt work with HtmlUnit i am using htmlunit with spring test in order to test all ihm interface from my web application. It works fine with html form (post and get) and with ajax get but i have a problem with ajax post request.
The controller don't received the request. If i replace post by get the junit test case works fine.
this the html view

    <title>Spring Html Unit</title>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Hello from Thymeleaf

    <button type="button" onClick="postTest()">Test post</button>

        result :

and the controller
@Controller
public class WelcomeController {
@GetMapping("/")
public String init(Model model) {
    model.addAttribute("myParam", "Guillaume");
    return "welcome";
}

@PostMapping("/test/post")
public @ResponseBody String post(@RequestParam String subject, @RequestParam String message, Model model) {
    return subject + " " + message;
}

}
you can also find the complete code on my github https://github.com/guisimon28/spring-test-htmlunit
Can you help me to find if there is some missing configuration or if its a htmlunig bug or pull request ?
Thanks for All
Guillaume


text:
Q: Video file is not displaying after converted to .mp4 I'm trying to create PHP video upload script which convert MOV and many other video files extensions to .mp4 extension. I successfully upload the file to the folder and create a record to the database. But when I try to display that video file in HTML5 video tag is not working.
Here is my PHP code:
  <?php include "includes/dbh.inc.php"; ?>

 <?php
if (isset($_SESSION['user_name'])){

    if (isset($_POST['submit'])) {
        $author = $_SESSION['user_name'];
        $post_photo = time() . '-' . $_FILES["post_photo"]["name"];
        if (file_exists($_FILES['post_photo']['tmp_name']) && is_uploaded_file($_FILES['post_photo']['tmp_name'])) {

            $targetvid     = md5(time());
            $target_dirvid = "post_video/";

            $target_filevid = $targetvid . basename($post_photo);

            $uploadOk = 0;

            $videotype = pathinfo($target_filevid, PATHINFO_EXTENSION);

    //these are the valid video formats that can be uploaded and
                  //they will all be converted to .mp4

            $video_formats = [
                "mpeg",
                "mp4",
                "mov",
                "wav",
                "avi",
                "dat",
                "flv",
                "MOV",
                "3gp"
            ];

            foreach ($video_formats as $valid_video_format) {

      //You can use in_array and it is better

                if (preg_match("/$videotype/", $valid_video_format)) {
                    $target_filevid = $targetvid . basename($_FILES["post_photo"] . ".mp4");
                    $uploadOk       = 1;
                    break;

                }

            }

            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {

                echo $message;

                // if everything is ok, try to upload file

            }

                if (move_uploaded_file($_FILES["post_photo"]["tmp_name"], $target_dirvid . $target_filevid)) {
                    $sql = "INSERT INTO video_posts (author, video_post) VALUES ('$author', '$target_filevid')" ;
                    $result = mysqli_query($conn, $sql);

                   if ($result) {
                    echo "Success";
                   } else {
                    echo "Failed" . mysqli_error($conn);
                   }
                }
            }

    }
}
?>

And this is my HTML video tag
P.S. I'm using foreach loop to display video for every user.

<video id="myVideo" controls  playsinline>
  <source src="../post_video/<?php echo $user_post['video_post']; ?>" type="video/mp4">
  <source src="../post_video/<?php echo $user_post['video_post']; ?>" type="video/ogg">
</video>

On database record the file name is absolutely the same as in the upload folder with MP4 extension but is still not showing into HTML page.

A: If you mean that your video when it been uploaded does not display in you website change the following:
$target_dirvid = "post_video/";

To:
$target_dirvid = "post_video\";

If you mean that you want to change the extension name to another and you want it to be displayed; you can not do this.


text:
Q: My Android emulator appears over sized and the screen is in the top left corner My android emulator on android studio is over sized and the screen is distorted and located in the top left corner with the rest of the phone appearing black.
Previously it worked fine with all apps run from VS Code and Android Studio. However recently it just got weird. I have uninstalled and reinstalled Android Studio as well as remove all files related to Android Studio with no fix, i have also resized the Emulator with no fix to the problem.

A: you can use another emulator because i used to be like that


text:
Q: Put all non zero values at the right of an array I have an fixed size array of n elements containing integers. I want to put all the non zero values at the right side of the array.
Examples:
[1, 0, 0, 4] => [0, 0, 1, 4]
[2, 0, 4, 3] => [0, 2, 4, 3]
[1, 0, 0] => [0, 0, 1]

What would be a simple algorithm to perform this?
This is what I currently have but it only shifts the element at index to right
def slide(arr):

    i = len(arr) - 2
    while i >= 0:

        if arr[i] != 0 and arr[i + 1] == 0:
            arr[i + 1] = arr[i]
            arr[i] = 0

        i -= 1

    print(arr)

A: I would count the zeros, remove them and include them at the beginning:
zeros = [0] * arr.count(0)
while 0 in arr:
    arr.remove(0)
arr = zeros + arr

A: To shift values right with their initial order:
(inplace, linear time complexity)
def slide(arr):
    zeros = 0
    for i in range(len(arr) - 1, -1, -1):
        if arr[i] == 0:
            zeros += 1
        else:
            arr[i+zeros] = arr[i]
    for i in range(zeros):
        arr[i] = 0
    print(arr)

slide([1,0,2,0,0,3])

>>[0, 0, 0, 1, 2, 3]

A: Create a new array, same size, initialized with 0's.

Scan the first array:
    if the current element is not zero:
        copy it into the second array starting from the end

Time complexity: O(n)
Space complexity: O(n)

straightforward and intuitive approach


text:
Q: Go Lang how do represent Json with types that can vary I have a need to unmarshal a json object that has values that can change. A typical object would have as an example the following properties defined:
{
    "entityName": "example Property",
    "properties": [
        {
            "name": "property1",
            "type": "string",
            "value": "Test Value"
        },
        {
            "name": "property2",
            "type": "float",
            "value": "12.5"
        },
        {
            "name": "property3",
            "type": "integer",
            "value": 1
        }
    ]
}

Each property would declare itself as the type it would need to be unmarshalled to. I have solved this problem in Java using generics but I am unsure, how I would declare my object in Go?

A: In go you would you the JSON library to parse the JSON-encoded data into a struct. So for your example let's say you are getting your data from a webpage.
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "io/ioutil"
)

type Payload struct {
    EntityName string
    properties Properties
}

type Properties struct{
    name string
    type string
    value string

}

func main() {
    url := "some site where data is stored"
    res, err  := http.Get(url)
    if err != nil {
        panic (err)
    }
    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err)
    }

    var p Payload

    err = json.Unmarshal(body, &p)
    if err != nil{
       panic (err)
    }

    fmt.Println(p.EntityName\n, p.properties)
}

This is by no means an efficient or smart way of doing this, I just quickly hacked this together. But I hope it conveys the concept.


text:
Q: Перенос временной папки в другое место Можно ли перенести временную папку с диска С в другое место, прозрачно для всех программ?

A: Предварительно создать TempFolder на D и:
mklink /D c:\TempFolder d:\TempFolder


text:
Q: Use .NET 4.0 or .NET 3.5? Windows 7 and Vista have the .NET 2.0/3.5 language runtime installed, so whatever you code in 3.5 will run on Windows 7 and most of it on Vista, too. But Windows 8 only delivers the .NET 4.0 CLR. When executing an assembly build with .NET 3.5, Windows 8 would need to install the .NET 3.5 runtime.
This would be a contra for .NET 3.5, but a contra for .NET 4.0 would be the low market share on Windows 7 and below.
What .NET framework should be used if you want high compatibility?

A: Well, it really depends on how you intend to deploy your application.
I believe using the .net 4.0 can only be a good idea, because installing a newer version of the framework is really easy, especially using the built in deployement tools in VS.
So why go for an "older" framework, when you have the possibility of using a better version ? Will you be getting any benefits from using the 4.0 instead of the 3.5 ?
I believe yes, but maybe not, in which case you could go for the 3.5

A: I think the question goes into the direction, what framework will be supported "out of the box" by the OS. But as you already noted their is no common base between the different OSes. All you can do is built a setup project that checks for the requirements.
But i think you should go with .Net 4 cause it has the smallest footprint needed for a installation. For further informations you could check out smallestdotnet.

A: According to this MSDN article you won't need to install 3.5 on Windows 8 as it is backward-compatible:

The .NET Framework 4 is backward-compatible with applications that were built with the .NET Framework versions 1.1, 2.0, 3.0, and 3.5. In other words, applications and components built with previous versions of the .NET Framework will work on the .NET Framework 4.

Also, this question might be of intrest:
https://serverfault.com/questions/121563/are-net-versions-backwards-compatible.

A: .Net even supports side by side execution.
Have a look at this MSDN article for details.
So running code >=2.0 will be not a problem for future versions.
3.5 is a reasonable choice, if you do not need TPL.

A: I thought that 4 .NET includes all preceding versions of framework starting from 1.0. But seems like 3.5 should be explicitly "enabled" in Windows 8. Anyway 4.0 is the best option.


text:
Q: Cannot Mount a Restored Content Db to new Web application In the same Application server, I have Created new Web application and I'm trying to Mount the Restored Content Db of another WebApplication.
But in the end of the process it returns me the CurrentSiteCount = 0.
It is running in the same server with all features installed.
The new WEbApp is working fine, because if I try to Mount another content_DB everything works well.
If I try to do the same process in another environment using this restored Content Db, it finds the Right amount o Sites and SC. Even if nothing works because of features and many other things.
PS C:\Users\mossadm>  Mount-SPContentDatabase -Name WSS_Content  -DatabaseServer [Servername]-WebApplication site.com:8888/

Id               : 0c9934ae-fea5-41c4-9dd8-b8f7e8d2b1f7
Name             : WSS_Content
WebApplication   : SPWebApplication Name=[Name]

   Server           : [servername]

CurrentSiteCount : 0

A: As per my experience, I don't think you can make of a copy of content DB with in same farm even with the different web app. because it contains the site collections IDs which will remain same even making the copy. Config db have those ids that why you cant see any site collection in new restored db.
You can restore it to different farm.
In order to prove it detach the old db abd attach the new one and you will see the all site collections.

A: Since the original site is in the same farm I would use the Backup-SPSite / Restore-SPSite commands.  When the site is restored to a new location, it should be given a new ID.
You can also see this happen sometimes when bringing in a content databases and the root site is not available (because the current DB contains the root site collection).  When this happens you can use the unattached method for backing up the site collections from the database and then restore them. for example below would access unattached DB (technically get's attached to Central Admin when you run this) and list the sites in the DB.
Get-SPContentDatabase -ConnectAsUnattachedDatabase -DatabaseName <name of imported DB> | Get-SPSite -limit all;


text:
Q: Filter JSON Obj I'm getting a JSON object from a XMLHttpRequest and am looking for a solution to filter bt genre. I also need a way to return all results (unfiltered) if no filterable parameter is passed.
app.js (pseudo function)
function filterObject(json, filterBy) {
  // filter through json
  // return item that matches filterBy
}

data.json
[{
  "date": {
    "dayOfWeek": "Thursday",
    "month": "Oct"
  },
  "location": "Bristol",
  "genre": "rock"
}, {
  "date": {
    "dayOfWeek": "Cardiff",
    "dayOfMonth": 13,
    "month": "Oct"
  },
  "location": "Manchester",
  "genre": "jazz"
}]

A: You can use array#filter to filter your json on genre value.

var json = [{"date": {"dayOfWeek": "Thursday","month": "Oct"},"location": "Bristol","genre": "rock"}, {"date": {"dayOfWeek": "Cardiff","dayOfMonth": 13,"month": "Oct"},"location": "Manchester", "genre": "jazz"}];

function filterObject(json, filterBy) {
  return filterBy ? json.filter(o => o.genre === filterBy) : json;
}

console.log(filterObject(json,'jazz'));

console.log(filterObject(json));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use Array#filter
Something like this:

(function() {
  var json = [{
    "date": {
      "dayOfWeek": "Thursday",
      "month": "Oct"
    },
    "location": "Bristol",
    "genre": "rock"
  }, {
    "date": {
      "dayOfWeek": "Cardiff",
      "dayOfMonth": 13,
      "month": "Oct"
    },
    "location": "Manchester",
    "genre": "jazz"
  }];

  function filterObject(json, filterBy) {
    if (filterBy !== undefined) {
      return json.filter(function(x) {
        return x.genre === filterBy;
      });
    } else {
      return json;
    }
  }
  var resultWithParameter = filterObject(json, "jazz");
  console.log(resultWithParameter);

  var resultWithoutParameter = filterObject(json);
  console.log(resultWithoutParameter);
})();

A: You can use filterBy as object with key and value properties to find any property you like (not only genre key).
   function filterObject(data, filterBy) {
    if(typeof filterBy === 'undefined') return data;
     return data.filter(function(item) {
      return item[filterBy.key] === filterBy.value;
     })
   }

Test:
  filterObject(arr, {key: 'genre', value: 'rock'}); // return rock band
  filterObject(arr, {key: 'genre', value: 'jazz'}); // jazz band
  filterObject(arr, {key: 'location', value: 'Bristol'}); // return band with location key
  filterObject(arr); // return initial array


text:
Q: Что означает запись !!arr.indexOf('green') var arr=['red', 'blue', 'green'];

alert(!!arr.indexOf('green'));

A: Конкретно с indexOf() это сомнительная идея. Поскольку !!arr.indexOf(item) будет проверять что указанный элемент не является первым элементом в массиве или вообще там отсутствует. Лично я не могу придумать зачем это может понадобиться

A: !! - Способ сконвертировать int в bool

A: Я так понимаю, что это проверка на то, является ли 'green' нулевым...
В противном случает этот код не имеет смысла, т.к indexOf возвращает -1 в случае отсутствия значения, а !!-1 === true