Q: Take the subset of the file related to the time stamp I have some json file in dictionary format. The lines looks like here:
{"a":"1", "b":"2", "c":"3", "time":1334572551435}
{"a":"1", "b":"2", "c":"4", "time":1334575352456}
{"a":"2", "b":"2", "c":"7", "time":1334575335345}
...

time is in a UTC format. The whole file has about 300 milliones unique lines (anyway the same time could come twice). How I can choose a lines for some particular time, for example between 1334575352456 and 1334575353456?
I personally have the next idea from some tutorial:
awk ’$"time" == 1334575352456, $"time" == 1334575353456’ inputfile.json

anyway, I suppose this solution is for column "time", not for dictionary with the key "time" (Actually $"time" should be $4)

A: Try:
$ awk -F'[:}]' '$(NF-1) >= 1334575352456 && $(NF-1) <= 1334575353456' file
{"a":"1", "b":"2", "c":"4", "time":1334575352456}

-F'[:}]' set fields delimiter is : or }, so you can access the the time value by accessing second from last field, using $(NF-1).
To save ouput, use:
$ awk -F'[:}]' '$(NF-1) >= 1334575352456 && $(NF-1) <= 1334575353456' file > output.txt

If you have gawk 4.1.0 and above, you can use -i option to make edit inplace:
$ awk -i inplace -F'[:}]' '$(NF-1) >= 1334575352456 && $(NF-1) <= 1334575353456' file

A: Since the input is a set of JSON objects, it makes sense to use a JSON-aware tool.
Using the jq JSON processor to extract only the entries that have a time value strictly between some t0 and t1 time values (the -c option used here selects "compact" output):
jq -c --argjson t0 1334572551435 --argjson t1 1334575352456 \
    'select(.time > $t0 and .time < $t1)' file

The equivalent command with Miller (mlr), albeit without parametrising the start and end of the time range:
mlr --json filter '$time > 1334572551435 && $time < 1334575352456' file


Q: How to use function recursively in javascript? I have one form where on keyup function I am showing amount in words below that input. It's working as expected with my function. Now O have another input with 2 radio buttons. Onchange this radio buttons also I have to work my function of ShowAmountInWords. I am stuck here.   Suppose, I have 2 radio buttons with FD and RD. Limit for FD is 10 digits and Limit for RD is 11 digits.

$(document).ready(function() {
  $('#amount').on('keyup', function() {
    var amountInWrods = $('#amount').val();
    var words = changeToWord(amountInWrods); //calling that function to show amount in words
    $('#words').val(words);

  });
});

function changeToWord(amount) {
  //code to convert number to word
  return amountInWrods;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='amount' id='amount'>
<label id='words'>To show Amount in words</label>
<input type="radio" id="FD" name="tyoeofdeposit" value="FD">
<input type="radio" id="RD" name="tyoeofdeposit" value="RD">

I am adding my code for radio button validation inside above function.

function changeToWord(amount) {
  $('input[type=radio][name=typeofDeposit]').change(function() {
    if (this.value == 'FD') {
      if (amount > 10) {
        return 'input less amount';
      }
    } else if (this.value == 'RD') {
      if (amount > 11) {
        return 'input less amount';
      }
    }
  });
  //code to convert number to word
  return amountInWrods;
}

User will input amount and it will go to onkeyup event and from here it will go to function changetowords in that it will check for deposit type  If user input 10 digits with FD then it will show amount in words  If user input 11 digits with FD then it will return error msg. same for RD. But problem is  when FD is selected and user will add 11 digits so it returns errormsg but now, user want to change deposit type to RD so in this case that errormsg should be gone and Amountinwords should return proper response.I am stuck here.I tried with recursion function but it shows me error of max size exceeded.


Q: Red5 application debug i'm trying to deploy my red5 app to the webapps folder.  But! I've got some errors in my output.
    Exception in thread "Launcher:/myApp" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'web.context' defined in ServletContext resource [/WEB-INF/red5-web.xml]: Unsatisfied dependency expressed through bean property 'clientRegistry': : Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1147)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1040)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
    at org.red5.server.tomcat.TomcatLoader$1.run(TomcatLoader.java:594)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.red5.core.Application] for bean with name 'web.handler' defined in ServletContext resource [/WEB-INF/red5-web.xml]; nested exception is java.lang.ClassNotFoundException: org.red5.core.Application
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1208)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:568)
[INFO] [Launcher:/myApp] org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1af1915: defining beans [placeholderConfig,web.context,web.scope,web.handler]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@46136
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:302)
    at org.springframework.beans.factory.BeanFactoryUtils.beanNamesForTypeIncludingAncestors(BeanFactoryUtils.java:185)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:805)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:762)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:680)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1132)
    ... 11 more
Caused by: java.lang.ClassNotFoundException: org.red5.core.Application
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1484)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1329)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:258)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1200)
    ... 19 more

After all of that i've got my app folder in webapps, but there is no .class file in the classes folder of my project. So, i can't use server-side app in my client app.
What's wrong?
App was built by default. Here is my red5-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <!--
    Defines a properties file for dereferencing variables
    -->
    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/WEB-INF/red5-web.properties" />
    </bean>

    <!--
    Defines the web context
    -->
    <bean id="web.context" class="org.red5.server.Context"
        autowire="byType" />

    <!--
    Defines the web scopes
    -->
    <bean id="web.scope" class="org.red5.server.WebScope"
         init-method="register">
        <property name="server" ref="red5.server" />
        <property name="parent" ref="global.scope" />
        <property name="context" ref="web.context" />
        <property name="handler" ref="web.handler" />
        <property name="contextPath" value="${webapp.contextPath}" />
        <property name="virtualHosts" value="${webapp.virtualHosts}" />
    </bean>

    <!--
    Defines the web handler which acts as an applications endpoint
    -->
    <bean id="web.handler"
        class="org.red5.core.Application"
        singleton="true" />

</beans>

And my Application class
package org.red5.core;

/*
 * RED5 Open Source Flash Server - http://www.osflash.org/red5
 *
 * Copyright (c) 2006-2008 by respective authors (see below). All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.service.ServiceUtils;

/**
 * Sample application that uses the client manager.
 *
 * @author The Red5 Project (red5@osflash.org)
 */
public class Application extends ApplicationAdapter {

    /** {@inheritDoc} */
    @Override
    public boolean connect(IConnection conn, IScope scope, Object[] params) {
        return true;
    }

    /** {@inheritDoc} */
    @Override
    public void disconnect(IConnection conn, IScope scope) {
        super.disconnect(conn, scope);
    }

}

I did all of that with Red5 plugin in Eclipse. So... i have no idea what could be wrong..

A: I had the exact same problem.  Sounds like you're trying to follow the tutorial videos only using the new Red5_1.0, Like I was.  After many days, beers, and bruises from banging my head against my desk, I discovered that if you change your class to "org.red5.server.scope.WebScope" in your red5-web.xml file it should work correctly (bean id="web.scope").  Also, you may need to change your org.red5.core source imports from "import org.red5.server.api.IScope;" to "import org.red5.server.api.scope.IScope;".  Apparently there has been some class refactoring in the newer versions of Red5

A: I was getting a similar error, although when I checked my class was already set to "org.red5.server.scope.WebScope" as mentioned in Ninth Realm Matt's answer. I later found that I was missing the lib directory under webaps/chat/WEB-INF/.
This may be useful if anyone else has a similar problem.


Q: Increasing the number of connections MySQL 8 can handle (Debian 9 server) and auto restart event scheduler I have a Debian 9 server (12 CPUs, 80GB of RAM), running Percona server for MySQL 8.0, about 1100 clients per second, the load is not very high around 0.3 to 2.30
Latested numbers from show engine innodb status: 183.82 inserts/s, 169.69 updates/s, 5.79 deletes/s, 2179444.29 reads/s
It runs really nice most of the time, but lately time to time it suddenly refuses new connections (when a very busy table gets locked for a long time or some query takes too long).
The logs shows:
[ERROR] [MY-000000] [connection_h] Error log throttle:       1912 'Can't create thread to handle new connection' error(s) suppressed
[ERROR] [MY-010249] [Server] Can't create thread to handle new connection(errno= 11)
[ERROR] [MY-010053] [Server] Event_scheduler::execute_top: Can not create event worker thread (errno=11). Stopping event scheduler

So, basically I have two questions:
1. How to tweak the server to accept more connections (I tried a lot of things which I will list below), it cant handle more than 4821
   to be exact
2. Whenever that happens, the event scheduler stops and I have to manually enable it again, its really bad because I have some MEMORY
   tables that gets full, they handle the heavy traffic and dumps to
   other tables every 5 seconds

Until now I've tried setting the soft and hard limits in /etc/security/limits.conf for *, mysql and root users:
*         hard    nofile      400000
*         soft    nofile      400000
*         hard    nproc       400000
*         soft    nproc       400000
mysql     hard    nofile      400000
mysql     soft    nofile      400000
root      hard    nofile      400000
root      soft    nofile      400000

I also have made many adjusments to /etc/sysctl.conf listing some below:
kernel.pid_max = 262144
vm.max_map_count = 262144
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.ip_local_port_range = 2000 65500
net.ipv4.tcp_max_syn_backlog = 32768
fs.file-max = 450000
net.core.netdev_max_backlog = 450000
net.core.somaxconn = 32768

I also made changes to systemd conf files: /lib/systemd/system/mysql.service - setting:
LimitNOFILE=220000
TasksMax=32768

mysqld.conf
bind-address                    = 0.0.0.0

# GENERAL #
user                           = mysql
default-storage-engine         = InnoDB
socket                         = /var/run/mysqld/mysqld.sock
pid-file                       = /var/lib/mysql/mysql.pid

# SAFETY #
max-allowed-packet             = 16M
max-connect-errors             = 1000000
skip-name-resolve
sysdate-is-now                 = 1
innodb                         = FORCE

wait-timeout                   = 600

# DATA STORAGE #
datadir                        = /var/lib/mysql/

# BINARY LOGGING #
sync-binlog                    = 0

# CACHES AND LIMITS #
tmp-table-size                 = 32M
max-heap-table-size            = 32M
max-connections                = 20000
thread-cache-size              = 300
open-files-limit               = 65535
table-definition-cache         = 4096
table-open-cache               = 4096

# INNODB #
innodb-flush-method            = O_DIRECT
innodb-log-files-in-group      = 2
innodb-log-file-size           = 512M
innodb-flush-log-at-trx-commit = 0
innodb-file-per-table          = 1
innodb-buffer-pool-size        = 64G
innodb-fast-shutdown           = 0
innodb-buffer-pool-dump-pct    = 75
innodb-buffer-pool-dump-at-shutdown = 1
innodb-buffer-pool-load-at-startup  = 1
innodb-io-capacity             = 400
innodb-io-capacity-max         = 2000

# LOGGING #
log-error                      = /var/log/mysql/mysql-error.log
log-queries-not-using-indexes  = 0
slow-query-log                 = 1
slow-query-log-file            = /var/log/mysql/mysql-slow.log
long-query-time                = 5

event_scheduler = 1
general_log_file               = /var/log/mysql/general.log
general_log                    = 0
local-infile                   = 1

I don't know what else I can do or where else I can look, tried to search for the problems and couldn't find anything that works, for the event scheduler its even worse, there's almost nothing to be found about that (try to search in google MY-010053 or Can not create event worker thread almost no results)
The server does not get unresponsive or slow, if I lock the tables on purpose, I start getting the error in about 10 seconds, and when I unlock it recover immediatly
As Wilson Hauck requested:
ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 326193
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 400000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 326193
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

iostat -xm 5 3
Linux 4.9.0-8-amd64 (zelda)     03/07/2019      _x86_64_        (12 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          11.24    0.00    1.56    0.76    0.00   86.44

Device:         rrqm/s   wrqm/s     r/s     w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sda               0.41    44.17    2.41   67.61     0.05     1.61    48.55     0.37    5.23    4.74    5.25   1.37   9.59

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           9.77    0.00    1.91    0.82    0.00   87.51

Device:         rrqm/s   wrqm/s     r/s     w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sda               0.00    52.20    0.00   81.60     0.00     1.85    46.51     0.45    5.51    0.00    5.51   1.14   9.28

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           5.83    0.00    1.41    0.77    0.00   91.99

Device:         rrqm/s   wrqm/s     r/s     w/s    rMB/s    wMB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sda               0.00   132.00    0.00  161.40     0.00     8.12   103.00     0.88    5.47    0.00    5.47   0.66  10.72

show full processlist there's nothing special:
4087783 event_scheduler localhost       Daemon  1   Waiting for next activation     0   0
275050068   xgh 179.191.66.174:51143    xgh Sleep   3           0   0
275050130   xgh 179.191.66.174:51144    xgh Query   0   starting    show full processlist   0   0
300324788   xgh 179.191.66.174:40708    xgh Sleep   12595           5   61
304505269   xgh 179.191.66.174:51680    xgh Sleep   72          0   0
304505986   xgh 179.191.66.174:51706    xgh Sleep   72          0   0
305818676   xgh 172.30.5.2:57288    xgh Query   0   Sending data    SELECT *
 FROM (`noticias`.`noticia`)
 WHERE `texto` =  'Carlos Ghosn deixa prisão após mais de 100 dias detido em Tóquio'    0   0
305818680   xgh 172.30.5.2:57296    xgh Sleep   57          0   0
305818682   xgh 172.30.5.2:57302    xgh Sleep   57          0   0
305818689   xgh 172.30.5.2:57316    xgh Sleep   57          0   0
305818692   xgh 172.30.5.2:57324    xgh Sleep   57          0   0
305842475   xgh 172.30.5.2:49326    xgh Sleep   1           94  550698
305842479   xgh 172.30.5.2:49334    xgh Sleep   1           0   0
305842481   xgh 172.30.5.2:49340    xgh Sleep   1           0   0
305842486   xgh 172.30.5.2:49350    xgh Sleep   1           0   0
305842489   xgh 172.30.5.2:49358    xgh Sleep   1           0   0
305842492   xgh 172.30.5.2:49364    xgh Sleep   1           0   0
305842496   xgh 172.30.5.2:49372    xgh Sleep   1           0   0
305842498   xgh 172.30.5.2:49376    xgh Sleep   1           0   0
305842501   xgh 172.30.5.2:49382    xgh Sleep   1           0   0
305842505   xgh 172.30.5.2:49392    xgh Sleep   1           0   0
305842508   xgh 172.30.5.2:49398    xgh Sleep   1           0   0

SHOW GLOBAL STATUS: https://pastebin.com/cg1v5bHD
SHOW GLOBAL VARIABLES: https://pastebin.com/8mkTzpr0

A: Please provide SHOW CREATE TABLE noticia.  If texto is of type TEXT, then the one running query in the PROCESSLIST requires a table scan.  If it is VARCHAR, then an index would probably help.
You claim there are lots of connections, but I see only one doing anything.  So SHOW FULL PROCESSLIST again, hoping to get several queries.

A: Rate Per Second=RPS - Suggestions to consider for your my.cnf [mysqld] section
innodb_lru_scan_depth=100  # from 1024 to conserve 90% of CPU cycles used for function
innodb_flushing_avg_loops=5  # from 30 to reduce delay and reduce innodb_buffer_pool_pages_dirty of 90,000 +
innodb_io_capacity=1900  # from 400 to allow higher IOPS to data devices
read_rnd_buffer_size=128K  # from 256K to reduce handler_read_rnd_next RPS of ~ 600,000 RPS

Monitor innodb_buffer_pool_pages_dirty with SHOW GLOBAL STATUS LIKE '%dirty%';
Time consumers that need to be reviewed, A) com_rollback_to_savepoint AVG 1 every 62 seconds, B) handler_rollback AVG 1 every 52 seconds, C) handler_savepoint_rollback AVG 1 every 31 seconds.
Disclaimer: I am the author of mysqlservertuning.com as listed in my profile, Network profile.  Good luck with your instance averaging 367 connections per second.


Q: Javascript to jquery a document.get with children What is the equivalent of this to jquery and how can I shorten it using children (both in jquery and javascript as I'm really curious why mine didn't work)? I tried children actually but didn't get a result I wanted.
document.getElementById('ShowRow').getElementsByClassName('value')[0].getElementsByTagName('a')[0].innerHTML

Thanks in advance

A: Something like this:
$('#ShowRow').find('.value:first a:first').html()

A: You can do:
$('#ShowRow').find('.value:first a:first').html()


Q: How to open page in new tab from GridView? I want to open page in new tab while clicking on the gridview link button. But I want to open new page based on alert type. For example, from the given below grid I clicked link button of Alert1 then it should open alert1.aspx page, if it is Alert2 then alert2.aspx. etc
Help me to find a proper solution. Thank you.
GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeader="False">
    <Columns>
    <asp:TemplateField HeaderText="Alert Type" SortExpression="Alert_Type">
    <EditItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Alert_Type") %>'>
    </asp:Label>
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Alert_Type") %>'>
    </asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Created_Time" HeaderText="Created Time"
    ReadOnly="True" SortExpression="Created_Time" />
    <asp:TemplateField >
    <ItemTemplate>
    <asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click">
    </asp:LinkButton>
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
 </asp:GridView>

C#:
protected void lnk_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_newtab');", true);
}

A: Here's the solution that you looking for:
 protected void lnk_Click(object sender, EventArgs e)
 {
      LinkButton lnk = sender as LinkButton;
      Label Label1 = lnk.NamingContainer.FindControl("Label1") as Label;

      if (Label1.Text == "Alert1")
      {
          Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);
      }
      else if (Label1.Text == "Alert2")
      {
          Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert2.aspx','_blank');", true);
      }
 }

Also, Give unique names to controls inside GridView.

A: Replace '_newtab' to '_blank'
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);

A: You need to set target attribute to _blank
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);

The second argument in window.open is to specify whether you want to open page in new tab or in existing tab. So you need to set it to _blank to open page in new tab

A: set CommandName to alert type and access it  in click event
 <asp:LinkButton ID="lnk" runat="server" Text="Click" OnClick="lnk_Click" CommandArgument='<%# Bind("Alert_Type") %>'>
</asp:LinkButton>

Click event
protected void lnk_Click(object sender, EventArgs e)
{
string alerttype=e.CommandArgument.ToString();
Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open("+alerttype+"'.aspx','_newtab');", true);
}


Q: Replace image with different image/button - javascript within a function, I'm trying to replace a image/button with another image/button.

But I have the problem that there is two of the same button, (button 2) when it is replaced! (one at the top of the page, and one where it is meant to be). I was wondering if there is a way of getting rid of the extra button at the top, or creating the button element within the javascript function?
Thanks for any help.

A: You can remove an element in javascript using
var el = document.getElementById('id');
var remElement = (el.parentNode).removeChild(el);

A: I'd suggest something akin to the following:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum).src;
    }
    else {
        var next = document.getElementById(nextElemId).src;
    }

    elem.src = next;
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum);
    }
    else {
        var next = document.getElementById(nextElemId);
    }
    if (!next){
        return false;
    }
    elem.style.display = 'none';
    next.style.display = 'inline-block';
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum);
    }
    else {
        var next = document.getElementById(nextElemId);
    }
    if (!next){
        return false;
    }
    elem.parentNode.insertBefore(next,elem.nextSibling);
    elem.style.display = 'none';
    next.style.display = 'inline-block';
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

A: You can hide the first button, not only change the image source. The code below shows one way of doing that.


Q: Global instance method I created a an instance method in my MainMenu init.
-(NSString*) iPhoneiPadConversionString: (NSString*) fileNameHold : (char) fileType {

....My Code.
}

All I want to do is reuse this method in my other classes....
fileName = [self iPhoneiPadCOnversionString: @"background.png": 'B'];

But I can't seem to figure out what the right stuff to do is... I have been trolling the board and can't quite put all the information together.  Any Help would be greatly appreciated.

A: What you want is a called a "category". With categories you can extend NSString (and add your method).
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html


Q: creating separate rules for horizontal and vertical alignment in css The plunkr link is https://plnkr.co/edit/mv3lL1vwu2LxoeFZw0TX
I want to position a div at the center of a page (vertically and horizontally). The div has a button which should be at the center of the div. I found a solution in Vertically center in viewport using CSS but it doesn't work for me. Also, I want to create two separate rules, one for vertical alignment and one for horizontal alignment and use them together (or separately) so that I can pick which element should be aligned in which way.
I do not want to use Flex, Bootstrap etc. as I am trying to understand CSS concepts.
the horizontal alignment rule is straightforward.
.center-horizontally-common-styles {
    display: block;
    margin: auto auto;
}

The vertical alignment rule is (modified from the SO link)
.centre-vertical-common-styles {
   position: fixed;
    right: 50%;
    top: 50%;
    transform: translateY(-50%);
    transform: translateX(50%);
}

.debug-border-common-styles {
    border: 3px solid black;
    height:40px;
    width:200px;
}

HTML
<div class="debug-border-common-styles centre-vertical-common-styles center-horizontally-common-styles">
    <button type="button"> Click Me! </button>
</div>

My understanding is that right: 50%; top: 50%; will use the browser's window (viewport?) as the reference and move the div's top edge and right edge to the location which is 50% mark of the browser's respective edge's location. TranslateY and TranslateX should now move the div upwards (-50%) and towards left(50%) respectively to align the button's center to the middle of the page thus centering the button. The issues I am facing are:
1) The translateY doesn't seem to work. If I change the height of the div to say 200px. the div starts growing downwards (i.e. its top edge seem to be fixed!) It doesn't happen if the width is changed to say 200px.
.debug-border-common-styles {
    border: 3px solid black;
    height:200px;
    width:200px;
}

2) The button inside the div is not at the center of the div. I created the following css rule for the button but translateY doesn't seem to work on this one as well.
.centre-button-vertical-common-styles {
   position: absolute; /*use absolute so that the origin is no the parent div*/
   right: 50%;
   top: 50%;
   transform: translateY(-50%);
   transform: translateX(50%);
}

3) Ideally, I would like to create two separate rules, say .center-vertical and .center-horizontal and combine them to use the desired effect. But If I do something like follows, it doesn't work. Is it possible to create two separate rules?
.center-horizontally-common-styles {
    display: block;
    margin: auto auto;
}

Not use right here because horizontal rule should place the item in middle
.centre-button-vertical-common-styles {
   position: absolute;
   top: 50%;
   transform: translateY(-50%);
}

A: Bro, you need few arrows of style. Do like this:)
 .centre-vertical-common-styles {
       position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
    .debug-border-common-styles {
        border: 3px solid black;
        height:40px;
        width:200px;
        display:flex;
        align-items:center;
        justify-content:center;
    }


Q: Perl Vs Python variable Scoping - gotchas to be aware of While investigating scoping in Perl and Python, I came across a silent scoping related behavior of Perl that can cause bugs very difficult to trace.  Specifically for programmers who are new to the language and not fully aware of all it's nuances.  I have provided example code for both Perl and Python to illustrate how scoping works in both the languages
In Python if we run the code:
    x = 30
    def g():
        s1 = x
        print "Inside g(): Value of x is %d" % s1

    def t(var):
        x = var
        print "Inside t(): Value of x is %d" % x
        def tt():
            s1 = x
            print "Inside t()-tt(): Value of x is %d" % x
        tt()
        g()

   t(200)

The resulting output is:
Inside t(): Value of x is 200
Inside t()-tt(): Value of x is 200
Inside g(): Value of x is 30

This is the usual lexical scoping behavior.  Python treats an assignment in a block by default as the definition and assignment to a new variable, not to the global variable that may exist in the enclosing scope.  To override this behavior, the keyword global needs to be used explicitly to modify the global variable x instead. The scope of the variable x in the function g() is determined by the place in the program where it is defined, not where the function g() gets called.  As a result of lexical scoping behavior in Python when the function g() is called within the function t() where another lexically scoped variable x is also defined and set to the value of 200, g() still displays the old value 30, as that is the value of the variable x in scope where g() was defined.  The function tt() displays a value of 200 for the variable x that is in the the lexical scope of tt().  Python has only lexical scoping and that is the default behavior.
By contrast Perl provides the flexibility of using lexical scoping as well as dynamic scoping.  Which can be a boon in some cases, but can also lead to hard to find bugs if the programmer is not careful and understands how scoping works in Perl.
To illustrate this subtle behavior, if we execute the following Perl code:
use strict;
our $x = 30;
sub g {
    my $s = $x;
    print "Inside g\(\)\: Value of x is ${s}\n";
}
sub t {
    $x = shift;
    print "Inside t\(\)\: Value of x is ${x}\n";
    sub tt {
        my $p = $x;
        print "Inside t\(\)-tt\(\)\: Value of x is ${p}\n";
    }
    tt($x);
    g();
}
sub h {
    local $x = 2000;
    print "Inside h\(\)\: Value of x is ${x}\n";
    sub hh {
        my $p = $x;
        print "Inside h\(\)-hh\(\)\: Value of x is ${p}\n";
    }
    hh($x);
    g();
}
sub r {
    my $x = shift;
    print "Inside r\(\)\: Value of x is ${x}\n";
    sub rr {
        my $p = $x;
        print "Inside r\(\)-rr\(\)\: Value of x is ${p}\n";
    }
    rr($x);
    g();
}
g();
t(500);
g();
h(700);
g();
r(900);
g();

the resulting output is:
Inside g(): Value of x is 30
Inside t(): Value of x is 500
Inside t()-tt(): Value of x is 500
Inside g(): Value of x is 500
Inside g(): Value of x is 500
Inside h(): Value of x is 2000
Inside h()-hh(): Value of x is 2000
Inside g(): Value of x is 2000
Inside g(): Value of x is 500
Inside r(): Value of x is 900
Inside r()-rr(): Value of x is 900
Inside g(): Value of x is 500
Inside g(): Value of x is 500

The line our $x defines/declares a global variable $x visible throughout the Package/code body.  The first call to t() the global variable $x is modified and this change is visible globally.
Perl as opposed to Python by default just assigns a value to a variable, whereas Python by default defines a new variable and assigns a value to it within a scope.  That is why we have the different results in the Python and the Perl code above.
That is why even the call to g() within t() prints the value 500.  The call to g() immediately after the call to t() also prints 500 and proves that the call to t() indeed modified the global variable $x in the global scope.  $x within function t() is lexically scoped, but not displaying the expected behavior as the assignment at line 8 makes a global change to the variable $x in the global scope.  This results in the call to g() within t() displaying 500 instead of 30.
In the call to the function h() where g() is called (line 25), the function g() prints 2000, similar to the output from function t().  However when the function h() returns and we again call g() immediately after it, we find that
$x has not changed at all.  That is the change to $x within h() did not change $x in it's global scope but only within the scope of h().  The change to $x is somehow temporarily confined to within the current scope where the local keyword is used.  This is dynamic scoping in practice in Perl.  The call to g() returns the value of the variable $x in the current execution scope of g() instead of the value of $x where g() is defined within the code a.k.a lexical scope.
Finally in the call to function r() at line 28, the keyword my forces the creation of a new lexically scoped local variable, identical to the behavior within function t() in the Python code snippet.  This is in stark contrast to what happened within h() or t() where no new variable was ever created.  Within function r() we observe that the call to g() actually prints the value of $x as 500, the value $x has in the lexical scope where g() has been defined and not the value in the current execution scope of g() (as opposed to dynamic scope result in h()).  The Perl function r() is the closest match in terms of scoping behavior to the original Python function t().
By default Perl modifies the global variable $x instead of creating a new lexically scoped $x variable as in Python, and this can be some times a source of confusion and errors to a Perl newbie.  For statically typed languages, this is not an issue as variables need to be declared explicitly and the chances of any confusion of whether an existing variable is being assigned to or a new variable is being defined and assigned to does not arise.  In dynamically typed languages, that do not require explicit declaration and where the programmer is unaware of the consequences of not using scoping syntaxes appropriately (as in use of my in Perl), it can often lead to unintended consequences if one is not careful.   The programmer might think that a new variable is being declared at line 8, but actually the global variable $x is being modified.  This is exactly the way Perl intends it to be used, but can lead to interesting effects if the programmer is not careful and not fully aware of what it means.  This kind of error could get difficult to catch and debug in a large program of several hundreds or thousands of lines of code.  The thing to remember is that without a my prefix, Perl treats assignments to variables as just assignments not a definition + assignment.
Perl treats assignment in a block by default as assignment to the global variable of the same name and requires explicit override by using my to define + assign to a lexically scoped local variable.
Python has opposite default behavior and treats all assignments in a block by default as defining and assigning to a local lexically scoped variable.  The use of the global key word needs to be explicitly used to override this default behavior.
I feel Python's default behavior is safer and maybe kinder to novice and intermediate level programmers than Perl's default scoping behavior.
Please add any other subtle scoping related issues to be aware of for both Perl and Python that you may be aware of.

A: The line $x = shift in your second Perl example just overwrites a global, lexically-scoped variable, same as if you would add global x to your Python code.
This has nothing to do with dynamic scoping, and there are many other languages with the same behaviour as Perl - I'd consider Python the odd man out here for requiring to explicitly import a variable name visible at lexical scope.
The real problem with the Perl code is not lexical scoping, but lack of declared parameters. With declared parameters, it would be impossible to forget the my, and the problem would go away as well.
I find Python's approach to scoping (as of Python 2) far more problematic: it's inconsistent (explicit imports for globals to get a read-write binding, whereas lexicals in nested functions are bound automatically, but read-only) and makes closures secon-class citizens.


Q: kernel gets stuck if I train/test split by 55% and 45% I am trying to train a neural net on a dataset. Everything works. There is no issue with the code if I specifiy 70% or 50% percent of the data as training and the rest as testing. But as I specify 55% and 45% for training and testing, the kernel gets stuck and gives the following error:
Error in plot.nn(nnet, rep = "best"): weights were not calculated
Traceback:

1. plot(nnet, rep = "best")
2. plot(nnet, rep = "best")
3. plot.nn(nnet, rep = "best")
4. stop("weights were not calculated")

Here is the code that I have written so far:
library(neuralnet)
    Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset
    for(i in 1:ncol(Main)){
      Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE)
    }
    set.seed(123)
# in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly
    indexes = createDataPartition(Main$Type, p=0.55, list = F)

    # Creating test and train sets.
    train = Main[indexes, ]
    test = Main[-indexes, ]
    xtest = test[, -1]
    ytest = test[, 1]

    nnet = neuralnet(Type~., train, hidden = 5, linear.output = FALSE)

    # Plotting
    plot(nnet, rep = "best")

    # Predictions
    ypred = neuralnet::compute(nnet, xtest)

    yhat = ypred$net.result
    yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal",
                                  ifelse(max.col(yhat[ ,1:4])==2, "Proneural",
                                         ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural"))))

    # Confusion matrix
    cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest))
    print(cm)

Here is a link to the: Dataset

A: By adding just act.fct = "tanh" parameter in the model, everything runs smoothly.
Here is the working version:
    library(neuralnet)
    Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset
    for(i in 1:ncol(Main)){
      Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE)
    }
    set.seed(123)
    # in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly
    indexes = createDataPartition(Main$Type, p=0.55, list = F)

    # Creating test and train sets.
    train = Main[indexes, ]
    test = Main[-indexes, ]
    xtest = test[, -1]
    ytest = test[, 1]

    nnet = neuralnet(Type~., train, hidden = 5, act.fct="tanh", linear.output = FALSE)

    # Plotting
    plot(nnet, rep = "best")

    # Predictions
    ypred = neuralnet::compute(nnet, xtest)

    yhat = ypred$net.result
    yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal",
                                  ifelse(max.col(yhat[ ,1:4])==2, "Proneural",
                                         ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural"))))

    # Confusion matrix
    cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest))
    print(cm)


Q: yolov4-tiny on Colab. ConverterError: Variable constant folding is failed I'm trying to convert the tensorflow weights to tensorflow lite. First of all, I converted.tflite from generating TensorFlow SavedModel. I do this in Google colab. Can I execute this code?
%cd /content/tensorflow-yolov4-tflite
!python convert_tflite.py --weights ./checkpoints/yolov4-tiny-pretflite-416 --output ./checkpoints/yolov4-tiny-416.tflite

then the result
`tensorflow.lite.python.convert_phase.ConverterError`: Variable constant folding is failed. Please consider using enabling `experimental_enable_resource_variables` flag in the TFLite converter object. For example, converter.experimental_enable_resource_variables = True

btw, this my file convert_tflite.py
    import tensorflow as tf
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
import cv2
from core.yolov4 import YOLOv4, YOLOv3, YOLOv3_tiny, decode
import core.utils as utils
import os
from core.config import cfg

flags.DEFINE_string('weights', './checkpoints/yolov4-416', 'path to weights file')
flags.DEFINE_string('output', './checkpoints/yolov4-416-fp32.tflite', 'path to output')
flags.DEFINE_integer('input_size', 416, 'path to output')
flags.DEFINE_string('quantize_mode', 'float32', 'quantize mode (int8, float16, float32)')
flags.DEFINE_string('dataset', "/Volumes/Elements/data/coco_dataset/coco/5k.txt", 'path to dataset')

def representative_data_gen():
  fimage = open(FLAGS.dataset).read().split()
  for input_value in range(10):
    if os.path.exists(fimage[input_value]):
      original_image=cv2.imread(fimage[input_value])
      original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
      image_data = utils.image_preprocess(np.copy(original_image), [FLAGS.input_size, FLAGS.input_size])
      img_in = image_data[np.newaxis, ...].astype(np.float32)
      print("calibration image {}".format(fimage[input_value]))
      yield [img_in]
    else:
      continue

def save_tflite():
  converter = tf.lite.TFLiteConverter.from_saved_model(FLAGS.weights)

  if FLAGS.quantize_mode == 'float16':
    converter.optimizations = [tf.lite.Optimize.DEFAULT]
    converter.target_spec.supported_types = [tf.compat.v1.lite.constants.FLOAT16]
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
    converter.allow_custom_ops = True
  elif FLAGS.quantize_mode == 'int8':
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
    converter.optimizations = [tf.lite.Optimize.DEFAULT]
    converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS]
    converter.allow_custom_ops = True
    converter.representative_dataset = representative_data_gen

  tflite_model = converter.convert()
  open(FLAGS.output, 'wb').write(tflite_model)

  logging.info("model saved to: {}".format(FLAGS.output))

def demo():
  interpreter = tf.lite.Interpreter(model_path=FLAGS.output)
  interpreter.allocate_tensors()
  logging.info('tflite model loaded')

  input_details = interpreter.get_input_details()
  print(input_details)
  output_details = interpreter.get_output_details()
  print(output_details)

  input_shape = input_details[0]['shape']

  input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)

  interpreter.set_tensor(input_details[0]['index'], input_data)
  interpreter.invoke()
  output_data = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]

  print(output_data)

def main(_argv):
  save_tflite()
  demo()

if __name__ == '__main__':
    try:
        app.run(main)
    except SystemExit:
        pass

I save this file in folder tensorflow-yolov4 tflite.

Can someone know how to solve this problem? I need you guys. Thank you

A: Add two lines before tflite_model = converter.convert() in save_tflite() function like this
converter.experimental_enable_resource_variables = True
converter.experimental_new_converter = True

tflite_model = converter.convert()


Q: onbackpressed make my app close without confirmation I'm new android developer, my app closes when I press back from any page in menu. I added this code with dialog but it is not working
@Override
public void onBackPressed() {
    super.onBackPressed();

    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();

    if(count == 0) {
        // Do you want to close app?
    }

}

A: Have you tried putting the super call in an else block so it is only called if the key is not KEYCODE_BACK ?
/* Prevent app from being killed on back */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // Back?
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Back
            moveTaskToBack(true);
            return true;
        }
        else {
            // Return
            return super.onKeyDown(keyCode, event);
        }
    }

That should work for now! Feel free to comment if you have any problems.

A: try this:
@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    int count = fm.getBackStackEntryCount();
    if(count == 0) {
       // Do you want to close app?
       showDialog();
    }
}

public void showDialog() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Do you want to close the app");
    alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
              finish();  //or super.onBackPressed();
        }
    });
    alert.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
    });
    alert.show();
}

A: Override activity's onBackPressed with the following in case you have for instance made changes in some values and forgot to update those afterwards, but in stead pressed the back button :
@Override
  public void onBackPressed() {
    if( <condition>) {
      AlertDialog.Builder ad = new AlertDialog.Builder( this);
      ad.setTitle("Changes were made. Do you want to exit without update?");
      ad.setPositiveButton(
              "OK",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  backPress();
                }
              }
      );
      ad.setNegativeButton(
              "Update the changes",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  <Update the changes>;
                  Toast.makeText(getApplicationContext(), "Changes were updated", Toast.LENGTH_SHORT).show();
                  backPress();
                }
              }
      );
      ad.setCancelable( false);
      ad.show();
    } else {
      backPress();
    }
  }

  private void backPress() {
    super.onBackPressed();
  }


Q: Cacti graph not showing properly Hoping to reach all of you Cacti experts right there. I have tried posting the same issue on the Cacti forums website, but after nearly a week had no answer. Hoping to have more luck here.
I'm pretty new to Cacti, and in the past days I've worked my way through to installation, configuration, etc.
I am now at a stage where I need to hook up the system I need to monitor (called Diffusion) into cacti. Diffusion is a java-based push engine, and my aim is to graph specific MBeans the server exposes.
I have created Perl scripts that give me the info I need in a correct fashion, and built a graph template to display data from 4 data sources pertaining a threadpool.
As of now the values are fixed, hence the outcome is always 0, 3, 8 and 10 (4 data sources, dumping on 4 rrds).
For some reason, though the only line I can see is the one returning 0, and the graph is sized between 0 and 1, wehreas I'd expect to see the other lines as well and the graph being sized between 0 and some value above 10.

Just to make it clear, logs (DEBUG level) do not show any warning, data gathering seems to work well, and I have no "complain" from cacti when creating sources, templates, etc.
Any help would be appreciated.
Thanks.

A: After a few attempts with changing a variety of parameters, I managed to solve the issue by simply changing the graph type to GAUGE.
Seems to wrk pretty well now.


Q: Jupiternote book on iPad / makrdown cells / how to drag a picture? I use JUNO connect to run cocalc on my iPad.
How can I get a picture in my picture file on the iPad into a markdown cell?
Thanks a lot for any help!


Q: In an IntelliJ Kotlin project, when I try to run a java class, I get a "Could not find or load main class" error I try to run the class from the green arrow in IntelliJ and I get the "Could not find or load main class"  error. If I try to run the class from the terminal by running
javac <filename.java>
java <filename>

it works. I tried to do "rebuild project" and to make a new project and it did not change anything.
Here is a photo of my project:

Here is a photo of my Run-Edit configurations

A: Your java code needs to be placed in src/main/java directory instead of src/main/kotlin.
Kotlin compiler doesn't compile Java files in Kotlin source roots, Java compiler doesn't compile Java files in Kotlin source roots, therefore .class files are not created by any of the compilers and you get this error.
The solution is to move *.java files into src/main/java directory. Create this directory manually if it doesn't exist.


Q: How to call a setter method in the Data Assignments I/O in a jbpm task? I have a process in jBPM. The process has a Human Task.
Also there are Data Objects: SrcData, CalcInter.
In the Human Task's Assignment Data I/O panel I need to read properties from the objects in Data Inputs section, and write a calculated variable in the property of CalcInter object in Data Outputs section (see picture).
Screenshot of Assignment Data I/O panel
Objects' properties reading in Data Inputs works as intended. As suggested here:
How to call a getter method in the Data Assignments I/O in a jbpm task?
But writing Object property in Data Outputs in such way doesn't work.
I've tried:
#{CalcInter.setAxx(axx)}
#{CalcInter.setAxx((int)axx)}
#{CalcInter.setAxx(#{axx})}

How to solve this? (And why is it so complicated?)

A: I've found that the issue can be solved by using MVEL notation instead of pure Java.
If in Data Outputs as a Target we use following expression:
#{CalcInter.axx}

The jBPM engine correctly updates the object property.
(How to use a Java style in the case and if it is possible — I still don't know.)


Q: what is the significance of " #!flask/bin/python " in flask? why this line #!flask/bin/python is added on the top of this code?
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, World!"

if __name__ == '__main__':
    app.run(debug=True)

I got following error when I removed it
from: can't read /var/mail/flask
./app.py: line 3: syntax error near unexpected token `('
./app.py: line 3: `app = Flask(__name__)'

A: #! is a shebang. On UNIX/UNIX like operating systems it basically tells your shell which executable (python in your case) to execute the script with. Without it, the shell is executing the script directly and since it does not understand Python code, it raises an error.


Q: Adding rows to tables of datasets? I created a data set within VS2012 and created some tables for it. But i am unable to fill the tables using C#.
This runs without errors:

Database1DataSet.LocationRow newLocationRow;
newLocationRow = database1DataSet.Location.NewLocationRow();
newLocationRow.LocationID = 1;
newLocationRow.LocationName = "Test";
newLocationRow.LocationInfo = "Test";
database1DataSet.Location.Rows.Add(newLocationRow); //<- i get an error here ONLY if i use a row with a incorrect foreign key.
this.tableAdapterManager.UpdateAll(database1DataSet);

When i insert a simple row into a table like this i cannot find it in the database explorer, it still shows a single row with NULL. Am i doing something wrong?


Q: Adjust decay rate dynamically Say I have a stream of values $\langle s_1, s_2,\ldots\rangle$ coming in and a function
$$E_{s_1:s_n}(t) = E_{s_1:s_{n-1}}(t-1) + \alpha\cdot (s_t-E_{s_1:s_{n-1}}(t-1))$$
that compute their exponential moving average as the values flow in.
I would like the alpha, i.e the decay rate, to adjust dynamically as a function of the last $h$ values we have seen. That is, if the trend is that the values are similar then I want my rate to plateau.
Otherwise, if the trend is that the values are decreasing quickly, I would like the decay rate to be greater and vice-versa.
Right now, I was thinking of defining:
$$\alpha(s_{k-h}, s_{k-h-1}, \ldots , s_k) = E_{\Delta_{k-h}:\Delta_k}(t-1) + \alpha_\Delta \cdot ((s_k - s_{k-1}) - E_{\Delta_{k-h}:\Delta_k}(t-1))$$
That is, the exponential moving average of the difference between two consecutive values of our time serie with an arbitrary alpha ($\alpha_\Delta$)
I am not a statistician, just a student that tries to play with mathematics. Help is greatly welcomed, including links to resources that could help me solve this problem in a better fashion. I am completely open to new ideas!


Q: Array.length seemingly not working; console.log shows otherwise I want to eventually write contactList to the page but even though console.log is showing that contactList is properly receiving contacts being pushed from localStorage, its length remains at 1! And when I do try to iterate over contactList to write to the page, it doesn't work as expected and I see undefined where values should be.
var contactList = [];
window.onload = init;
function init(){
    var data = window.localStorage.getItem("contacts");
    if(data){
        myData = JSON.parse(data);
        console.log("This is local storage:\n");
        console.log(myData);
        console.log("This is contact list before I push local storage:\n");
        console.log(contactList);
        contactList.push(myData);
        console.log("This is contact list after I push local storage:\n");
        console.log(contactList);
        var j = contactList.length;
        console.log("This is the length of contact list:\n");
        console.log(contactList.length);

    }
}

Here's an example of my console window:

This is local storage:
form.js (line 12)
[[[Object { firstname="hi",  lastname="hi",  number="hi"}], Object {
firstname="hi",  lastname="hi",  number="hi"}], Object{ firstname="hi",  lastname="hi",  number="hi"}]
form.js (line 13)
This is contact list before I push local storage:
form.js (line 14)
[]
form.js (line 15)
This is contact list after I push local storage:
form.js (line 17)
[[[[Object { firstname="hi",  lastname="hi",  number="hi"}], Object { firstname="hi",  lastname="hi",  number="hi"}], Object { firstname="hi",  > lastname="hi",  number="hi"}]]
form.js (line 18)
This is the length of contact list:
form.js (line 20)
1

A: That is the expected outcome with push. It looks like you want to use concat.
push will append whatever the argument is to a new element at the end of the array. If you add a string it will add the string. If you add an array it will add an array...as the last element. It will not flatten the resultant array. On the other hand concat will concat the two arrays and return a new array. The original array will be unchanged though.

A: var a = [1]

console.log(a.length) // 0

var b = [2]

var c = a.push(b)

console.log(c) // [1, [2]]

console.log(c.length) // 2

Try using concat():
var a = [1]

console.log(a.length) // 1

var b = [2]

var c = a.concat(b)

console.log(c) // [1, 2] <<< Desired behaviour

console.log(c.length) // 2


Q: [MySQL]Insert a value depending on a condition I'm studying MySQL so I'm a bit new to all this stuff, but the last time I asked you guys, you proved to be really helpful, so perhaps you can help me again because I haven't been able to find the answer on my own.
Ok, so the thing is, I need to add a new column to an already existing table, and it should be like:
ALTER TABLE `medicos`
ADD COLUMN `tipo_medico` VARCHAR(20) NOT NULL DEFAULT 'indiferente' AFTER `sueldo`;

Now I'm supposed to run an INSERT instruction to add the data there. After adding that column, the table looks like this:

These values equal to: Medic_number, Surnames, Speciality, Day of birth, University, Wage and Medic_type (the new column I've added). The data I add on all the columns except the last one doesn't really matter, but the last column must be filled following the next conditions:
-By default, it'll be "indiferente" (that's working).
-If a medic has studied in an university ending in -a (i.e. Valencia), it'll say "Excellent".
-If a medic is 40 years old or older, it'll say "Expert".
Now, I know how to do these conditions ("... university like = '%a'", etc), but I don't know how to add that into the INSERT instruction. This is what I've gotten so far:
insert into medicos values ('A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500');

That adds everything but the last column, which is the one where I'm lost. What can I do to tell the INSERT instruction to, depending on which of the previously named conditions are true, add one value or another?
I hope I've been clear enough, I'm not a native English speaker so I'm sorry if that wasn't good enough. Also I've tried to format the codes this time, I hope that'll work.
Thanks.

A: This seems to be a case when we need to apply a logic on column values before a record is inserted. I would suggest creating a BEFORE INSERT trigger on this table, which will be automatically executed by MySql before each record is inserted.
We can write the logic to determine the value of last column depending upon values supplied for the other columns. Have a look at this link for trigger example.
If the requirement here is to do a one time bulk insert then, we can drop this trigger once insertion is complete.

A: I would advise you to do it either with BEFORE INSERT trigger as Darshan Mehta recommends, or do your logic in the programming side, or with a stored procedure.
Still it is doable at query time, so to answer your question specifically, try something like this:
INSERT INTO medicos (num_colegiado, apellidos, especialidad, fecha_nac, universidad, sueldo, tipo_medico) SELECT 'A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500', IF('Loquesealogia' like '%a','Excellent',IF(DATE_ADD('1970-03-14', interval 40 YEAR)>NOW(),'Expert','indiferente'))


Q: Caling procedure in conversion.asm from main .asm I have two asm files, one is conversion.asm and one is main.asm, I am using conversion.asm in main.asm. I am using floating point stack but I am not getting the right output.
main.asm
Include conversion.asm

.386
.stack 4096

ExitProcess PROTO, dwExitCode:DWORD

.data
Cel DD 25
Faren DD ?

.code
main PROC
  push dword ptr Cel
  fld dword ptr [esp]

  call C2F

  fstp dword ptr [Faren]
  mov ebx, [Faren]
  INVOKE ExitProcess, ebx
main ENDP
END main

conversion.asm

.model flat, stdcall

ExitProcess PROTO, dwExitCode:DWORD
.stack 4096

.data
Cfirst DD 2
Csecond DD 1
common DD 32

C2F PROC
    push dword ptr Cfirst
    fld dword ptr [esp]
    add esp,4
    fmulp
    sub esp,4
    push dword ptr Csecond
    fld dword ptr [esp]
    add esp,4
    fdivp
    sub esp,4
    push dword ptr common
    fld dword ptr [esp]
    add esp,4
    faddp
    sub esp,4
    RET
C2F ENDP

Please help me out

A: fmul, fdiv, fadd edit data in floating stack directly, so instead of pulling from stack to register, do operation directly in floating stack.
Correct usage of floating point stack in conversion.asm:
.DATA
five DWORD 5.0
nine DWORD 9.0
ttw DWORD 32.0

.CODE
C2F proc
    fmul nine
    fdiv five
    fadd ttw
    ret
C2F ENDP

For reading float and writing float I used Irvine library, which uses floating point stack:
Include Irvine32.inc
Include conversion.asm

.data
Celprompt BYTE "Enter a value in C:",0
Cel DWORD 0
Resprompt BYTE "In Farenheit that value is - "
Faren DD ?

.code
main PROC
  mov edx, OFFSET Celprompt
  call WriteString
  call Crlf
  call ReadFloat
  call C2F
  call Crlf
  mov edx, OFFSET Resprompt
  call WriteString
  call WriteFloat
main ENDP
END main


Q: Copy tables form schema in another schema in Oracle I want to write a procedure or a cursor.
Input data  -- NAME OWNER.
We know name  (OWNER) AND from table  ALL_OBJECTS
Take the name of the table.
Tables > 30.
How to write correctly ?

CREATE OR REPLACE PROCEDURE USER_NAME
(

  v_USER VARCHAR2
)
AS
  v_sysdate VARCHAR2(10) := to_char(SYSDATE ,'MMDDYYYY');
  v_table_name VARCHAR2(50);

BEGIN

  SELECT
  TABLE_NAME INTO v_table_name
  FROM
    ALL_OBJECTS F   -- Table with two columnsю. OWNER AND NAME TABLES
  WHERE
    F.OWNER  = v_USER;

   --Name of tables and owner ALL_OBJECTS

EXECUTE IMMEDIATE 'CREATE TABLE USER_BANCU.'||v_USER||'_'||v_table_name||'__'||v_sysdate||to_char(sysdate,'HH24_MI_SS')||'    AS
             SELECT *
             FROM '||v_USER||'.'||v_table_nam;
COMMIT;
END;
/

A: Try DBMS_METADATA_GET_DDL.
enter link description here


Q: Uninstall / remove a Homebrew package including all its dependencies I have a Homebrew formula that I wish to uninstall/remove along with all its dependencies, skipping packages whom other packages depend upon (a.k.a. Cascading package removal in Package manager parlance).
e.g. Uninstall package a which depends on packages b & c, where package d also depends on package c. The result should uninstall both a & b, skipping c.
How can I do that?
There must be a way to uninstall a package without leaving unnecessary junk behind.

A: EDIT:
It looks like the issue is now solved using an external command called brew rmdeps or brew rmtree.
To install and use, issue the following commands:
$ brew tap beeftornado/rmtree
$ brew rmtree <package>

See the above link for more information and discussion.

[EDIT] see the new command brew autoremove in https://stackoverflow.com/a/66719581/160968

Original answer:
It appears that currently, there's no easy way to accomplish this.
However, I filed an issue on Homebrew's GitHub page, and somebody suggested a temporary solution until they add an exclusive command to solve this.
There's an external command called brew leaves which prints all packages that are not dependencies of other packages.
If you do a logical and on the output of brew leaves and brew deps <package>, you might just get a list of the orphaned dependency packages, which you can uninstall manually afterwards. Combine this with xargs and you'll get what you need, I guess (untested, don't count on this).

EDIT: Somebody just suggested a very similar solution, using join instead of xargs:
brew rm FORMULA
brew rm $(join <(brew leaves) <(brew deps FORMULA))

See the comment on the issue mentioned above for more info.

A: brew rmtree doesn't work at all. From the links on that issue I found rmrec which actually does work. God knows why brew doesn't have this as a native command.
brew tap ggpeti/rmrec
brew rmrec pkgname

A: You can just use a UNIX pipe for this
brew deps [FORMULA] | xargs brew rm

A: A More-Complete Bourne Shell Function
There are a number of good answers already, but some are out of date and none of them are entirely complete. In particular, most of them will remove dependencies but still leave it up to you to remove the originally-targeted formula afterwards. The posted one-liners can also be tedious to work with if you want to uninstall more than one formula at a time.
Here is a Bourne-compatible shell function (without any known Bashisms) that takes a list of formulae, removes each one's dependencies, removes all copies of the formula itself, and then reinstalls any missing dependencies.
unbrew () {
    local formula
    for formula in "$@"; do
        brew deps "$formula" |
        xargs brew uninstall --ignore-dependencies --force
        brew uninstall --force "$formula"
    done
    brew missing | cut -f2 -d: | sort -u | xargs brew install
}

It was tested on Homebrew 1.7.4.
Caveats
This works on all standard formulae that I tested. It does not presently handle casks, but neither will it complain loudly if you attempt to unbrew a cask with the same name as a standard formula (e.g. MacVim).

A: The goal here is to remove the given package and its dependencies without breaking another package's dependencies. I use this command:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | xargs brew install

Note: Edited to reflect @alphadogg's helpful comment.

A: Other answers didn't work for me, but this did (in fish shell):
brew remove <package>
for p in (brew deps <package>)
    brew remove $p
end

Because brew remove $p fails when some other package depends on p.

A: By the end of 2020, the Homebrew team added a simple command brew autoremove to remove all unused dependencies.
First, uninstall the package:
brew uninstall <package>
Then, remove all the unused dependencies:
brew autoremove

A: Based on @jfmercer answer (corrections needed more than a comment).
Remove package's dependencies (does not remove package):
brew deps [FORMULA] | xargs brew remove --ignore-dependencies

Remove package:
brew remove [FORMULA]

Reinstall missing libraries:
brew missing | cut -d: -f2 | sort | uniq | xargs brew install

Tested uninstalling meld after discovering MeldMerge releases.

A: Using this answer requires that you create and maintain a file that contains the package names you want installed on your system.  If you don't have one already, use the following command and delete the package names what you don't want to keep installed.
brew leaves > brew_packages

Then you can remove all installed, but unwanted packages and any unnecessary dependencies by running the following command
brew_clean brew_packages

brew_clean is available here: https://gist.github.com/cskeeters/10ff1295bca93808213d
This script gets all of the packages you specified in brew_packages and all of their dependancies and compares them against the output of brew list and finally removes the unwanted packages after verifying this list with the user.
At this point if you want to remove package a, you simply remove it from the brew_packages file then re-run brew_clean brew_packages.  It will remove b, but not c.

A: Save the following script as brew-purge
#!/bin/bash
#:Usage: brew purge formula
#:
#:Removes the package and all dependancies.
#:
#:
PKG="$1"
if [ -z "$PKG" ];then
   brew purge --help
   exit 1
fi
brew rm $PKG
[ $? -ne 0 ] && exit 1
while brew rm $(join <(brew leaves) <(brew deps $PKG)) 2>/dev/null
  do :
done
echo Package $PKG and its dependancies have been removed.
exit 0

Now install it with the following command
sudo install brew-purge /usr/local/bin

Now run it
brew purge package

Example using gpg
$ brew purge gpg
Uninstalling /usr/local/Cellar/gnupg/2.2.13... (134 files, 11.0MB)
Uninstalling /usr/local/Cellar/adns/1.5.1... (14 files, 597.5KB)
Uninstalling /usr/local/Cellar/gnutls/3.6.6... (1,200 files, 8.9MB)
Uninstalling /usr/local/Cellar/libgcrypt/1.8.4... (21 files, 2.6MB)
Uninstalling /usr/local/Cellar/libksba/1.3.5... (14 files, 344.2KB)
Uninstalling /usr/local/Cellar/libusb/1.0.22... (29 files, 508KB)
Uninstalling /usr/local/Cellar/npth/1.6... (11 files, 71.7KB)
Uninstalling /usr/local/Cellar/pinentry/1.1.0_1... (12 files, 263.9KB)
Uninstalling /usr/local/Cellar/libassuan/2.5.3... (16 files, 444.2KB)
Uninstalling /usr/local/Cellar/libtasn1/4.13... (59 files, 436KB)
Uninstalling /usr/local/Cellar/libunistring/0.9.10... (54 files, 4.4MB)
Uninstalling /usr/local/Cellar/nettle/3.4.1... (85 files, 2MB)
Uninstalling /usr/local/Cellar/p11-kit/0.23.15... (63 files, 2.9MB)
Uninstalling /usr/local/Cellar/gmp/6.1.2_2... (18 files, 3.1MB)
Uninstalling /usr/local/Cellar/libffi/3.2.1... (16 files, 296.8KB)
Uninstalling /usr/local/Cellar/libgpg-error/1.35... (27 files, 854.8KB)
Package gpg and its dependancies have been removed.
$

A: The answer of @jfmercer must be modified slightly to work with current brew, because the output of brew missing has changed:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | cut -f1 -d: | xargs brew install

A: Slightly refined; can supply multiple packages; has usage when none supplied.
#!/bin/bash
# Removes the package and all dependancies.

if [ $# -eq 0 ]; then
   echo "$(basename $0) <pkg> [<pkg> [...]]"
   exit 1
fi

function tree() {
    pkg="$1"
    join <(brew leaves) <(sort <(brew deps ${pkg}; echo ${pkg}))
}

let e=0
for pkg in "$@"; do
    printf "Purging %s and its dependencies...\n" "${pkg}"
    deps=( $(tree ${pkg}) )
    while (( ${#deps[@]} > 0 )); do
        brew rm "${deps[@]}"
        deps=( $(tree ${pkg}) )
    done
done


Q: Waking up thread from signal handler I understand that about the only thing, a signal handler in ISO/C++11 is allowed to do is to read from or write to a lock free atomic variable or a volatile sig_atomic_t (I believe, POSIX is a little bit more permissive and allows to call a bunch of system functions).
I was wondering, if there is any way, to wake up a thread that is waiting on a condition variable. I.e. something like:
#include <mutex>
#include <atomic>
#include <condition_variable>

std::mutex mux;
std::condition_variable cv;

std::atomic_bool doWait{ true };

void signalHandler(int){
    doWait = false;
    cv.notify_one();
}

int main() {
    //register signal handler
    //Do some stuff

    {//wait until signal arrived
        std::unique_lock<std::mutex> ul(mux);
        cv.wait(ul, []{return !doWait; });
    }

    //Do some more stuff
}

Which has at least two problems:

*

*I believe, I'm not allowed to call notify_one() in a signal handler (corrct me if I'm wrong)

*The signal could arrive just between the check for doWait and when the thread goes to sleep, so it would never wake up (obviously, I can't lock the mutex in the signalHander to avoid that).

So far, the only solution I can see is to implement busy waiting on the doWait variable (probably sleep for a couple of milliseconds in each iteration), which strikes me as quite inefficient.
Note that even though, my program above has only one thread, I labeled my question with multithreading, because it is about thread control primitives. If there is no solution in standard c++ I'd be willing to accept a solution using Linux/POSIX specific functions.

A: Assuming that your vendor's standard library uses the pthread_cond_* functions to implement C++11 condition variables (libstdc++ and libc++ do this), the pthread_cond_* functions are not async-signal-safe so cannot be invoked from a signal handler.
From http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_broadcast.html:

It is not safe to use the pthread_cond_signal() function in a signal handler that is invoked asynchronously. Even if it were safe, there would still be a race between the test of the Boolean pthread_cond_wait() that could not be efficiently eliminated.
Mutexes and condition variables are thus not suitable for releasing a waiting thread by signaling from code running in a signal handler.

If you're comfortable using semaphores, sem_post is designated async-signal-safe. Otherwise, your options for signal handling are the usual ones: the classic self-pipe, a signal handling thread blocked on sigwait/sigwaitinfo, or platform-specific facilities (Linux signalfd, etc.).


Q: What is causing my Windows 10 computer to crash? On January this year I built a new computer for coding and gaming with the following hardware:

*

*Asus - X99-DELUXE II ATX LGA2011-3 Motherboard

*4x G.Skill - Ripjaws 4 series 32GB (4 x 8GB) DDR4-3000 Memory

*Intel - 750 Series 1.2TB PCI-E Solid State Drive

*EVGA - GeForce GTX 1080 8GB FTW Hybrid Gaming Video Card

The system was never stable. I'm experiencing a blue screen of death about every other week and sometimes it fails to boot with q-code 61, which stands for NVRAM Initializing.
I talked to Asus who told me the motherboard was defective because the MemOK! button was not doing something (although the behavior of card matched the manual and not the tech support person). I returned the X99-DELUXE II and got an Asus X99E WS hopping for workstation quality. This is my main working tool after all.
Lo and behold, the problem persisted. Since I had enough RAM, I removed half of it and I've been rotating it to try to identify a bad DIMM, but so far, I cannot really attribute the crashes to a particular one.
The computer was re-installed at some point and I was very careful what drivers I was putting on it. This made no difference.
These are the last 5 crashes:

and this is the q-code log of a stuck boot (it happens sometimes):
Power ON
0000:34
0002:57
0003:34
0006:01
0004:48
0C14:01
0C11:0E
0C17:18
0C18:06
0C21:01
0C23:01
0C28:0F
0C29:02
0C25:FF
0C26:BB
0C2A:2D
0C2B:01
0CE0:15
0C41:63
0C19:FF
0CA1:01
0CA7:02
0CA9:01
0CAA:01
0CAF:01
0C2F:67
0CBF:01
0CB0:FF
0CB1:15
0CAF:--
RESET
0000:FF
0002:51
0003:34
0006:01
0004:47
0C14:01
0C11:0E
0C17:19
0C18:06
0C21:01
0C27:01
0C28:0E
0CFF:01
0C29:02
0C25:FF
0C26:B8
0C2A:2D
0C2B:01
0CEB:01
0CE0:0D
0C41:62
0C19:FF
0CA1:01
0CA3:01
0CA7:01
0CA9:03
0CA7:01
0CA9:01
0CAA:01
0CAF:02
0C2F:69
0CB0:FF
0CB1:9F
0CB4:02
0CB2:01
0CB3:1D
0CB6:96
0CB7:03
0CBE:01
0CB7:05
0CBA:01
0CB7:01
0CBB:02
0CBC:01
0CBF:1B
0CAF:--
RESET
0000:FF
0002:51
0003:34
0006:01
0004:46
0C14:01
0011:01
0C11:01
0011:01
0C11:07
0C13:01
0C17:16
0C18:05
0C23:01
0C28:0D
0C29:02
0C25:FF
0C26:BC
0C2A:2D
0CEB:01
0CE0:10
0C40:01
0C41:60
0C19:FF
0CA1:01
0CA7:01
0CA9:01
0CA7:01
0CAA:01
0CAF:01
0C2F:67
0CB0:FF
0CB1:9D
0CB4:02
0CB3:1C
0CB6:95
0CB7:08
0CBA:01
0CB7:01
0CBB:01
0CBF:FF
0C3F:01
0C33:FF
0C32:FF
0C4F:FF
0C6F:01
0C60:FF
0C61:FF
0C9A:3D
0C0A:01
0C03:FF
0C78:ED
0CB6:FF
0C68:FF
0C78:01
0C70:FF
0C79:FF
0C90:04
0C91:FF
0C94:24
0C95:FF
0C96:FF
0C97:04
0CB2:FF
0C98:02
0C9C:FF
0CBC:01
0CB4:1D
0C94:01
0C9C:02
0CB4:13
0C9C:01
0C99:FF
0CB9:01
0CB4:FF
0C94:01
0C99:B1
0CA9:01
0CA2:FF
0CA0:01
0CA2:FF
0CA0:FF
0CAD:FF
0CFB:FF
0C92:0E
0CA0:A0
0CA2:FF
0C99:01
0CA9:01
0CA0:BA
0CA2:FF
0C99:02
0CA0:FF
0CB1:--
Power OFF
DUMP Finish

Any ideas what's going?
Sadly, I don't have hardware laying around to start swapping out parts willy-nilly, but if I have a strong enough reason to swap some part, I'll get a new one and send back the old one for a refund (I cannot afford the downtime). I think the only major parts that I haven't swapped yet are:

*

*Intel - 750 Series 1.2TB PCI-E Solid State Drive

*EVGA - GeForce GTX 1080 8GB FTW Hybrid Gaming Video Card

They are not cheap to play around with.


Q: How can I convert a .jpg or .png image to .raw format? Is there any software that converts JPEG or PNG to RAW?
I have been looking around and I've only found applications that do the reverse.

A: I just find out here how to do that with Gimp !
Works almoust perfectly ! :P
Update
Used method:

*

*Export the file on Gimp: Ctrl Shift E

*On the export window, choose Raw Image Data on Select File Type

*

*Click on Export button

*On the raw image export window, Choose Planar for the RGB Save Type

*

*Click on Export button

*Open the folder where the file was saved and rename his extension from .data to .raw

*On Unity3d, chose Bit 8 for Depth on the Import Heightmap window

Unfortunately, the generated image by Gimp isn't that good... So, I'm still would appreciate some help.

A: Ubuntu by default has Imagemagick installed and provides the convert command line tool to convert to various image formats. You can simply do:
convert xyx.jpg xyz.RAW

A: Answer above may work for old versions of ImageMagick, but this worked for me:
convert lena512.bmp gray:lena512.raw

and vice versa
convert -size 512x512 -depth 8 gray:lena512.raw lena512.png

For many images this works (I haven't found solution for mogrify):
parallel -j 4 convert {} gray:{}.raw ::: slice-*.png

-j is number of processes, {} gets replaced by the filename matching the mask specified after ::: so output files are named as slice-0000.png.raw


Q: Eliminar texto entre simbolos  Tengo una variable de texto que contiene expresiones entre <>. Me gustaría eliminar todas esas expresiones entre flechas <>.
He intentado el siguiente código, pero me elimina más texto que solo las expresiones entre <>:
library(stringr)
df_new$variable_text <- str_replace(df_new$variable_text, "\\<.*\\>", "")

Un ejemplo es que tengo los siguientes textos como observaciones:

Fragmentarium has already established...

The proposed empirical strategy

Y me gustaría eliminar

Muchas gracias


Q: Website layout is broken,  is empty and I can't access wp-admin (wp-login) My site's https://www.beckers-trier.de layout and code is sort of broken. I don't code, but the theme is self-developed and I also don't remember changing anything about the site, except for adding the facebook pixel code in the . The Problem is that a few errors are given, which you can see in the wp-login site of my site. I can't login either, being warned that the cookie settings are closed because of a 'surprising output'

A: The error itself is quite self-explainatory, the server is trying to send some headers but some output has already started.
The warnings at start of the page are very likely to be generated from the PHP interpreter on your machine, either you have a weird display_errors directive in your php.ini or the constant WP_DEBUG on your wp-config.php is set to true.
Double check both configuration files and make sure the display of the errors are set to off and WP_DEBUG to false.


Q: Python return value prints only one value from the object instead of all the values I have a Python file with two class A and B, and I am inheriting temp from class A to B. In my class A function temp, I am getting the id value from an XML file which has values like this,
[1,2,3,4,5]

My Class A with temp function
class A:
        def temp(self):
        id = []
        for child in root:
            temp_id=child.get('id')
            id.append(temp_id)
        return id

and I am getting the function value in class B,
class B (A):
           fun=A
           value = fun.temp()
           for x in value:
             return x

While printing the return value instead of printing all the values, I am getting only the first value
[1,1,1,1,1]

Can some one please let me know on how to solve this, thanks.

A: Standard functions can only return a single value. After that, execution continues from where that function was called. So, you're trying to loop through all the values, but return upon seeing the first value, then the function exits and the loop is broken.
In your case, you could simply return fun.temp(). Or, if you want to process each value, then return the new list, you could run something like:
new_list = []
value = fun.temp()
for x in value:
   # do something with x here
   new_list.append(x)
return new_list

Also, it appears you may be a bit confused about how inheritance works. DigitalOcean has a  great article on it, if you want to take a look.


Q: Is there an easy way to show this matrix is totally unimodular? Consider $2n\times n^2$ matrix
$$J=\begin{bmatrix}
C_{11}&C_{12}&\dots&C_{1n}\\
C_{21}&C_{22}&\dots&C_{2n}\\
\vdots\\
C_{n1}&C_{n2}&\dots&C_{nn}\\
D_{11}&D_{12}&\dots&D_{1n}\\
D_{21}&D_{22}&\dots&D_{2n}\\
\vdots\\
D_{n1}&D_{n2}&\dots&D_{nn}\\
\end{bmatrix}$$
where each $C_{ij}$ and $D_{ij}$ is $1\times n$ submatrix.
$C_{ij}$ contains all $1$s iff $i=j$ else contains all $0$s.
$D$s form repetitions of $n\times n$ identity matrix.
Consider matrix of form $$\begin{bmatrix}J\\I_{n^2}\end{bmatrix}$$ where $I_{n^2}$ is identity of $n^2\times n^2$ size.
For example if $n=4$ we have
$$\begin{bmatrix}
1&1&1&1&0&0&0&0&0&0&0&0&0&0&0&0\\
0&0&0&0&1&1&1&1&0&0&0&0&0&0&0&0\\
0&0&0&0&0&0&0&0&1&1&1&1&0&0&0&0\\
0&0&0&0&0&0&0&0&0&0&0&0&1&1&1&1\\
1&0&0&0&1&0&0&0&1&0&0&0&1&0&0&0\\
0&1&0&0&0&1&0&0&0&1&0&0&0&1&0&0\\
0&0&1&0&0&0&1&0&0&0&1&0&0&0&1&0\\
0&0&0&1&0&0&0&1&0&0&0&1&0&0&0&1\\
1&0&0&0&0&0&0&0&0&0&0&0&0&0&0&0\\
0&1&0&0&0&0&0&0&0&0&0&0&0&0&0&0\\
0&0&1&0&0&0&0&0&0&0&0&0&0&0&0&0\\
0&0&0&1&0&0&0&0&0&0&0&0&0&0&0&0\\
0&0&0&0&1&0&0&0&0&0&0&0&0&0&0&0\\
0&0&0&0&0&1&0&0&0&0&0&0&0&0&0&0\\
0&0&0&0&0&0&1&0&0&0&0&0&0&0&0&0\\
0&0&0&0&0&0&0&1&0&0&0&0&0&0&0&0\\
0&0&0&0&0&0&0&0&1&0&0&0&0&0&0&0\\
0&0&0&0&0&0&0&0&0&1&0&0&0&0&0&0\\
0&0&0&0&0&0&0&0&0&0&1&0&0&0&0&0\\
0&0&0&0&0&0&0&0&0&0&0&1&0&0&0&0\\
0&0&0&0&0&0&0&0&0&0&0&0&1&0&0&0\\
0&0&0&0&0&0&0&0&0&0&0&0&0&1&0&0\\
0&0&0&0&0&0&0&0&0&0&0&0&0&0&1&0\\
0&0&0&0&0&0&0&0&0&0&0&0&0&0&0&1\\
\end{bmatrix}$$
How does one show this type of matrix is always totally unimodular?


Q: Cost Query with having and > I have the next query :
select code
  from user
  group by code
  having
    sum(case when name= 'A' then 1 end) >
    sum(case when name= 'A' then 1 end)

If i check the cost of the query it says it's 180, but if I use '=' instead of >, the cost is 1 , so does anyone have any idea why this is happening? why it's only using the index with '=' and not with '<'

A: Is this a real query? I'm asking because the query is invalid - having clause is equal to writing 1 > 1, so always False... And if you replace '>' with '=' the query is always true unless the result from sum() is NULL...


Q: How to change the id format of field in a model? For example I have a field of customer IDs going from
1, 2, 3, 4, 5, ...

However I want to change the format to
010101, 010102, 010103, 010104, 010105, ...

As it display on my database and templates.
Is there any way of doing that?
I am using PostgreSQL version 12 and pgadmin 4.
I have been using of the below on the query editor

SELECT concat('0101', lpad(id, 2, '0')) from public.accounts_customer

However receiving the error below
ERROR:  function lpad(integer, integer, unknown) does not exist
LINE 1: SELECT concat('0101', lpad(id, 2, '0')) from public.accounts...
                              ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
SQL state: 42883
Character: 23

A: You can' t add  leading 0 to an integer and store  in db  you can manage only the selecting result  .. eg
 select concat('0101', lpad(yourcol,2,'0'))
 from your_table

or try force the cast
 select concat('0101', lpad(yourcol,2,'0'::text))
 from your_table


Q: Automate 1GP Managed Package Uninstallation (Remove dependencies via Apex Script or anything) Good day all!
I've a 1GP Managed package installed in my org. So, naturally, I'm using several components from the package in my org. However, whenever I want to uninstall it(scenarios where I must uninstall) every time, there are many dependencies. I've to do some manual steps to remove the dependencies. Those are mentioned below:

*

*Page Layout: I must manually unassign package ones to remove dependencies.

*Approval Process: Need to remove email templates.

*Flow: Need to deactivate.

*Process builder: Need to deactivate.

So, it's time-consuming! What I intend to do is write an Apex Script and run it. The script will remove all the dependencies so I can uninstall it in seconds.
My question is, is there anything like this?

*

*I've recently learned about the Apex Metadata API, but I'm not sure if it applies to my scenario.

*Also, I'm wondering if it's possible to deploy Metadata from VSCode to manage the layout or other assignments.

Thank you!


Q: What does "self-describing" in reference to Web Services really mean? I've heard a lot of buzz through the years about "Self Describing" web services and I'm curious what it means. I've flipped through the W3C standard and it doesn't really help.
I understand you can say "Give me this argument and call this functionality and I'll return something like this", but how is that actually helpful? How can software know what is relevant to a client given some context?
Can anyone give real world examples of this concept, and explain how it's better than some other alternative? Or maybe how useful/useless it is?

A: It's really designed as a standard for describing in a cross-platform cross-language manner an interface that a developer can use to develop a SOAP based way to exchange information with a web service.
Another alternative would be providing a library that provides a local interface to a blackbox communcation scheme, which is fraught with compatability/security issues.
Or providing documentation, which may be difficult to find, have compatibility issues, be out of date, or incomplete.
In short, it's very useful.


Q: Wrap figure changes right spacing I'm using moderncv and I'd like to add a note at the end of last page.
I added it using \vspace but somehow this sentence has huge right spacing, as you can see from the picture here.
In my document I also have a logo, and after some tries I realized that it is because of this wrap figure that I have the issue. Removing the picture the note at the bottom of the page has normal spacing. It is quite weird because only that sentence is influenced and not the test of the text.
How can I fix this? Here there are the output example and a MWE
Output example:

MWE:
\documentclass[11pt,a4paper,sans]{moderncv}
\moderncvstyle{casual}
\moderncvcolor{blue}

\usepackage{wrapfig}
\usepackage{lipsum}
\usepackage{graphicx}

\usepackage[scale=0.75]{geometry} % Reduce document margins
%\setlength{\hintscolumnwidth}{3cm} % Uncomment to change the width of the dates column
%\setlength{\makecvtitlenamewidth}{10cm} % For the 'classic' style, uncomment to adjust the width of the space allocated to your name

%----------------------------------------------------------------------------------------
%   NAME AND CONTACT INFORMATION SECTION
%----------------------------------------------------------------------------------------

\firstname{John} % Your first name
\familyname{Smith} % Your last name

% All information in this block is optional, comment out any lines you don't need
\title{Curriculum Vitae}
\address{123 Broadway}{City, State 12345}
\mobile{(000) 111 1111}
\fax{(000) 111 1113}
\email{john@smith.com}
\extrainfo{additional information}
\quote{"A witty and playful quotation" - John Smith}

%----------------------------------------------------------------------------------------
\begin{document}
\makecvtitle % Print the CV title

%% LOGO  ---------------------------------------------------------
\begin{wrapfigure}{R}{0.20\textwidth}
    \vspace{-70pt}
    \begin{center}
    \textit{This is my special logo}
        \includegraphics[width=0.20\textwidth]{pictures/logo}
    \textit{my logo}
    \end{center}
\end{wrapfigure}
%% ------------------------------------------------------------------

\section{Contact Information}

\cvitem{Mobile 1}{012 345 6789}
\cvitem{Mobile 1}{012 345 6789}
\cvitem{E-mail}{email@email.com}

\section{Education}

\cventry{2011--2012}{Masters of Commerce}{The University of California}{Berkeley}{\textit{GPA -- 8.0}}{First Class Honours}  % Arguments not required can be left empty
\cventry{2007--2010}{Bachelor of Business Studies}{The University of California}{Berkeley}{\textit{GPA -- 7.5}}{Specialized in Commerce}

\section{Masters Thesis}

\cvitem{Title}{\emph{Money Is The Root Of All Evil -- Or Is It?}}
\cvitem{Supervisors}{Professor James Smith \& Associate Professor Jane Smith}
\cvitem{Description}{This thesis explored the idea that money has been the cause of untold anguish and suffering in the world. I found that it has, in fact, not.}

\section{Custom}
\cvitem{AA}{Lorem ipsum dolor sit amet, consectetur adipiscing elit eleifend feugiat mauris}
\cvitem{BB}{Lorem ipsum dolor sit amet, consectetur adipiscing elit eleifend feugiat mauris}

%----------------------------------------------------------------------------------------
%   CLOSING SENTENCE
%----------------------------------------------------------------------------------------
\vspace{\stretch{1}}\textit{Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras fringilla ligula sit amet est dignissim commodo. Integer eleifend feugiat mauris et congue. Aenean eget sem leo.}
\begin{flushright}
\textit{Last update: Feb 2016}
\end{flushright}

\end{document}

A: Solved using \centering instead of begin{center} and end{center} and adding \vspace{-82pt} before \end{wrapfigure}.
If you have a better solution, please post it.


Q: Is PGSQL not executing my index because of the ORDER BY clause? I have a rails query that looks like this:
Person.limit(10).unclaimed_people({})

def unclaimed_people(opts)
  sub_query = where.not(name_id: nil)
  if opts[:q].present?
    query_with_email_or_name(sub_query, opts)
  else
    sub_query.group([:name_id, :effective_name])
             .reorder('MIN(COALESCE(kudo_position,999999999)), lower(effective_name)')
             .select(:name_id)
  end
end

Translating to SQL, the query looks like this:
SELECT  "people"."name_id" FROM "people"
  WHERE ("people"."name_id" IS NOT NULL)
GROUP BY "people"."name_id", "people"."effective_name"
  ORDER BY MIN(COALESCE(kudo_position,999999999)), lower(effective_name) LIMIT 10

Now when I run an EXPLAIN on the SQL query, what's returned shows that I am not running an index scan. Here is the EXPLAIN:
     QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=728151.18..728151.21 rows=10 width=53) (actual time=6333.027..6333.028 rows=10 loops=1)
   ->  Sort  (cost=728151.18..729171.83 rows=408258 width=53) (actual time=6333.024..6333.024 rows=10 loops=1)
         Sort Key: (min(COALESCE(kudo_position, 999999999))), (lower(effective_name))
         Sort Method: top-N heapsort  Memory: 25kB
         ->  GroupAggregate  (cost=676646.88..719328.87 rows=408258 width=53) (actual time=4077.902..6169.151 rows=946982 loops=1)
               Group Key: name_id, effective_name
               ->  Sort  (cost=676646.88..686041.57 rows=3757877 width=21) (actual time=4077.846..5106.606 rows=3765261 loops=1)
                     Sort Key: name_id, effective_name
                     Sort Method: external merge  Disk: 107808kB
                     ->  Seq Scan on people  (cost=0.00..112125.78 rows=3757877 width=21) (actual time=0.035..939.682 rows=3765261 loops=1)
                           Filter: (name_id IS NOT NULL)
                           Rows Removed by Filter: 317644
 Planning time: 0.130 ms
 Execution time: 6346.994 ms

Pay attention to the bottom part of the query plan. There is a Seq Scan on people. This is not what I was expecting, in my development and production database, I have placed an index on the foreign name_id field. Here is the proof from the people table.
"index_people_name_id" btree (name_id) WHERE name_id IS NOT NULL

So my question is why would it not be running the index. Could it perhaps be from the ORDER BY clause. I read that it could affect the execution of an index. This is the web page where I read it from. Why isn't my index being used?
In particular here is the quote from the page.

Indexes are normally not used for ORDER BY or to perform joins. A sequential scan followed by an explicit sort is usually faster than an index scan of a large table. However, LIMIT combined with ORDER BY often will use an index because only a small portion of the table is returned.

As you can see from the query, I am using ORDER BY combined with LIMIT so I would expect the index to be used. Could this be outdated? Is the ORDER BY really affecting the query? What am I missing to get the index to work? I'm not particularly versed with the internals of PGSQL so any help would be appreciated.