text:
Q: Setar localStorage em diferentes domains Tenho três aplicações:
1. Login (que roda na porta 8080) com jQuery bem simples
2. API (que roda na porta 4000) com Nodejs
3. Web (que roda na porta 4200) com Angular
Quando estou no login e clico em "Entrar", vai chamar a API, validar se o usuário existe, se sucesso vai retornar um token do JWT. Quando retorna esse token, preciso setar ele no localStorage, pra depois redirecionar para a aplicação web.
O problema disso, é que são portas diferentes, se eu setar no localStorage da aplicação do login e depois redirecionar para a aplicação web, o token não vai mais existir no localStorage.
Como posso resolver este problema?

A: A API localStorage() é executada pelo navegador sobre a "Politica de Mesma Origem" (Same-Origem) por isto mesmo que a aplicação rode em um mesmo domínio (example.com) portas e subdomínios são tratados como origens diferentes.
Para contornar isto você pode trabalhar em alguma solução que faça uso de <iframe> e postMessage() para poder sincronizar o dados de localStorage().
Existem diversas bibliotecas que faze exatamente isto como por exemplo a Cross Domain Local Storage contudo, se seu único intuito é conferir o "token" simplesmente salve este "token" em um cookie que ele estará disponível para todo domínio, subdomínios e portas.
Vale lembrar que "tokens" JWT possuem marcação de tempo para validação bem como você poderia criar alguma base para controlar "tokens" expedidos e já utilizados.
Você pode remover o cookie assim que utilizar o "token", se for usar esta abordagem não esqueça de usar (caso em produção) um cookie sobre as bandeiras HTTPONLY (apenas para o servidor), SECURE (apenas sobre TLS) e até mesmo SAMESITE.


text:
Q: Add percentage numbers from a cell in PPTX I'm a novice in Python, and I'm struggling with pptx rn.
I have an xlsx file and I want to import a single percentage number from a cell in my presentation.
Here is the traceback:
line 40, in to_unicode
    raise TypeError("expected unicode string, got %s value %s" % (type(text), text))
TypeError: expected unicode string, got <class 'float'> value 0.29

A: Try:
subtitle.text = str(active_sheet['C8'].value)

as a start. This should avoid the exception, but might not give you the exact representation you want.
I expect it will give you "0.29", but let's come back to that. The reason you are getting the exception is because you are assigning a numeric (float) value to a property that expects a str value. Converting it to string using the built-in str() function takes care of that.
To get a percentage representation, try:
subtitle.text = "{:.0%}".format(active_sheet['C8'].value)

There are other ways of what is called interpolating strings from numbers in Python that you can find on search, but this is a good one in this case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: addOperation to add two identical operation to a queue, but only one operation is running I have a task which need to add operation to a queue and run it in sequence.
but when use addOperation to add two identical operation to a queue, but only one operation is running.
the queue is init as follows:
_lineItemsToPrintQueue = [[NSOperationQueue alloc] init];
_lineItemsToPrintQueue.name = @"com.bindo.lineItemsToPrint";
_lineItemsToPrintQueue.maxConcurrentOperationCount = 1;
_lineItemsToPrintQueue.qualityOfService = NSQualityOfServiceUtility;


text:
Q: Cassandra Error - Clustering column cannot be restricted (preceding column is restricted by a non-EQ relation) We are using Cassandra as the data historian for our fleet management solution. We have a table in Cassandra , which stores the details of journey made by the vehicle. The table structure is as given below
CREATE TABLE  journeydetails(
bucketid text,
vehicleid text,
starttime timestamp,
stoptime timestamp,
travelduration bigint,
PRIMARY KEY (bucketid,vehicleid,starttime,travelduration)
);

Where:

*

*bucketid :- partition key which is a combination of month and year

*vehicleid : -unique id of the vehicle

*starttime :- start time of the journey

*endtime :- endtime of  the journey

*travelduration:- duration of travel in milliseconds

We would like to run the following query - get all the travels of a vehicle - 1234567 between 2015-12-1 and 2015-12-3 whose travel duration is greater than 30 minutes
When I run this query:
select * from  journeydetails where bucketid in('2015-12') and vehicleid in('1234567')
  and starttime > '2015-12-1 00:00:00' and starttime < '2015-12-3 23:59:59'
  and travelduration > 1800000;

I get this result:
InvalidRequest: code=2200 [Invalid query] message="Clustering column "travelduration"
cannot be restricted (preceding column "starttime" is restricted by a non-EQ relation)

Does anyone have a recommendation on how to fix this issue?

A: select * from journeydetails where bucketid in('2015-12') and vehicleid in('1234567')
  and starttime > '2015-12-1 00:00:00' and starttime < '2015-12-3 23:59:59'
  and travelduration > 1800000;

That's not going to work.  The reason goes back to how Cassandra stores data on-disk.  The idea with Cassandra is that it is very efficient at returning a single row with a precise key, or at returning a continuous range of rows from the disk.
Your rows are partitioned by bucketid, and then sorted on disk by vehicleid, starttime, and travelduration.  Because you are already executing a range query (non-EQ relation) on starttime, you cannot restrict the key that follows.  This is because the travelduration restriction may disqualify some of the rows in your range condition.  This would result in an inefficient, non-continuous read.  Cassandra is designed to protect you from writing queries (such as this), which may have unpredictable performance.
Here are two alternatives:
1- If you could restrict all of your key columns prior to travelduration (with an equals relation), then you could apply a your greater-than condition:
select * from journeydetails where bucketid='2015-12' and vehicleid='1234567'
  and starttime='2015-12-1 00:00:00' and travelduration > 1800000;

Of course, restricting on an exact starttime may not be terribly useful.
2- Another approach would be to omit travelduration altogether, and then your original query would work.
select * from journeydetails where bucketid='2015-12' and vehicleid='1234567'
  and starttime > '2015-12-1 00:00:00' and starttime < '2015-12-3 23:59:59';

Unfortunately, Cassandra does not offer a large degree of query flexibility.  Many people have found success using a solution like Spark (alongside Cassandra) to achieve this level of reporting.
And just a side note, but don't use IN unless you have to.  Querying with IN is similar to using a secondary index, in that Cassandra has to talk to several nodes to satisfy your query.  Calling it with a single item probably isn't too big of a deal.  But IN is one of those old RDBMS habits that you should really break before getting too deep into Cassandra.

A: I run into same problem. Instead of playing with the clustered and primary keys, you could simply add an index to the needed columns. With this, you get rid of these pitfalls and you can use whatever column you want in your query.

A: turns out you can just use 'allow filtering' at the end of the query


text:
Q: SQL running sum for an MVC application I need a faster method to calculate and display a running sum.
It's an MVC telerik grid that queries a view that generates a running sum using a sub-query.  The query takes 73 seconds to complete, which is unacceptable.  (Every time the user hits "Refresh Forecast Sheet", it takes 73 seconds to re-populate the grid.)
The query looks like this:
SELECT outside.EffectiveDate
[omitted for clarity]
       ,(
              SELECT SUM(b.Amount)
              FROM vCI_UNIONALL inside
              WHERE inside.EffectiveDate <= outside.EffectiveDate
              ) AS RunningBalance
[omitted for clarity]
FROM vCI_UNIONALL outside

"EffectiveDate" on certain items can change all the time... New items can get added, etc.  I certainly need something that can calculate the running sum on the fly (when the Refresh button is hit).  Stored proc or another View...?  Please advise.
Solution: (one of many, this one is orders of magnitude faster than a sub-query)
Create a new table with all the columns in the view except for the RunningTotal col.  Create a stored procedure that first truncates the table, then INSERT INTO the table using SELECT all columns, without the running sum column.
Use update local variable method:
DECLARE @Amount DECIMAL(18,4)
SET @Amount = 0
UPDATE TABLE_YOU_JUST_CREATED SET RunningTotal = @Amount, @Amount = @Amount + ISNULL(Amount,0)

Create a task agent that will run the stored procedure once a day.  Use the TABLE_YOU_JUST_CREATED for all your reports.

A: Take a look at this post
Calculate a Running Total in SQL Server
If you have SQL Server Denali, you can use new windowed function.
In SQL Server 2008 R2 I suggest you to use recursive common table expression.
Small problem in CTE is that for fast query you have to have identity column without gaps (1, 2, 3,...) and if you don't have such a column you have to create a temporary or variable table  with such a column and to move you your data there.
CTE approach will be something like this
declare @Temp_Numbers (RowNum int, Amount <your type>, EffectiveDate datetime)

insert into @Temp_Numbers (RowNum, Amount, EffectiveDate)
select row_number() over (order by EffectiveDate), Amount, EffectiveDate
from vCI_UNIONALL

-- you can also use identity
-- declare @Temp_Numbers (RowNum int identity(1, 1), Amount <your type>, EffectiveDate datetime)
-- insert into @Temp_Numbers (Amount, EffectiveDate)
-- select Amount, EffectiveDate
-- from vCI_UNIONALL
-- order by EffectiveDate

;with
CTE_RunningTotal
as
(
    select T.RowNum, T.EffectiveDate, T.Amount as Total_Amount
    from @Temp_Numbers as T
    where T.RowNum = 1
    union all
    select T.RowNum, T.EffectiveDate, T.Amount + C.Total_Amount as Total_Amount
    from CTE_RunningTotal as C
        inner join @Temp_Numbers as T on T.RowNum = C.RowNum + 1
)
select C.RowNum, C.EffectiveDate, C.Total_Amount
from CTE_RunningTotal as C
option (maxrecursion 0)

There're may be some questions with duplicates EffectiveDate values, it depends on how you want to work with them - do you want to them to be ordered arbitrarily or do you want them to have equal Amount?


text:
Q: java merging two List> to HashMap I have two list called List<Map<String, Object>> cpuReport and List<Map<String, Object>> memoryReport, I want to put these two list into one HashMap where cpureport and memoryReport can have same or different keys in HashMap.
memoryReport : [{robot=GEMPSAPPPROD02, memory_min=3.17, memory_max=90.79, memory_avg=31.857100643332412, memory_50=34006, memory_60=5700, memory_65=2480, memory_100=2450}, {robot=MUMGEMIDADBPROD05, memory_min=6.07, memory_max=8.75, memory_avg=8.184755153233644, memory_50=44635, memory_60=0, memory_65=0, memory_100=0}]
cpuReport : [{robot=Hema, cpu_min=1.12, cpu_max=1.12, cpu_avg=1.12, cpu_50=0, cpu_60=0, cpu_65=0, cpu_100=0}, GEMPSAPPPROD02={robot=GEMPSAPPPROD02, cpu_min=0.03, cpu_max=35.88, cpu_avg=2.6957142857143097, cpu_50=44636, cpu_60=0, cpu_65=0, cpu_100=0}]
mergedMap: GEMPSAPPPROD02={robot=GEMPSAPPPROD02, memory_min=3.17, memory_max=90.79, memory_avg=31.857100643332412, memory_50=34006, memory_60=5700, memory_65=2480, memory_100=2450,cpu_min=0.03, cpu_max=35.88, cpu_avg=2.6957142857143097, cpu_50=44636, cpu_60=0, cpu_65=0, cpu_100=0},MUMGEMIDADBPROD05={robot=MUMGEMIDADBPROD05, memory_min=6.07, memory_max=8.75, memory_avg=8.184755153233644, memory_50=44635, memory_60=0, memory_65=0, memory_100=0},Hema={robot=Hema, cpu_min=1.12, cpu_max=1.12, cpu_avg=1.12, cpu_50=0, cpu_60=0, cpu_65=0, cpu_100=0}

public List<Map<String, Object>> getMergedReport(List<Map<String, Object>> cpuReport,
        List<Map<String, Object>> memoryReport) {
    Map<String, Object> MergedMap = new HashMap<String, Object>();
    List<Map<String, Object>> listOfBothMaps = new ArrayList<>();
    String robotFromcpu = null;
    try {
        for (Map<String, Object> cpuMap : cpuReport) {
            robotFromcpu = (String) cpuMap.get("robot");
            MergedMap.put(robotFromcpu, cpuMap);
            }
        for (Map<String, Object> memoryMap : memoryReport) {
            String robotFromMemory = (String) memoryMap.get("robot");
            Map<String, Object> map = (Map<String, Object>) MergedMap.get(robotFromMemory);
            if(map != null){
                map.putAll(memoryMap);
            }
            else{
                MergedMap.put(robotFromMemory, memoryMap);
            }
            LOGGER.info("The merged map is : " + map);
            listOfBothMaps.add(map);
        }
        } catch (Exception e) {
        LOGGER.info("The exception is : " + e.getMessage());
    }
    return listOfBothMaps;
}

Working code:
 Map<String, Object> mergedMap = new HashMap<String, Object>();
        List<Map<String, Object>> listOfMergedMaps = new ArrayList<>();
        String robotFromcpu = null;
            for (Map<String, Object> cpuMap : cpuReport) {
                robotFromcpu = (String) cpuMap.get("robot");
                mergedMap.put(robotFromcpu, cpuMap);
                }
            for (Map<String, Object> memoryMap : memoryReport) {
                String robotFromMemory = (String) memoryMap.get("robot");
                Map<String, Object> map = (Map<String, Object>) mergedMap.get(robotFromMemory);
                if(map != null){
                    map.putAll(memoryMap);
                    LOGGER.info("The merged map is : " + map);
                    }else{
                    mergedMap.put(robotFromMemory, memoryMap);
                }
            }
            for(Map.Entry<String, Object> map : mergedMap.entrySet()) {
                listOfMergedMaps.add((Map<String, Object>)map.getValue());
            }

A: below should work :
public List<Map<String, Object>> getMergedReport(List<Map<String, Object>> cpuReport,
        List<Map<String, Object>> memoryReport) {
    Map<String, Object> MergedMap = new HashMap<String, Object>();
    List<Map<String, Object>> listOfBothMaps = new ArrayList<>();
    cpuReport.addAll(memoryReport); // merge two lists
    Iterator itr_mergedList= cpuReport.iterator(); // get iterator for list
    while(itr_mergedList.hasNext())
    {
        HashMap m= (HashMap)itr_mergedList.next();
        Set s = m.entrySet(); // get no. of entries in above list
        Iterator itr_entrySet= s.iterator(); // get iterator for above entry set
        while(itr_entrySet.hasNext())
        {
            Map.Entry en=(Map.Entry) itr_entrySet.next();
            MergedMap.put((String)en.getKey(), en.getValue()); // put in merged map
        }
    }
    listOfBothMaps.add(MergedMap); // add map obj to list
    return listOfBothMaps;
}


text:
Q: Have we ever seen a captured ship incorporated permanently in the enemy's fleet? The threat of a starship being boarded and captured by enemy forces appears often in Star Trek franchise. On some occasions, such an operation is successful and the enemy gains the control over the starship. Such a starship is of great value for the enemy's intelligence services and would most likely be disassembled and studied by them. However, in situations when the ship's design is already known, or several ships of the same class are captured, there is no need to disassemble every one of them. Such ships can be manned by the enemy and be incorporated in the enemy's fleet.
There have been episodes in which a captured enemy ship is used for covert operations, however these ships do not last for long (like the Dominion's ship used by Starfleet).
Conditions I would like to exclude:

*

*A captured ship used by an individual and not in actual control of enemy's fleet (like Dukat's Bird-of-Prey).

*A captured ship used in one major operation and not used continuously by the enemy due to its destruction / becoming disabled / not being shown ever again (like Jem'Hadar fighter captured by Starfleet).

Have we ever seen a captured ship incorporated permanently in the enemy's fleet?

A: The Kazon fleet comprises entirely of vessels taken from their former enslavers, the Trabe

NEELIX: They're Trabe vessels, actually. Everything the Kazon have, they stole from the Trabe. Mabus will tell you all about it over
  a sumptuous dinner. The food hasn't been very good where we've been.

A: While Terok Nor isn't technically a ship, it is capable of moving around inside the Bajor system under its own steam. It's renamed Deep Space Nine and is used extensively by the Federation and Bajorans.

A: U.S.S. Defiant, NCC-1764, Constitution class cruiser.
Originally built by:

United Federation of Planets

Captured by:

The Tholian Assembly in TOS S3E09 "The Tholian Web"

Captured by, and incorporated into the fleet of:

 The Terran Empire (Mirror Universe) in ENT S4E18 & S4E19 "In a Mirror, Darkly"

A: There is another example of this that seems to have been missed.
Gul Dukat captures a Klingon Bird-of-Prey (DS9:Return to Grace and incorporates it into the joint cardassian/dominion fleet. (DS9: In Purgatory's Shadow & By Inferno's Light

A: Although it didn't last too long, the Nyrians captured Voyager in Displaced.  After all the Voyager crew were replaced, their leader stated "Your vessel will be used to defend Nyrian acquisitions."


text:
Q: C# TCP server wait for 2 clients to respond I'm currently working on a server/client project.
My question is, how the server can wait for two specific connections to respond?
Server:
private TcpListener tcpListener;
private Thread listenThread;
private List<Connection> ConList = new List<Connection>();
Queue queue = new Queue();

public struct Connection
{
     public Stream stream;
     public StreamWriter streamw;
     public StreamReader streamr;
     public TcpClient tcpC;
}

private void ListenForClients()
{
     this.tcpListener.Start();

     while (true)
     {
         try
         {
            Connection c = new Connection();
            c.tcpC = this.tcpListener.AcceptTcpClient();

            c.stream = c.tcpC.GetStream();
            c.streamr = new StreamReader(c.stream);
            c.streamw = new StreamWriter(c.stream);

            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));

            clientThread.Start(c);

            queue.Enqueue(c);
         }
         catch()
         {
             break;
         }
     }
 }
 private void HandleClientComm(Object client)
 {
     Connection con;
     con = (Connection)client;

     ConList.Add(con);

     byte[] message = new byte[4096];
     int bytesRead;

     while (true)
     {
         bytesRead = 0;

         try
         {

                bytesRead = con.stream.Read(message, 0, 4096);

                string s = Encoding.UTF8.GetString(message, 0, message.Length);
         }
         catch
         {
             //Socket error
             break;
         }

         if (bytesRead == 0)
         {
             //Client lost connection

             con.stream.Close();
             con.tcpC.Close();
             ConList.Remove(con);
             con = null;

             break;
         }
     }
 }

 private void QueueTimer_Tick(object sender, EventArgs e)
 {
      if (queue.count >= 2)
      {
            Connection c1;
            Connection c2;

            c1 = new Connection();
            c1 = (Connection)queue.Dequeue();

            c2 = new Connection();
            c2 = (Connection)queue.Dequeue();

            //Start thread which waits for a response from both connections
      }
 }

Each connection gets placed in queue and if queue.count >= 2 (timer checks every 20 seconds) a new thread should be startet which waits for a responds from both of the clients with a 10 seconds timeout. I tried to figure something out for 3 days but cannot find a good way to do it. Do you guys have any suggestions?

A: Here is a simple TPL based listener/responder without needing to dedicate a thread to the process.
    private TcpListener _listener;

    public void OnStart(CommandLineParser commandLine)
    {
        _listener = new TcpListener(IPAddress.Any, commandLine.Port);
        _listener.Start();
        Task.Run((Func<Task>) Listen);
    }

    private async Task Listen()
    {
        IMessageHandler handler = MessageHandler.Instance;

        while (true)
        {
            var client = await _listener.AcceptTcpClientAsync().ConfigureAwait(false);

            // Without the await here, the thread will run free
            var task = ProcessMessage(client);
        }
    }

    public void OnStop()
    {
        _listener.Stop();
    }

    public async Task ProcessMessage(TcpClient client)
    {
        try
        {
            using (var stream = client.GetStream())
            {
                var message = await SimpleMessage.DecodeAsync(stream);
                _handler.MessageReceived(message);
            }
        }
        catch (Exception e)
        {
            _handler.MessageError(e);
        }
        finally
        {
            (client as IDisposable).Dispose();
        }
    }
}

A: First off a point about your QueueTimer_Tick() function.  In it you have the following code:
c1 = new Connection();
c1 = (Connection)queue.Dequeue();

The first line of this isn't needed, it creates a new Connection object that is immediately overwritten by whatever you pull off the queue.  Alos what not use a typed queue in the same way as you use a typed List?
To answer your question what I think you are after is the Socket.Select() method.  It will take a list of sockets and check them for readability and it also allows a timeout to be specified.
To acheive what you want you'll need to call Select() in a loop where each time you check for readability of the clients who haven't yet become readable.  You'll also need to work out how much of your 10 second delay each call to select has used and adjust the timeout accordingly.
So in psuedo code:
create L1 a list of sockets that are to be readable
set the timeout T to 10 seconds
while L1 is not empty
   copy L1 to a tempory list L2
   Socket.Select(L2,T)
   If a timeout then exit loop
   Remove the socket(s) that are readable from L1
   recalculate T based on how long the Select took
End While

NB: The TcpClient.Client() method gets the Socket for a TcpClient.


text:
Q: How to display all sub categories from one category? I'm trying to show all the subcategories of the category id3.
Category ID3 ->
  Category Level 2 for Category ID3 ->
    Category Level 3 (for category Level 2)
<?php if (!Mage::registry('current_category')) return ?>
<?php
$categoryId = 3;
$category = Mage::getModel('catalog/category')->load($categoryId);
$_categories = $category->getChildrenCategories();
?>
<?php $_count = is_array($_categories)?count($_categories):$_categories->count(); ?>
<?php if($_count): ?>

<?php echo $this->__('Каталог') ?>

                <?php foreach ($_categories as $_category): ?>
                    <?php if($_category->getIsActive()): ?>

                        <a href="<?php echo $this->getCategoryUrl($_category) ?>"<?php if ($this->isCategoryActive($_category)): ?> class="current"<?php endif; ?>>
                            <?php echo $this->escapeHtml($_category->getName()) ?>

                    <?php endif; ?>
                <?php endforeach ?>

<?php endif; ?>

A: Try this
<?php
$cat = Mage::getModel('catalog/category')->load(4);
$subcats = $cat->getChildren();

foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    echo '
getURL().'" title="View the products for the "'.$_category->getName().'" category">'.$_category->getName().'';
    $sub_cat = Mage::getModel('catalog/category')->load($_category->getId());
    $sub_subcats = $sub_cat->getChildren();
    foreach(explode(',',$sub_subcats) as $sub_subCatid)
    {
          $_sub_category = Mage::getModel('catalog/category')->load($sub_subCatid);
          if($_sub_category->getIsActive()) {
              echo '
getURL().'" title="View the products for the "'.$_sub_category->getName().'" category">'.$_sub_category->getName().'
';
              $sub_sub_cat = Mage::getModel('catalog/category')->load($sub_subCatid);
              $sub_sub_subcats = $sub_sub_cat->getChildren();
              foreach(explode(',',$sub_sub_subcats) as $sub_sub_subCatid)
              {
                $_sub_sub_category = Mage::getModel('catalog/category')->load($sub_sub_subCatid);
                if($_sub_sub_category->getIsActive()) {
                    echo '
getURL().'" title="View the products for the "'.$_sub_sub_category->getName().'" category">'.$_sub_sub_category->getName().'
';
                }
              }
           }
     }
     echo '
';
  }
}

?>

I hope this will help you.

A: For some reason magento retrieve categories tree in different format depending on use category flat configuration, so take a look at code in:

Mage/Catalog/Block/Navigation.php::_renderCategoryMenuItemHtml()

    ... @line 246
    // get all children
    // If Flat Data enabled then use it but only on frontend
    $flatHelper = Mage::helper('catalog/category_flat');
    if ($flatHelper->isAvailable() && $flatHelper->isBuilt(true) && !Mage::app()->getStore()->isAdmin()) {
        $children = (array)$category->getChildrenNodes();
        $childrenCount = count($children);
    } else {
        $children = $category->getChildren();
        $childrenCount = $children->count();
    }
    $hasChildren = ($children && $childrenCount);
    ...

As you can see, you could find how to do some staff in the right way just looking into the core code.
If you can, try to grab the category model from some registry instead to load it again, on frontend you always have a category tree loaded ready to use.


text:
Q: Beautify Ruby source code with Geany How can I get Geany to beautify or prettify ruby code? What's the distinction between the two, anyhow?
My main interest is indents, that the indenting is consistent and correct.
I would like to integrate the gem into Geany if there's no plugin.
See also:
SO question 1194185
PlugIn for Ruby Refactoring

A: Geany allows this to be handled by external tools, for example astyle. Go to Edit->Format->Send Selection to->Set Custom Commands to set external tools up and play with astyle --style=gnu -FpPn, sort and others. As long as the script mentioned above is able to be ran from the command line, I guess it will also be possible to set it up as such an external tool.
For ruby in particular, you can use rbeautify.


text:
Q: Set selected option of type model in dropdownlist with knockout I'm trying to load the saved option from server side with knockout, please see below the general idea,
I have the following classes in javascript:
funcion Request() {
    this.Id = ko.observable('');
    this.Name = ko.observable('');
    this.Form = ko.obsevable('');
}

function Form() {
    this.Id = ko.observable('');
    this.Name = ko.observable('');
}

this is my viewModel
function RequestViewModel() {
    var self = this;
    self.Request = new Request();
    *self.Request.Form = new Form();*
}

I can save the Form without problem, but when I try to load the Form field saved into the database, the binding doesn't function.
If anybody have ever had the same problem, please let me know How can I fix it?

A: You form is an observable. When setting an observable, you should call it as a method, and set parse the value as a parameter. Something like this:
function RequestViewModel() {
    var self = this;
    self.Request = new Request();
    self.Request.Form(new Form());
}

If you have loaded the form from the database, it should look something like this:
self.Request.Form(myLoadedForm);

A: The answer by aaberg is correct, but if you're saying you need to load them all at once, I recommend you use the knockout mapping plugin to automate this: http://knockoutjs.com/documentation/plugins-mapping.html
Your call would look something like this:
ViewModel = ko.mapping.fromJS(requestFromServer);


text:
Q: Marginal PDF from joint PDF question
I am working on the 6.041 MIT Opencourseware course. Though, currently I am struggling with assignment 1b of the attached assignment (see pic).
As the joint pdf is linear (red circle), I do not see why the marginal PDF of Y can be quadratic (orange arrow). My feeling is that the provided solution mistakenly calculates the CDF.
What I did when trying to solve this; was to create a definite integral with bounds 1 and 2. In other words, replace the y (green arrow) with a 2. Though, as a result I would then have a new problem, as with this approach I would only have a constant (no variable) in my marginal PDF.
Do I have a mistake in my understanding? Thanks in advance!

A: First, draw the three inequalities $$ 1 \leq x \leq y \leq 2$$ in the xy-plane. Then find their intersection.

To find the marginal PDF $f_Y(y)$, you have to integrate $f_{X,Y}(x,y)$ with respect to $x$ over the triangle depicted in the figure. Look at the arrow. It passes through $x=1$ first and then it passes through $x=y$. So
$$ f_Y(y)=\int_{x=1}^{x=y} \frac{3}{2}x\, dx$$
for $1\leq y \leq 2$.


text:
Q: Select list of IDs from one table and delete all IDs from a second table in SQL Server I'm trying to figure out the best query to accomplish the following.
I have 2 tables that are related by an ID column.
Table1
ID
UserID

Table2
ID
SomeDataColumn

What I need to do is select a list of IDs from Table1 where my UserID='5' or some number. This should return multiple rows with respective IDs. Then I need to delete all rows from Table2 that contain any ID from my returned list of IDs from Table1.
The only way I could figure out how to do this was to select all of the rows from my first table, put them in a cursor, and then loop through each one running a Delete query for each ID. But it seems there must be a more efficient way to do this with a join or something.
Any ideas? Thanks all!

A: This might get you there:
delete from Table2 where ID in (select ID from Table1 where UserID = '5')

You're right to think there is a better way in SQL

A: 3 ways
DELETE   FROM SomeTable
WHERE id IN(SELECT id FROM AnotherTAble WHERE USerID = 5 and id is not null)

DELETE  s
 FROM SomeTable s
JOIN AnotherTAble  a on s.ID = a.ID
WHERE a.USerID = 5

DELETE  s
 FROM SomeTable s
WHERE EXISTS (SELECT 1 from AnotherTAble  a WHERE a.ID = S.ID
AND a.USerID = 5)

A:  DELETE Table2
 WHERE ID IN (
     SELECT ID FROM Table1
     WHERE UserID=5
 )

That does it?

A: Use a join,
DELETE FROM [Table2]
FROM [Table2] as t2
INNER JOIN [Table1] as t1 ON t2.[ID] = t1.[ID]
WHERE t1.[UserID] = 5;


text:
Q: Letting socket.io client version lag behind server version Situation
We're using socket.io for mobile-server communications. Since we can't force-upgrade users' devices, if we want to upgrade to version 1 (non-back-compatible), we have to handle both versions on the server for a while.
Question
What are the options?
My current favourite is to wrap both the old version and the new version in a multiplexer. It detects the version of the incoming request based on headers and query parameters and thereby knows which functions to invoke.
Another (shittier) option is to wrap the new version in a module that can translate the old version of the protocol into the new version (and back again) when necessary. This suffers from a serious drawback. It would be time-consuming and uncertain work to ensure I've properly determined and handled all the tiny differences. Some differences might take some serious massaging.
(In case you're curious or it's helpful to know, we're doing this in Go.)

A: It appears that you could run two separate versions of socket.io on the server.  Since the two versions don't have unique module filenames you would probably need to load one version from a different path.  And, then obviously when loading the modules and initializing them you'd assign them to differently named variables.  For example:
var io_old = require('old/socket.io');
var io = require('socket.io);

Once you have the two versions loaded on the server, I think there are two different approaches for how they could be run.
1)  Use a different port for each version.  The older version would use the default port 80 (no configuration change required for that) which is shared with the node.js web server.  The newer version would be run on a different port (say port 3000).  You would then initialize each version of socket.io to its own port.  Your newer version clients would then connect to the the port the newer version was running on.
For the old socket.io server running on port 80, you would use whatever initialization you already have which probably hooks into your existing http server.
For the new socket.io server running on some other port, you would initialize it separately like this:
var io_old = require('old/socket.io')(server);
var io = require('socket.io')(3000);

Then, in the new version client, you would specify port 3000 when connecting.
var socket = io("http://yourdomain.com:3000");

2)  Use a different HTTP request path for each version.  By default, each socket.io connection starts with an HTTP request that looks like this: http://yourdomain.com/socket.io?EIO=xx&transport=xxx?t=xxx.  But, the /socket.io portion of that request is configurable and two separate versions of socket.io could each be using a different path name.  On the server, the .listen() method that starts socket.io listening takes an optional options object which can be configured with a custom path as in path: "/socket.io-v2".  And similarly, the .connect() method in the client also accepts that options object.  It's kind of hard to find the documentation for this option because it's actually an engine.io option (which socket.io uses), but socket.io passes the options through to engine.io.
I have not tried either of these myself, but I've studied how socket.io connections are initiated from client and server and it looks like the underlying engine supports this capability and I can see no reason why it should not work.
Here's how you'd change the path on the server:
var io = require('socket.io')(server, {path: "/socket.io.v1"});

Then, in the client code for the new version, you'd connect like this:
var socket = io({path: "/socket.io.v1"});

This would then result in the initial connection request being made to an HTTP URL like this:
http://yourdomain.com/socket.io.v1?EIO=xx&transport=xxx?t=xxx
Which would be handled by a different request handler on your HTTP server, thus separating the two version.

FYI, it is also possible that the EIO=3 query parameter in the socket.io connection URL is actually an engine.io version number and that can also be used to discern client version and "do the right thing" based on that value.  I have not found any documentation on how that works and could not even find where that query parameter was looked at in the engine.io or socket.io source code so that would take more investigation as a another possibility.

A: I don't really have an immediate solution for this, but I have some kind of   advice. I guess you could use it to save a lot of time.

*

*first of all Im working in a startup which uses socketIo for almost
everything

*We knew that this problem would happen so our initial design was to
make everything pluggable which means that we can swap out socketio for
sockjs and it will still work.

*The way its done is by defining the common set of APIs which rarely change
in a system. We call it managers. The managers can just expose the API   which the rest of the devs need to use without messing up anything. It speeds up a lot.

*The manager implementation changes in the background but still the APIs   are the same, so the engineers working on the core can confidently make   changes.

*Seems like you have a tight dependency in your code. Or may be not. I'm not so sure. Try following this principle if you haven't.

A: We're going to go the route of keeping both the 0.9.x version and the current version as separate libraries on the server. Eventually, when the pool of clients has more-or-less all updated, we'll just pull the plug on the 0.9.x version.
The way we'll manage the two versions is by wrapping the socket.io services in a package that will determine which wrapped socket.io version to pass the request off to. This determination will depend on features of the request, such as custom headers (that can be added to the newer clients) as well as query parameters and other headers utilized exclusively by one version or the other.
Since we're using Go, there's so far no universally agreed upon way to manage dependencies, let alone a way that can respect version differences. Assuming the back-compat branch of the repo wasn't broken (which it is), we'd have two options. The first would be to fork the repo and make the back-compat version the master. We'd then import it as if it had nothing to do with the other one. The second option would be to use gopkg.in to pretend the separate branches were separate repos.
In either event, we could import the two branches/repos like so
import (
    socketioV0 "github.com/path/to/older/version"
    socketioV1 "github.com/path/to/current/version"
)

And then refer to them in the code using their import names socketioV0 and socketioV1.


text:
Q: How to order by slug in wordpress without $args Im the admin of a website built in wordpress, builded by someone else. I know only the basics, I made a few changes here and there but now I hit a wall. What Im trying to do is order some categories by slug. Here is the code that calls categories.

     <?php foreach (get_categories('child_of='.get_query_var('cat')) as $cat): ?>

Im sure its not the best way to do it, another category page in the same website uses $args and there, it was pretty easy to solve the same problem. However I dont understand how this works. Hope someone can help me, in case you are curios the page this will reflect on is http://tumbili.mx/p/products/bsj/
Thanks a lot.

A: you can use below code for ordering
foreach (get_categories('orderby=slug&order=ASC&child_of='.get_query_var('cat')) as $cat):


text:
Q: Why autoincrement doesn't follow a sequential order I have a database in a server and I am rewriting my old program with c# . When I checked the ID's columns which are defined autoincremental I saw the result as shown on the pictures
1st table:

2nd table:

Any idea? I hadn't deleted any row and my command sql is still the same between Id 20 and 33 . The only difference after 20 I corrected my transactional writing data and it works. It can affect the increment of id ?


text:
Q: How to submit MR job to YARN cluster with ResourceManager HA wrt Hortowork's HDP? I am trying to understand how to submit a MR job to Hadoop cluster, YARN based.
Case1:
For case in which there is only one ResourceManager (that is NO HA), we can submit the job like this (which i actually used and I believe is correct).
hadoop jar word-count.jar  com.example.driver.MainDriver -fs  hdfs://master.hadoop.cluster:54310 -jt master.hadoop.cluster:8032 /first/dir/IP_from_hdfs.txt  /result/dir

As can be seen, RM is running on port 8032 and NN on 54310 and I am specifying the hostname becasue there is only ONE master.
case2:
Now, for the case when there is HA for both NN and RM, how do I submit the job? I am not able to understand this, because now we have two RM and NN (active / standby), and I understand that there is zookeeper to keep track of failures. So, from client perspective trying to submit a job, do I need to know the exact NN and RM for submitting the job or is there some logical naming which we have to use for submitting the job?
Can anyone please help me understand this?

A: With or without HA, the command to submit the job remains the same.
hadoop jar <jar> <mainClass> <inputpath> <outputpath> [args]

Using -fs and -jt is optional and are not used unless you want to specify a Namenode and JobTracker that is different from the one in the configurations.
If the fs.defaultFS property in core-site.xml and the properties defining the nameservice (dfs.nameservices) and its namenodes are configured properly in hdfs-site.xml of the client, the Active Master will be chosen whenever a client operation is performed.
By default, this Java class is used by the DFS Client to determine which NameNode is currently Active.
<property>
  <name>dfs.client.failover.proxy.provider.<nameserviceID></name>
  <value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
</property>


text:
Q: $\sigma(x,y) = |x_{1} - y_{1}|^3 + |x_{2} - y_{2}| + ... + |x_{n} - y_{n}|$, how would I show that this is equivalent but not uniformly equivalent? If $x,y \in \mathbb{R}^n$, and $\sigma(x,y) = |x_{1} - y_{1}|^3 + |x_{2} - y_{2}| + ... + |x_{n} - y_{n}|$, how would I show that this is equivalent but not uniformly equivalent? I already figured out that this is a metric, but I am having a hard time showing as I stated above. Clearly the power of $3$ is not uniformly continuous which means its not uniformly equivalent. Just to clear any confusion I am looking for a set of $n$ tuples that is equivalent but uniformly equivalent which is why I chose the following metric above. The $\epsilon - \delta$ argument for equivalence is not as easy as I thought it would be. The help would be appreciated!

A: Hint
The metrics are uniformly equivalent if and only if there exist $c,C>0$ such that
$$c(|x_{1} - y_{1}| + |x_{2} - y_{2}| + \cdots + |x_{n} - y_{n}|)\le \sigma(x,y)\le C( |x_{1} - y_{1}| + |x_{2} - y_{2}| + \cdots + |x_{n} - y_{n}|).$$
In particular, for $x=(x_1,x_2,\cdots,x_n),y=(y_1,x_2,\cdots,x_n)$ it should be
$$c |x_{1} - y_{1}| \le |x_{1} - y_{1}|^3 \le C|x_{1} - y_{1}|,$$ or equivalently,
$$c \le |x_{1} - y_{1}|^2 \le C.$$
Is this possible?


text:
Q: Guest OS in VirtualBox How safe is the Virtualbox Guest OS assuming I have this setup. Host is Windows XP and Guest is another Windows XP?

*

*If the Host was infected by a virus or worm, will be the Guest OS be affected as well?

*If the Host was infected by a keylogger, will the keylogger be able to capture the keys typed in the Guest OS?

*If the Host was infected by spyware, will it affect the Guest OS?

*Basically, are the Host and Guest OS separate from each other? Can I think of it as 2 separate machines?

A: You can think of the guest and host as separate computers. However, a key logger can conceivably grab the input for the guest even if it were only on the host.

A: *

*That matters. Most of viruses aren't even aware of virtual machine, but then, crazy programmer could make such feature.

*Yes, it can, unless the keylogger is really badly coded.

*Look point 1.

*You can consider the guest OS that it cannot access files on your host in any way. It's different story with host OS. It can access guest OS fully (but many viruses aren't aware of its existence, because not many people use them, and programming viruses to detect VM would really take a lot of time).


text:
Q: Android WebView Destroy Opa pessoal estou com um certo problema quando eu executo um destroy em uma webview.
    wb.getSettings().setAllowFileAccess(true);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.getSettings().setRenderPriority(RenderPriority.HIGH);
    wb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

detalhe isso só ocorre quando eu seto o JavaScriptEnable.
            mWebContainer.removeView(wb);
            wb.clearHistory();
            wb.stopLoading();
            wb.clearView();
            wb.clearCache(true);
            wb.destroyDrawingCache();
            wb.setWebChromeClient(null);
            wb.setWebViewClient(null);
            wb.getSettings().setJavaScriptEnabled(false);
            wb.removeAllViews();
            wb.destroy();

Já tentei quase tudo para dar o destroy sem que o erro acontecesse

04-02 13:34:14.893: E/webview(24263): java.lang.Throwable: Error: WebView.destroy() called while still attached!
  04-02 13:34:14.893: E/webview(24263):   at android.webkit.WebViewClassic.destroy(WebViewClassic.java:2188)
  04-02 13:34:14.893: E/webview(24263):   at android.webkit.WebView.destroy(WebView.java:647)
  04-02 13:34:14.893: E/webview(24263):   at android.view.View.performClick(View.java:4421)
  04-02 13:34:14.893: E/webview(24263):   at android.view.View$PerformClick.run(View.java:17903)
  04-02 13:34:14.893: E/webview(24263):   at android.os.Handler.handleCallback(Handler.java:730)
  04-02 13:34:14.893: E/webview(24263):   at android.os.Handler.dispatchMessage(Handler.java:92)
  04-02 13:34:14.893: E/webview(24263):   at android.os.Looper.loop(Looper.java:213)
  04-02 13:34:14.893: E/webview(24263):   at android.app.ActivityThread.main(ActivityThread.java:5225)
  04-02 13:34:14.893: E/webview(24263):   at java.lang.reflect.Method.invokeNative(Native Method)
  04-02 13:34:14.893: E/webview(24263):   at java.lang.reflect.Method.invoke(Method.java:525)
  04-02 13:34:14.893: E/webview(24263):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
  04-02 13:34:14.893: E/webview(24263):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
  04-02 13:34:14.893: E/webview(24263):   at dalvik.system.NativeStart.main(Native Method)
  04-02 13:34:15.294: E/AndroidRuntime(24263): FATAL EXCEPTION: main
  04-02 13:34:15.294: E/AndroidRuntime(24263): java.lang.NullPointerException
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.ZoomManager.onSizeChanged(ZoomManager.java:955)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.WebViewClassic.onSizeChanged(WebViewClassic.java:5689)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.WebView.onSizeChanged(WebView.java:2157)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.sizeChange(View.java:14582)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.setFrame(View.java:14557)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.WebView.access$701(WebView.java:243)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.WebView$PrivateAccess.super_setFrame(WebView.java:1788)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.WebViewClassic.setFrame(WebViewClassic.java:5665)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.webkit.WebView.setFrame(WebView.java:2151)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.layout(View.java:14468)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewGroup.layout(ViewGroup.java:4562)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.layout(View.java:14471)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewGroup.layout(ViewGroup.java:4562)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.widget.FrameLayout.onLayout(FrameLayout.java:452)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.layout(View.java:14471)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewGroup.layout(ViewGroup.java:4562)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.layout(View.java:14471)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewGroup.layout(ViewGroup.java:4562)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.widget.FrameLayout.onLayout(FrameLayout.java:452)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.View.layout(View.java:14471)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewGroup.layout(ViewGroup.java:4562)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1984)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1738)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1008)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5508)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.Choreographer.doCallbacks(Choreographer.java:562)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.Choreographer.doFrame(Choreographer.java:532)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.os.Handler.handleCallback(Handler.java:730)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.os.Handler.dispatchMessage(Handler.java:92)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.os.Looper.loop(Looper.java:213)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at android.app.ActivityThread.main(ActivityThread.java:5225)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at java.lang.reflect.Method.invokeNative(Native Method)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at java.lang.reflect.Method.invoke(Method.java:525)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
  04-02 13:34:15.294: E/AndroidRuntime(24263):    at dalvik.system.NativeStart.main(Native Method)

A: Você precisa remover o WebView da sua view.
Exemplo:
webViewPlaceholder.removeView(myWebView);
myWebView.removeAllViews();
myWebView.destroy();

SO em inglês

Seguem um exemplo simples:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent" android:id="@+id/root" >

    <WebView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/webView" android:layout_gravity="center_horizontal"/>

    <Button android:layout_width="fill_parent" android:text="Remove" android:layout_height="wrap_content" android:onClick="onClickButton"/>
</LinearLayout>

public class MyActivity extends Activity {
    private WebView wb;
    private LinearLayout ll;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.wb = (WebView) findViewById(R.id.webView);
        this.wb.getSettings().setJavaScriptEnabled(true);
        this.wb.getSettings().setAllowFileAccess(true);
        this.wb.getSettings().setJavaScriptEnabled(true);
        this.wb.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        this.wb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        this.ll = (LinearLayout)findViewById(R.id.root);
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.wb.loadUrl("http://www.google.com.br");
    }

    public void onClickButton(View view) {
        //deatach the view
        ll.removeView(wb);
        wb.clearHistory();
        wb.stopLoading();
        wb.clearView();
        wb.clearCache(true);
        wb.destroyDrawingCache();
        wb.setWebChromeClient(null);
        wb.setWebViewClient(null);
        wb.getSettings().setJavaScriptEnabled(false);
        wb.removeAllViews();
        wb.destroy();
    }
}


text:
Q: Boot-repair tool tells me Legacy mode compatibility (CSM) is turned off, but the ASUS bios tells me it's on After a mistake on my part during an Ubuntu reinstall, I lost my legacy windows boot.
I tried to get it back with boot-repair, who does see the windows session, but tell me to activate CSM.
I did, and checked it was actually turned on on subsequent attempts, but the same warning messaged appeared in boot-repair:
-On my installed Ubuntu, it said that a legacy windows version was detected, and I should enable CSM and run boot-repair from a key, preventing me from running boot-repair,
-And on my live usb key (with a temporary install of boot-repair) it said that a legacy windows was detected, and I should enable CSM, but this time it was simply a warning and not a hard block.
I did run it from key (just in case), it was successful, but still no option to launch windows from the GRUB.
Any idea why boot-repair and the ASUS BIOS are disagreeing on the fact that CSM is on/off?


text:
Q: Reconciling @@TRANCOUNT Running SS2005.  I have a script that calls procedureA which in turn calls procedureB.
procedureA has no explicit transactions.  procedureB is split up into several small blocks of non-nested BEGIN and COMMIT TRANSACTION.
I have peppered procedureB with PRINT statements to show me the value of @@TRANCOUNT.  It's always at 0 or 1.
But when I check master..sysprocesses it shows open_tran at 1 or 2.  Where this extra transaction is coming from?
I am posting the 2 procedures below.  pr_Get12Relatives has been stripped of most of its content for clarity as it contains 1600 lines!  It just repeats the same behavior as it searches for different types of relationships.
procedureA = pr_GetRelatives
procedureB = pr_Get12Relatives

A: This thread answers my question..
When a DML statement is currently being executed in a session the open_tran and @@trancount is always at least 2.
For example
Connection 1
CREATE TABLE T( X INT PRIMARY KEY)

GO

BEGIN TRAN

INSERT INTO T VALUES(1)

WAITFOR DELAY '00:01'

ROLLBACK

Connection 2
INSERT INTO T VALUES(1) /*Blocks on Connection 1*/

Connection 3
(look at blocked connection 2)
SELECT lastwaittype,
       open_tran
FROM   master..sysprocesses
WHERE  spid = <spid of connection 2>

Results
+----------------------------------+-----------+
|           lastwaittype           | open_tran |
+----------------------------------+-----------+
| LCK_M_X                          |         2 |
+----------------------------------+-----------+


text:
Q: Why the Range for in a two-dimensional Array is written in this way? This is a tiny program from github.com/pezy/CppPrimer.
int ia[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

// a range for to manage the iteration
for (const int(&p)[4] : ia)
    for (int q : p) cout << q << " ";
cout << endl;

Just want to know why here const int(&p)[4] is used in the range for.
I had intended to use for(int p[4] : ia), because i thought in this way p will become a int[4] so it, whether by values or by reference, would work in the next line when each element in p is accessed by q.
But when I tried for(int p[4] : ia), the compiler said cannot use int* to initialize a int[]. I just don't know why.
Furthure more, I know this code won't work:
int i = 10;
int *c= &i;
int &p = c;

A reference cannot be initialized by a pointer, but according to the error given by the compiler, it seems just the case in this range for.

A: for(int p[4] : ia)

Will try to copy the arrays. That's not allowed in C++.
for(const int(&p)[4] : ia)

uses a reference to iterate the arrays and does not copy their elements. And to the second code snippet:
int &p = c;

p is a reference to int, it cannot refer to a pointer to int. The following is valid:
int *&p = c; // reference to c
int &r = *c; // reference to int pointed to by c

A: Inside the range-for loop's mechanism (described here), something equivalent to this happens :
int ia[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

// begin is deduced to be an int (*)[4]
auto begin = ia, end = ia + 12;

// Hence *begin is an int (&)[4]
int p[4] = *begin;

It is not possible, however, to copy-initialize an array from another array, and the code fails to compile.
The error message you get is because the compiler tries to decay *begin (a reference to a row) to a pointer to the first element of the row, which fails for the same reason.
The working example, however, ends up with :
const int (&p)[4] = *begin;

Which initializes a reference with another reference of the same type, with a const added. Which is perfectly valid.


text:
Q: Swipe between Android activities as with ViewPager In my Android application I have two separate but related top-level screens / activities. I want to have two separate launcher icons for them, but allow the user to "swipe" between them, as with ViewPager.
The options I see are:

*

*Implement two separate activities, and somehow allow swiping between them. The issues is that ViewPager can't be used with two separate activities.

*Implement a single activity with two fragments, and use the ViewPager to switch between them. The swiping is simple, but is it possible to have two launchers that automatically switch to the correct fragment?
Is any of the above two options feasible, or is there something else I can try?

A: I tried solution two, but the issue is that a single activity cannot detect which launcher icon was used (please tell me if I'm wrong).
My solution was to add two "dummy" activities, which then launch the main activity which the correct "page" number. The difficulty with this approach is to handle the task stack properly. When the launcher is selected, the dummy activity must be launched, and it must send an intent to the main activity. Android tries really hard to prevent you from doing this, and just bring the last activity to the front again.
This is the best I could come up with:
The dummy activities (similar for LaunchActivity2):
public class LaunchActivity1 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent newIntent = new Intent(this, MainActivity.class);
        newIntent.putExtra(MainActivity.EXTRA_PAGE, 1);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(newIntent);
        finish();
    }
}

In the main activity:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    ViewPager viewPager = (ViewPager)findViewById(R.id.MainViewPager);
    viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

    int page = getIntent().getIntExtra(EXTRA_PAGE, -1);
    if(page >= 0 && page <= NUM_ITEMS)
        viewPager.setCurrentItem(page);
}

public void onNewIntent(Intent intent) {
    if(intent.hasExtra(EXTRA_PAGE)) {
        int page = intent.getIntExtra(EXTRA_PAGE, -1);
        ViewPager viewPager = (ViewPager)findViewById(R.id.MainViewPager);
        if(page >= 0 && page <= NUM_ITEMS)
            viewPager.setCurrentItem(page);
    }
}

AndroidManifest.xml:
    <!-- LaunchActivity2 is similar -->
    <activity android:name=".LaunchActivity1" android:label="Launch 1"
              android:clearTaskOnLaunch="true"
              android:noHistory="true"
              android:taskAffinity="Launch1"
              android:theme="@android:style/Theme.Translucent.NoTitleBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"
              android:label="My App"
              android:clearTaskOnLaunch="true"
              android:finishOnTaskLaunch="true"
              android:launchMode="singleTask"
              android:taskAffinity="MyApp">
    </activity>

The issue with different task affinities is that both launchers, as well as the main task, appear in the "Recent Applications" list.
I would not recommend this approach to anyone else - rather just use a single launcher icon.

A: Solution 1: You can swipe in terms of starting the other Activity each time. In this case you should fix the transition animation for the two activities in order to have a "swiping" effect and set the two activities as SingleTask in order not to have multiple instances in your task (thus you should implement the onNewIntent() method).
Solution 2: Yeap this is possible. Based on the launcher icon, you should start and show the suitable fragment each time and then use swipe in order to change views.
Hope this helps!

A: I would go for solution 2, there's no need for dummy activities, it'll slow down the launch of your app, instead you can add activity-aliases in your Manifest, like this:
    <activity-alias
        android:name=".MySecondLauncher"
        android:exported="true"
        android:icon="@drawable/my_second_icon"
        android:label="@string/my_second_launcher"
        android:targetActivity=".MainScreen">
        <meta-data
            android:name="secondLauncher"
            android:value="true" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity-alias>

Then, in the MainScreen activity, you can check which launcher you were called with, you can do that by looking for the launcher activity-alias name, or by checking the meta-data I added above:
ComponentName component = intent.getComponent();
String name = component.getShortClassName();
boolean secondLauncher = ".MySecondLauncher".equals(name);

or:
ActivityInfo info = getPackageManager().getActivityInfo(intent.getComponent(),PackageManager.GET_META_DATA);
boolean secondLauncher = info.metaData.getBoolean("secondLauncher", false);

A: I know this is old, but that's the first question I got to when I looked for the same problem.
You can find the solution there: ViewPager for multiple Activities, use Fragments... (it is also in the support library if you need to run on earlier versions of Android)


text:
Q: Creating a dynamic timeline that only takes into account office hours relatively new to excel here.
Pt.1 - Creating a dynamic weekday timeline based on hours
I'm trying to make a timeline based on the hours of each task, like so:

I know how to just add hours to a date&time, but there are a few other things I have to take into account:

*

*Days only run from 08:00 h to 16:00 h, any task that runs past 16:00 h on one day is continued on the next.

*Only counts weekdays, so it goes from Mon->Fri and Fri->Mon

The idea is that I can use this table for any project, and just knowing the time required for each task generates a timeline.
Pt.2 - Adding a column for actual completed dates
To make it even more complicated, I want to add another column, where I can write in when I actually completed a task, that then updates the rest of the table, like this:

I've currently got some massive and admittedly disorganized formulas in the Start and End Columns, though I suspect its better off starting from scratch. They dont work all the time (don't skip weekends, count hours outside the 8am-16pm range), and they are as follows:
Start: =IF(W9<>"", IF(TIME(HOUR(AA8), MINUTE(AA8), SECOND(AA8))<TIME(16,0,0),AA8,DATE(YEAR(AA8),MONTH(AA8),DAY(AA8))+1+TIME(8,0,0))+SUM(INT((WEEKDAY(AA8-{1,7})+DATE(YEAR(AA8),MONTH(AA8),DAY(AA8))+1+TIME(8,0,0)-AA8)/7)), "")=IF(W9<>"", IF(TIME(HOUR(AA8), MINUTE(AA8), SECOND(AA8))<TIME(16,0,0),AA8,DATE(YEAR(AA8),MONTH(AA8),DAY(AA8))+1+TIME(8,0,0))+SUM(INT((WEEKDAY(AA8-{1,7})+DATE(YEAR(AA8),MONTH(AA8),DAY(AA8))+1+TIME(8,0,0)-AA8)/7)), "")
End: =IF(AB10="", IF(W10<>"", IF(TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1,0,0)>TIME(16,0,0), IF(Z10+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1, 0, 0)>TIME(16, 0, 0), IF(HOUR(DATE(YEAR(Z10),MONTH(Z10),DAY(Z10+1))+TIME(8,0,0)+ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0)+TIME(((((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8)-ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0))*8, 0, 0))=8, DATE(YEAR(Z10),MONTH(Z10),DAY(Z10+1))+TIME(8,0,0)+ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0)+TIME(((((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8)-ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0))*8, 0, 0)-(2/3), DATE(YEAR(Z10),MONTH(Z10),DAY(Z10+1))+TIME(8,0,0)+ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0)+TIME(((((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8)-ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0))*8, 0, 0)), Z10+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1, 0, 0)), Z10+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10), 0, 0))+SUM(INT((WEEKDAY(Z10-{1,7})+IF(TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1,0,0)>TIME(16,0,0), IF(Z10+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1, 0, 0)>TIME(16, 0, 0), IF(HOUR(DATE(YEAR(Z10),MONTH(Z10),DAY(Z10+1))+TIME(8,0,0)+ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0)+TIME(((((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8)-ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0))*8, 0, 0))=8, DATE(YEAR(Z10),MONTH(Z10),DAY(Z10+1))+TIME(8,0,0)+ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0)+TIME(((((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8)-ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0))*8, 0, 0)-(2/3), DATE(YEAR(Z10),MONTH(Z10),DAY(Z10+1))+TIME(8,0,0)+ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0)+TIME(((((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8)-ROUNDDOWN(((HOUR((TIME(HOUR(Z10),MINUTE(Z10),SECOND(Z10))))+IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1)-16)/8, 0))*8, 0, 0)), Z10+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10)+1, 0, 0)), Z10+TIME(IF(ISNUMBER(SEARCH("Concept", W10)), Y10/3, Y10), 0, 0))-Z10)/7)), ""), AB10+AC10)

A: Presuming that your the first row of your pictured table is in row 3 and the End column is column D, please paste the formula below to D3, but not before having made a few preparations.

*

*Set up a named range DayStart and enter =Time(8,0,0) into its only cell.

*Set up a named range DayEnd and enter =Time(16,0,0) into its only cell.

*Set up a named range Holidays and enter the dates of non-working days other than Saturdays and Sundays.

These three ranges can be anywhere in the workbook provided their scope includes the worksheet on which the formula is pasted. The holidays will be considered as off-days. The work hours can be changed at any time.
=WORKDAY(C3,INT((((MOD(C3,1)-DayStart)+(B3/24))/(DayEnd-DayStart))),Holidays)+(MOD((((MOD(C3,1)-DayStart)+(B3/24))/(DayEnd-DayStart)),1)*(DayEnd-DayStart))+IF(ABS((((MOD(C3,1)-DayStart)+(B3/24))/(DayEnd-DayStart))-1)>(0.1^4),DayStart,(DayEnd-1))

Here are a few formulas copied form my development process.
=WORKDAY(C3,INT(J3),Holidays)+K3
[K3] =(MOD(J3,1)*(DayEnd-DayStart))+IF(ABS(J3-1)>(0.1^4),DayStart,(DayEnd-1))
[J3] =(I3/(DayEnd-DayStart))
[I3] =(G3+F3)
[G3] =(MOD(C3,1)-DayStart)
[F3] =(B3/24)

[B3] hold the number of hours, not as Time but as a plain integer (didn't try fractions) as in your pictured table.
[C3] promises to be a problem, at least in the format you seem to have.
I used a formula like =DATE(2020,1,22)+TIME(8,0,0) to ensure a proper date. The problem I foresee arises if you intend to use the current date in the table caption to define the date in column C.
FYI, I found the date format you used not convenient because I tested with up to 64 hours and several imaginary holidays. So, I needed a date format like ddd, mmm dd, yyyy hh:mm, to include the full date as well as the weekday.


text:
Q: Setting Key/Value Pairs I've created a List as a property of the class, and want to set the Key/Value pairs when defining the List. I was originally using a structure but realized it's probably not the ideal solution so I changed it to a List. The problem is I'm getting an error with the syntax.
Any ideas?
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>[]
    {
            new KeyValuePair<String, String>("lsd",""),
            new KeyValuePair<String, String>("charset", "")
    };

A: Try this:
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>
{
    new KeyValuePair<String, String>("lsd",""),
    new KeyValuePair<String, String>("charset", "")
};

You had an extra [] in your definition. You are not creating an array, so you don't need it. Also when initializing list with some values, the values should be separated by a comma (,).
In my opinion, a better approach would be to use Tuple class:
pirvate List<Tuple<string, string>> formData = new List<Tuple<string, string>>()
{
    new Tuple<string, string>("lsd",""),
    new Tuple<string, string>("charset", "")
};

A: Probably I'm missing something, but I would have used a Dictionary instead of
So simple....
Dictionary<string, string>formData = new Dictionary<string, string>
{
    {"lsd", "first"},
    {"charset", "second"}
};

and then use it in these ways:
foreach(KeyValuePair<string, string>k in formData)
{
    Console.WriteLine(k.Key);
    Console.WriteLine(k.Value);
}
....
if(formData.ContainsKey("lsd"))
    Console.WriteLine("lsd is already in");
....
string v = formData["lsd"];
Console.WriteLine(v);

A: Change the semi-colon to a comma on the third line and remove the square brackets from the first line.
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>
{
        new KeyValuePair<String, String>("lsd",""),
        new KeyValuePair<String, String>("charset", "")
};

Incidentally, if you change it to a Dictionary you get the ability to look up the values by their key more easily.

A: remove the [] from the declaration

A: private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>()
    {
            new KeyValuePair<String, String>("lsd",""),
            new KeyValuePair<String, String>("charset", "")
    };

*

*Why [] after the constructor?

*Items within collection initializer has to be separated using comma: ,.

A: try
           private List<KeyValuePair<String, String>> formData = new List<KeyValuePair<String, String>>
    {
            new KeyValuePair<String, String>("lsd",""),
            new KeyValuePair<String, String>("charset", "")
    };


text:
Q: Trying Favorite tab inside a .map on react. I cannot change the boolean type on mysql table I have a problem with my fav' tab button. i cannot send the .post and i dont know how to solve it... Here is my frontend code:
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useLocation } from "react-router-dom";
import axios from 'axios';
import { Buffer } from "buffer";

function CompoNuevos() {
  const { state = { success: false } } = useLocation();
  const [cnuevos, setCnuevos] = useState([]);

(...)

  useEffect(() => {
    fetch("http://localhost:3001/api/cnu")
      .then((x) => x.json())
      .then((y) => y.data)
      .then((allCnuevos) => setCnuevos(allCnuevos));
  }, []);
async function handleClick() {
  await axios.post('http://localhost:3001/api/oportunidades', {
    id: cnuevos.id,
    ofertas: true,
  });
}
  return (
(...)
{cnuevos &&
        cnuevos.map((cnuevo) => {
          return (
(...)
<button onClick={handleClick}>Marcar como oferta</button>
);
        })}
export default CompoNuevos;

and here my route:
import express from "express";
import { DataTypes } from "sequelize";
import sequelize from "../models/loadSequalize.js";
import { Sequelize } from "sequelize";

const Oferta = sequelize.define(
  "Oferta",
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
    },
    nombre: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    precio: {
      type: Sequelize.INTEGER,
      allowNull: false,
    },
    descripcion: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    data: {
      type: Sequelize.BLOB("long"),
      allowNull: false,
    },
    ofertas: {
      type: Sequelize.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
  },
  { tableName: "cnuis", timestamps: false }
);

const oportunidadesRouter = express.Router();

oportunidadesRouter.post("/", async (req, res) => {
  const { id, ofertas } = req.body;

  await Oferta.update(
    { ofertas: ofertas },
    {
      where: {
        id: id,
      },
    }
  );

  res.send({ success: true });
});

export default oportunidadesRouter;

i also have the sequelize connection and this:
import express from "express";
import cors from "cors";
(...)
import oportunidadesRouter from './routes/oportunidades.js';
const app = express();
app.use(express.json());

(...)
app.use('/api/oportunidades', oportunidadesRouter);
const port = 3001
app.listen(port, () => console.log(`App listening on port ${port}!`))

anyone knows what's happening on my error?
i tryed different methods but i cannot change the boolean on the database...

A: Since cnuevos is an array, cnuevos.id will return undefined (and the backend logic will fail). You need to pass the id of the item inside the .map as an argument to the function handleClick and use this id on the backend endpoint


text:
Q: Auto update web pages of browser I started learning html few days ago. one thing that frustrate me that I have to refresh the browser every time. I am using vs code. Is there another code editor that can automatically do this for me or some other browser. I am using chrome btw.
expecting : updates web pages automatically

A: There is no need to install another browser or code editor. You can just install live server extenstion in vs code; that automatically does the job for ya.


text:
Q: Split text file (line by line) to different files Looking for data splitter line by line, by using python

*

*RegEx?

*Contain?

As example file "file" contain:
X
X
Y
Z
Z
Z

I need the clean way to split this file into 3 different ones, based on letter
As a sample:
def split_by_platform(FILE_NAME):

    with open(FILE_NAME, "r+") as infile:
        Data = infile.read()
        If the file contains "X"
            write to x.txt
        If the file contains "Y"
            write to y.txt
        If the file contains "Z"
            write to z.txt

x.txt file will look like:
X
X

y.txt file will look like:
Y

z.txt file will look like:
Z
Z
Z

A: EDIT thanks to @bruno desthuilliers, who reminded me of the correct way to go here:
Iterate over the file object (not 'readlines'):
def split_by_platform(FILE_NAME, out1, out2, out3):

    with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3:
        for line in infile:
            if "X" in line:
                of1.write(line)
            elif "Y" in line:
                of2.write(line)
            elif "Z" in line:
                of3.write(line)

EDIT on a hint of @dim:
Here the more general approach for an arbitrary length list of flag chars:
def loop(infilename, flag_chars):
    with open(infilename, 'r') as infile:
        for line in infile:
            for c in flag_chars:
                if c in line:
                    with open(c+'.txt', 'a') as outfile:
                        outfile.write(line)

A: This should do it:
with open('my_text_file.txt') as infile, open('x.txt', 'w') as x, open('y.txt', 'w') as y, open('z.txt', 'w') as z:
    for line in infile:
        if line.startswith('X'):
            x.write(line)
        elif line.startswith('Y'):
            y.write(line)
        elif line.startswith('Z'):
            z.write(line)

A: Here is a more generic way to do the same job:
from collections import Counter

with open("file.txt", "r+") as file:
    data = file.read().splitlines()
    counter = Counter(data)
    array2d = [[key, ] * value for key, value in counter.items()]
    print array2d # [['Y'], ['X', 'X'], ['Z', 'Z', 'Z']]
    for el in array2d:
        with open(str(el[0]) + ".txt", "w") as f:
            [f.write(e + "\n") for e in el]

The above code will generate X.txt, Y.txt and Z.txt with the corresponding values. If you have for example several C letters the code will generate a file C.txt.


text:
Q: Set a specific session timeout for specific sessions I want to set a specific session timeout for specific sessions in the admin panel without affecting the session timeouts of the sessions in the site
I have searched already for answers but all of them affects all of the sessions (not just specific sessions)
Here are the sessions I want to have a specific timeout:
$_SESSION["user_id"]);
$_SESSION["user_first_name"];
$_SESSION["user_last_name"];
$_SESSION["user_email"];
$_SESSION["user_type"];
$_SESSION["user_profile_picture"];


text:
Q: Why after sorting merged lists I receive None instead the merged list when printing it? I have two lists that I slice to show only the first m elements for the first list and the first n elements for the second list.
Then I merge then.
Thereafter I sort the result list, but when I print it, I receive None instead the merged list sorted.
Why?
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 2

nums1 = nums1[:m] #output = [1, 2, 3]
nums2 = nums2[:n] #output = [2, 5]

nums1 = nums1 + nums2 #output = [1, 2, 3, 2, 5]
nums1 = nums1.sort()

print(nums1)
#expected output is [1, 2, 2, 3, 5]
#but receive None


text:
Q: Create a function similar to mnist.train.next_batch(128) for custom image data I am trying to implement the function: batch_x, batch_y = mnist.train.next_batch(128) for my dataset of images.
For training, I have 1000 folders (the name of the folder is the same as which class it belongs to "Class1", "Class2", "Class3" and so on).  Each of these folders conatain 500 images belonging to a single class.
So in all, I have 500,000 images which have to be trained.
What is the best way for me to divide them into batches (where images are randomly selected) and feed to my inference model?
I am not using Keras, and using Tensorflow 1.15.
This is my code:
import tensorflow as tf
tf.enable_eager_execution()
import numpy as np
import os
import pathlib
tf.__version__

AUTOTUNE = tf.data.experimental.AUTOTUNE
SHUFFLE_BUFFER_SIZE = 100
BATCH_SIZE = 128
IMG_WIDTH = 128
IMG_HEIGHT = 256
DATA_DIR = 'D:/PythonWorkspace/train'
DATA_DIR = pathlib.Path(DATA_DIR) #RD

def get_label(file_path):
  # convert the path to a list of path components
  parts = tf.strings.split(file_path, os.path.sep)
  # The second to last is the class-directory
  return parts[-2] == CLASS_NAMES

def decode_img(img):
  # convert the compressed string to a 3D uint8 tensor
  img = tf.image.decode_jpeg(img, channels=3)
  # Use `convert_image_dtype` to convert to floats in the [0,1] range.
  img = tf.image.convert_image_dtype(img, tf.float32)
  # resize the image to the desired size.
  return tf.image.resize(img, [IMG_WIDTH, IMG_HEIGHT])

def process_path(file_path):
  label = get_label(file_path)
  # load the raw data from the file as a string
  img = tf.io.read_file(file_path)
  img = decode_img(img)
  return img, label

#aataset = tf.data.Dataset.list_files(os.path.join(DATA_DIR,'*/*'))
dataset = tf.data.Dataset.list_files(str(DATA_DIR/'*/*')) #RD
for f in dataset.take(5):
  print(f.numpy())
dataset = dataset.map(process_path, num_parallel_calls=AUTOTUNE)
dataset = dataset.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE)
dataset = dataset.repeat()
dataset = dataset.batch(BATCH_SIZE)

Output:
'1.15.2'

b'D:\\PythonWorkspace\\train\\1403\\5T04015F015.jpg'
b'D:\\PythonWorkspace\\train\\0525\\C3T0020F097.jpg'
b'D:\\PythonWorkspace\\train\\0005\\24T0060F004.jpg'
b'D:\\PythonWorkspace\\train\\1159\\45T0008F041.jpg'
b'D:\\PythonWorkspace\\train\\0425\\C5T0021F007.jpg'

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-b683dfeb641b> in <module>
     32 for f in dataset.take(5):
     33   print(f.numpy())
---> 34 dataset = dataset.map(process_path, num_parallel_calls=AUTOTUNE)
     35 dataset = dataset.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE)
     36 dataset = dataset.repeat()

....
....
....
AttributeError: in converted code:

    <ipython-input-2-b683dfeb641b>:24 process_path  *
        label = get_label(file_path)
    <ipython-input-2-b683dfeb641b>:11 get_label  *
        parts = tf.strings.split(file_path, os.path.sep)
    d:\venv\lib\site-packages\tensorflow_core\python\ops\ragged\ragged_string_ops.py:642 strings_split_v1
        return ragged_result.to_sparse()

    AttributeError: 'Tensor' object has no attribute 'to_sparse'

A: You could use tf.data to build a pipeline. For example something like the following, courtesy of the tf.data guide:
AUTOTUNE = tf.data.experimental.AUTOTUNE
SHUFFLE_BUFFER_SIZE = 10000
BATCH_SIZE = 128
IMG_WIDTH = 128
IMG_HEIGHT = 128
DATA_DIR = <Your data dir>

def get_label(file_path):
  # convert the path to a list of path components
  parts = tf.strings.split(file_path, os.path.sep)
  # The second to last is the class-directory
  return parts[-2] == CLASS_NAMES

def decode_img(img):
  # convert the compressed string to a 3D uint8 tensor
  img = tf.image.decode_jpeg(img, channels=3)
  # Use `convert_image_dtype` to convert to floats in the [0,1] range.
  img = tf.image.convert_image_dtype(img, tf.float32)
  # resize the image to the desired size.
  return tf.image.resize(img, [IMG_WIDTH, IMG_HEIGHT])

def process_path(file_path):
  label = get_label(file_path)
  # load the raw data from the file as a string
  img = tf.io.read_file(file_path)
  img = decode_img(img)
  return img, label

dataset = tf.data.Dataset.list_files(str(DATA_DIR/'*/*'))
dataset = dataset.map(process_path, num_parallel_calls=AUTOTUNE)
dataset = dataset.shuffle(buffer_size=SHUFFLE_BUFFER_SIZE)
dataset = dataset.repeat()
dataset = dataset.batch(BATCH_SIZE)

The resulting dataset would then return batches of random images and their labels.


text:
Q: Pubnub history; last value of each light I'm trying to "upgrade" Raspberry Pi Smart House Tutorial (Part 2) in its Web interface part. For now, when you open the Web interface (this one is directly from tutorial) you get default values of sliders set to 0. Is it somehow possible to read the history of a channel (that part I know is possible, at least for the last 100 messages) and extract last values for each light; history looks like this:
{"item": "light-living", "brightness": 6}
{"item": "light-living", "brightness": 9}
{"item": "light-porch", "brightness": 60}
{"item": "fireplace", "brightness": 4}
{"item": "light-porch", "brightness": 88}
{"item": "light-living", "brightness": 4}
{"item": "fireplace", "brightness": 7}
{"item": "light-porch", "brightness": 84}

So, I would have to extract last set value "brightness" for each "item"; in this case light-living, light-porch and fireplace. Can this be done?
JavaScript is used for communication with PubNub.
Thanks for the help.


text:
Q: adding pop up boxes to row names R shiny I am trying to add different messages to different rows in datatable in R shiny. But when I run the below code (this is just an example code, but I want something like that), it only adds the message to one of the row. How can I add to multiple rows?
library(shiny)

library(shinyBS)

library(DT)

ui <- fluidPage(
titlePanel('All you want to know about Titanic'),
fluidRow(

bsButton('tbutton','Lift Titanic'),
br(),
bsTooltip('tbutton', 'This button will inflate a balloon'),
width=2),
mainPanel(dataTableOutput('titanic')
 )
)

server <- function(input, output) {

tdata <- as.data.frame(Titanic)
tdata <- cbind(tdata,tdata)
output$titanic <- DT::renderDataTable({

header <-  htmltools::withTags(table(

  class = 'display',
  thead(
    tr(
      th(rowspan = 1, 'PassengerID'),
      th(colspan = 6, 'Titanic1'),
      th(colspan = 6, 'Titanic2')),
    tr(lapply(c(" ", rep(colnames(as.data.frame(Titanic)), 2)), th))
    )
   )
 )

rownames(tdata)[1] <-
as.character(popify(actionLink(inputId=paste("t_",i,sep=""),
label=rownames(tdata)[1]), title=paste("message1"), placement =
"bottom", trigger = "hover", options = NULL))
rownames(tdata)[2] <-
as.character(popify(actionLink(inputId=paste("t_",i,sep=""),
label=rownames(tdata)[2]), title=paste("message2"), placement =
"bottom", trigger = "hover", options = NULL))
rownames(tdata)[3] <-
as.character(popify(actionLink(inputId=paste("t_",i,sep=""),
label=rownames(tdata)[3]), title=paste("message3"), placement =
"bottom", trigger = "hover", options = NULL))

datatable(tdata, container=header, rownames=TRUE, selection='none',
escape=FALSE)
   })
}

shinyApp(ui = ui, server = server)

A: Here, I modified your code, see if it works for you now:
library(shiny)
library(shinyBS)

library(DT)

ui <- fluidPage(
  titlePanel('All you want to know about Titanic'),
  fluidRow(

    bsButton('tbutton','Lift Titanic'),
    br(),
    bsTooltip('tbutton', 'This button will inflate a balloon'),
    width=2),
  mainPanel(dataTableOutput('titanic')
  )
)

server <- function(input, output) {

  tdata <- as.data.frame(Titanic)
  tdata <- cbind(tdata,tdata)
  output$titanic <- DT::renderDataTable({

    header <-  htmltools::withTags(table(

      class = 'display',
      thead(
        tr(
          th(rowspan = 1, 'PassengerID'),
          th(colspan = 6, 'Titanic1'),
          th(colspan = 6, 'Titanic2')),
        tr(lapply(c(" ", rep(colnames(as.data.frame(Titanic)), 2)), th))
      )
    )
    )

    for (i in 1:3) {

      rownames(tdata)[i] <-
        as.character(
          popify(
            actionLink(inputId = paste("t_",i,sep=""), label = rownames(tdata)[i]),
            title = paste0("message", i),
            placement = "bottom",
            trigger = "hover",
            options = NULL
          )
        )

    }
    datatable(
      tdata, container=header, rownames=TRUE, selection='none', escape=FALSE
    )
  })
}

shinyApp(ui = ui, server = server)


text:
Q: What are dangers of using SSL certificates in embedded systems? I'm working on an embedded system that performs requests to a REST API with HTTPS. In my understanding, the SSL certificate of the server is verified using a bundle of trusted certificates stored locally. In my case they are in a Debian-based package called ca-certificates. This package is from 2019 so I wonder if I have to worry about this package being obsolete one day. If yes, when?

A:
This package is from 2019 so I wonder if I have to worry about this package being obsolete one day.  If yes, when?

The CA certificates in the package have a limited life time. For details look at the expiration times in the specific certificates. Also new publicly trusted CA might be added or less trusted ones removed.
In general it might not be a good idea in the first place to simply trust all public CA in your embedded system in the first place. If there is a fixed endpoint for your device than certificates and CA used there should be trusted instead of the whole world. When doing this the problem gets also smaller, i.e. you only have to worry about the specific CA used and not arbitrary changes to the trusted CA store.


text:
Q: CSS3 transform issue in IE I've got a problem. I have made my sliding menu with CSS3 transform but unfortunatly IE doesnt support that? Does anyone know if there is a fix for it somehow?
It starts out with having this as default:
-webkit-transform: translate(-100%, 0);
-moz-transform: translate(-100%, 0);
-ms-transform: translate(-100%, 0);
-o-transform: translate(-100%, 0);
transform: translate(-100%, 0);
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;
transition: all 1s ease;

And with a javascript click event i add this:
$('.MobilMenuContent').css('-webkit-transform', 'translate(0, 0)', '-moz-transform', 'translate(0, 0)', '-ms-transform', 'translate(0, 0)', '-o-transform', 'translate(0, 0)', 'transform', 'translate(0,0)');

A: As i see [ HERE ] everything is OK!
What do you mean it's not working?
Your question is not clear enough!
CSS:
div {
  width: 5em;
  height: 5em;
  background: #ccc;

  -moz-transform: translate(100px, 0);
  -ms-transform: translate(100px, 0);
  -webkit-transform: translate(100px, 0);
  transform: translate(100px, 0);

  -moz-transition: all 1s;
  -o-transition: all 1s;
  -webkit-transition: all 1s;
  transition: all 1s;
}

JS:
$('div').click(function() {
  $(this).css({
    '-moz-transform': 'translate(0, 0)',
    '-ms-transform': 'translate(0, 0)',
    '-webkit-transform': 'translate(0, 0)',
    'transform': 'translate(0, 0)'
  })
});


text:
Q: Custom Ribbon working but needs some tuning I had a problem that starting Excel from Python whacks the Custom ribbon.
I eventually got code that does the job. Starting Excel from Python does not whack the Custom ribbon anymore.
With complements of losing the state of the global IRibbonUI ribbon object
This was written some years ago.
The code works well on my machine. Quite usable and stable for one's own use but I see some strange things.
Let me just say I know nothing of VBA script nor do I understand the errors. I know other things in the IT field but not code. Hence why I'm here.
Errors I get:
In the Excel VBA editor line 9 text shows red (I dont know why..)
Running the Code in a Libre-Office x64 suite on Win10 x64 I get error
"BASIC syntax error.
Function not allowed within a procedure." (again I dont know why..)
Even more errors come up when running the code in an online compiler. (now I'm even more clueless..)
I have to get this VBA script to work for a personal project I'm working on which is really important to me.
This VBA script must be able to run on Win x64 and x86 platforms and on various Office releases.
All that's needed is some tweaking/tuning a few lines.
I'm asking pretty please if someone can help me to sort the errors.
Thank you in advance.
Much appreciated.
Option Explicit

Public YourRibbon As IRibbonUI
Public ABCDEFG As String

#If VBA7 Then
Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef source As Any, ByVal length As Long)
#Else
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef source As Any, ByVal length As Long)
#End If

Public Sub RibbonOnLoad(ribbon As IRibbonUI)
   ' Store pointer to IRibbonUI
    Set YourRibbon = ribbon
    Sheet1.Range("A1").Value = ObjPtr(ribbon)

End Sub

#If VBA7 Then
Function GetRibbon(ByVal lRibbonPointer As LongPtr) As Object
#Else
Function GetRibbon(ByVal lRibbonPointer As Long) As Object
#End If
        Dim objRibbon As Object
        CopyMemory objRibbon, lRibbonPointer, LenB(lRibbonPointer)
        Set GetRibbon = objRibbon
        Set objRibbon = Nothing
End Function

Sub GetVisible(control As IRibbonControl, ByRef visible)
    If ITTA = "show" Then
        visible = True
    Else
        If control.Tag Like ABCDEFG Then
            visible = True
        Else
            visible = False
        End If
    End If
End Sub

Sub RefreshRibbon(Tag As String)
    ITTA = Tag
    If YourRibbon Is Nothing Then
        Set YourRibbon = GetRibbon(Sheets(1).Range("A1").Value)
        YourRibbon.Invalidate
        'MsgBox "The Ribbon handle was lost, Hopefully this is sorted now by the GetRibbon Function?. You can remove this msgbox, I only use it for testing"
    Else
        YourRibbon.Invalidate
    End If
End Sub

'**********************************************************************************
'Examples to show only the Tab with the tag you want with getVisible in the RibbonX.
'**********************************************************************************

Sub DisplayRibbonTab()
'Show only the Tab, Group or Control with the Tag "ITTA"
    Call RefreshRibbon(Tag:="ITTA")
End Sub

'Sub DisplayRibbonTab_2()
'Show every Tab, Group or Control with every Tag that start with "My"
    'Call RefreshRibbon(Tag:="My*")
'End Sub

'Sub DisplayRibbonTab_3()
'Show every Tab, Group or Control(we use the wildcard "*")
    'Call RefreshRibbon(Tag:="*")
'End Sub

'Note: in this example every macro above will show you the custom tab.
'If you add more custom tabs this will be different

'Sub HideEveryTab()
'Hide every Tab, Group or Control(we use Tag:="")
    'Call RefreshRibbon(Tag:="")
'End Sub

A: A Custom Ribbon does not work on Libre Office.
Libre Office does not make allowance for Custom Ribbons.
Tested: This customUI Ribbon code runs fine in any Windows and Office release.

A: First, there is no need to use Windows API functions for the ribbon custom UI:
#If VBA7 Then
Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef source As Any, ByVal length As Long)
#Else
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef source As Any, ByVal length As Long)
#End If

Second, there is no need to return a pointer to the ribbon UI instance:
#If VBA7 Then
Function GetRibbon(ByVal lRibbonPointer As LongPtr) As Object
#Else
Function GetRibbon(ByVal lRibbonPointer As Long) As Object
#End If
        Dim objRibbon As Object
        CopyMemory objRibbon, lRibbonPointer, LenB(lRibbonPointer)
        Set GetRibbon = objRibbon
        Set objRibbon = Nothing
End Function

All you need to have is a ribbon XML which defines the structure of controls with callbacks defined in the code. The Fluent UI (aka Ribbon UI) is described in depth in the following series of articles:

*

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3)

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 2 of 3)

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)


text:
Q: Define type of the component I play with a Link component from the 4.0.0-beta.2 - it has a field component - ability to override the root element.
I want to create a wrapper around Link - MyLink and pass a component through props:
interface Props {
  component: ???
}

const MyLink = ({component}: Props) => {
  <MUILink component={component} ... />
}

So from type definitions I didn't get how to construct the final type of the component prop:
declare const Link: OverridableComponent<{
  props: LinkBaseProps & {
    TypographyClasses?: TypographyProps['classes'];
    underline?: 'none' | 'hover' | 'always';
  };
  defaultComponent: 'a';
  classKey: LinkClassKey;
}>;

and OverridableComponent:
/**
 * a component whose root component can be controled via a `component` prop
 *
 * Adjusts valid props based on the type of `component`
 */
export interface OverridableComponent<M extends OverridableTypeMap> {
  <C extends React.ElementType>(props: { component: C } & OverrideProps<M, C>): JSX.Element;
  (props: DefaultComponentProps<M>): JSX.Element;
}

Can somebody help me to define the type of component?

A: Looks like
interface Props {
  component: React.ElementType
}

does the trick for Link component.


text:
Q: Can I set an arbitrary value for a IP packet's total length? When I use raw socket to forge a IP packet, it seems that I can set an arbitrary value for its total length without regarding the true size of IP packet.
However, when I use Wireshark to catch the packet, I found the total length has been corrected to be the true size. This really confused me.
Can somebody explain this issue? I will be very grateful for your help.
Thanks.

A: When sending a packet larger than its actual size, the additional data in the payload is a chunk of zeroes. That's what in theory you should see on a captured packet of this kind when inspecting it with Wireshark (or tcpdump). For instance:
IP 192.168.0.3.17664 > 178.60.128.48.1: tcp 32
        0x0000:  4500 0064 f0d0 4000 4006 56ab c0a8 0003  E..d..@.@.V.....
        0x0010:  b23c 8030 4500 0001 0000 0000 ff06 dbe4  .<.0E...........
        0x0020:  c0a8 0003 b23c 8030 04d2 0050 0000 0000  .....<.0...P....
        0x0030:  0000 0000 5002 16d0 b3c4 0000 4142 4344  ....P.......ABCD
        0x0040:  4546 4748 494a 4b4c 4d4e 4f50 5152 5354  EFGHIJKLMNOPQRST
        0x0050:  5556 5758 595a 0000 0000 0000 0000 0000  UVWXYZ..........
        0x0060:  0000 0000                                ....

This is TCP packet to google.com (178.60.128.48). The payload is "ABC...XYZ", but the IP's total_length has been manually increased. The result is zero padding in the payload until completing the total length of the packet.
That said, my bet is that the problem is in the sendto system call. This is the call that actually sends a packet on the socket. But this call also sets the total_length of the packet.
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
               const struct sockaddr *dest_addr, socklen_t addrlen);

I suspect you have tweaked the packet's total_length field in the IPv4 header, but the len parameter on the sendto call has not been modified, so the packet's total length is overwritten to its original size when is sent.
That's my suspicion but it's hard to tell without checking the code.


text:
Q: SVG's appear black on MS Edge Somehow my images are shown perfectly on chrome and firefox, but on MS Edge it appears to be black. I surround my svg files with a html file so I can load them in another html file. Is this a known-issue? And does somebody have a solution?
Example:
https://imgur.com/a/kFlIiW6
The code structure looks like this:
<template style="display: flex">
<svg class="svgclassname" viewBox="0 0 128 128">
<--Styling and paths-->
</svg>
</template>

Thanks in advance!

A: If you surround your SVG with HTML and wish to use them in another HTML file, you can include them as images, instead.
<img src="mysvg.svg"/>

If you want to change fill, stroke or some other property, you will need to do that for that from the main SVG file.

A: For some reason MS Edge ignored my styling WITHIN the svg file. Calling fill on the paths fixed my issue.