text:
Q: What's is better for a members database? Hi and thanx for reading my post i am having a little trouble learning my  database in mysql.
Now i have it set up already but recently, but i had another person tell me my members table is slow and useless if i intend to have a lots of members!
I have looked it over a lot of times and did some google searches but i don't see anything wrong with it, maybe because i am new at it? can one of you sql experts look it over and tell me whats wrong with it please :)
--
-- Table structure for table `members`
--

CREATE TABLE IF NOT EXISTS `members` (
  `userid` int(9) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL DEFAULT '',
  `password` longtext,
  `email` varchar(80) NOT NULL DEFAULT '',
  `gender` int(1) NOT NULL DEFAULT '0',
  `ipaddress` varchar(80) NOT NULL DEFAULT '',
  `joinedon` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `acctype` int(1) NOT NULL DEFAULT '0',
  `acclevel` int(1) NOT NULL DEFAULT '0',
  `birthdate` date DEFAULT NULL,
  `warnings` int(1) NOT NULL DEFAULT '0',
  `banned` int(1) NOT NULL DEFAULT '0',
  `enabled` int(1) NOT NULL DEFAULT '0',
  `online` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`userid`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `emailadd` (`emailadd`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

--
-- Dumping data for table `members`
--

It's going to be a site for faqs/tips for games, i do expect to get lots of members at one point later on but i thought i would ask to make sure it's all ok, thanx again peace.

A: Did the other person explain why they think it is slow and useless?
Here's a few things that I think could be improved:
email should be longer - off the top of my head, 320 should be long enough for most email addresses, but you might want to look that up.
If the int(1) fields are simple on/off fields, then they could be tinyint(1) or bool instead.
As @cularis points out, the ipaddress field might not be the appropriate type.  INT UNSIGNED is better than varchar for IPv4.  You can use INET_ATON() and INET_NTOA() for conversion. See:
Best Field Type for IP address?
How to store IPv6-compatible address in a relational database
As @Delan Azabani points out, your password field is too long for the value you are storing.  MD5 produces a 32 character string, so varchar(32) will be sufficient.  You could switch to the more secure SHA2, and use the MySQL 'SHA2()' function.
Look into using the InnoDB database engine instead of MyISAM.  It offers foreign key constraints, row-level locking and transactions, amongst other things.  See Should you move from MyISAM to Innodb ?.

A: I don't think it's necessarily slow, but I did notice that among all other text fields where you used varchar, you used longtext for the password field. This seems like you are going to store the password in the database -- don't do this!
Always take a fixed-length cryptographic hash (using, for example, SHA-1 or SHA-2) of the user's password, and put that into the database. That way, if your database server is compromised, the users' passwords are not exposed.

A: Apart from what @Delan said, I noted that;

*

*JoinedOn column defined as ON UPDATE CURRENT_TIMESTAMP. If you need to maintain only the date joined, you should not update the field when the records been updated.

*IPAddress column is VARCHAR(80). If you store IPv4 type IP addresses, this will be too lengthy.

*Empty string ('') as DEFAULT for NOT NULL columns. Not good if intention is to have a value (other than '') on the field.

*Empty string ('') as DEFAULT for UNIQUE Fields. This contradicts the contraints enforced if your intention is to have a Unique Value (other than '').


text:
Q: Prism.Unity.Forms 8.1 container.resolve stoped working after upgrade from version 7.2 I'm not a developer, but I managed to make an Xamarin.forms android app with prism 7.2, but recently I needed to add more features to the app and updated all NuGet packages, which updated Prism to version 8.
After the upgrade when I try to resolve on a tabbedpage:
_unityContainer.Resolve<IMyTabbedPageSelectedTab>().SetSelectedTab(0);

I get the following Unity.ResolutionFailedException: 'Resolution failed with error: No public constructor is available for type XXX.Interfaces.IMyTabbedPageSelectedTab.'
My interface is:
public interface IMyTabbedPageSelectedTab
{
    int SelectedTab { get; set; }
    void SetSelectedTab(int tabIndex);
}

My MainPageViewModel:
    public class MainPageViewModel : ViewModelBase, IMyTabbedPageSelectedTab
{
    private readonly IUnityContainer _unityContainer;

    private int _selectedTab;
    public int SelectedTab
    {
        get { return _selectedTab; }
        set
        {
            SetProperty(ref _selectedTab, value);
            Title = $"My Tabbed Page - Tab [{SelectedTab + 1}]";
        }
    }

    public MainPageViewModel(INavigationService navigationService, IUnityContainer unityContainer): base(navigationService)
    {
        Title = $"My Tabbed Page - Tab [{SelectedTab + 1}]";

        this._unityContainer = unityContainer;
        _unityContainer.RegisterInstance<IMyTabbedPageSelectedTab>(this, new ContainerControlledLifetimeManager());
    }

    public void SetSelectedTab(int tabIndex)
    {
        SelectedTab = tabIndex;
    }
}

Can someone shed some light on what may be the problem?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Write a macro to check function return code Quite common that we have to call set of functions that have similar behavior - for example return negative value and set errno variable in case of failure. Instead of repeatedly write check code, sometimes it is useful to wrap it into macro:
#define CHECKED_CALL( func, ... ) \
    do {\
        auto ret = func( __VA_ARGS__ );\
        if( ret < 0 ) {\
            std::cerr << #func "() failed with ret " << ret << " errno " << errno << std::endl;\
            throw std::runtime_error( #func "()" failed" );\
         }\
    while(false)

then use is simple:
 CHECKED_CALL( func1, 1, 2, 3 );
 CHECKED_CALL( func2, "foobar" );

etc. Now let's say I need to get result of the call in case it did not fail. Something like:
 auto r = CHECKED_CALL( func3, 1.5 );

Obviously this would not work as written and of course I can write another macro, but question is, is it possible to write macro that would work in both cases? Or maybe not macro but not very complicated code, that will take me 10 times more time to implement than to write yet another macro for value return. Especially not to generate warning of unused code etc.

A: Almost everything in your CHECKED_CALL macro can be turned into a function template, which has the advantage of passing through the C++ compiler's type system instead of the preprocessor's brute textual substitution.
So, for instance, we can write
template<class Callable, class... Args>
void checked_call(Callable t_callable, std::string t_functionName, Args&&... t_args)
{
    auto ret = t_callable(std::forward<Args>(t_args)...);
    if( ret < 0 )
    {
    std::cerr << t_functionName << "() failed with ret " << ret << " errno " << errno << std::endl;
    throw std::runtime_error( t_functionName + "() failed" );
    }
}

One downside here is that checked_call requires us to explicitly pass a std::string representing the name of a function.
Example calling code:
int failingFunction()
{
    return -1;
}

int main(){
    checked_call(failingFunction, "failingFunction");
}

We can introduce a macro that automatically pairs a function with a string representation of its name to use with checked_call, like so:
#define NAMED_FUNCTION(func) func, #func

int main(){
    checked_call(NAMED_FUNCTION(failingFunction));
}

We could also adapt the definition of checked_call to return ret if we wanted to, by changing the return type from void to auto and adding a return ret; if it doesn't throw. However, you may need to examine your functions' actual signature to figure out where the true return value is, assuming the nominal return value is actually an error code.


text:
Q: WooCommerce change loading spinner icon IM trying to change the WooCommerce loading spinner icon. It's defined in the woocommerce.css:
.woocommerce .blockUI.blockOverlay::before {
    height: 1em;
    width: 1em;
    display: block;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -.5em;
    margin-top: -.5em;
    content: '';
    -webkit-animation: spin 1s ease-in-out infinite;
    animation: spin 1s ease-in-out infinite;
    background: url(../images/icons/loader.svg) center center;
    background-size: cover;
    line-height: 1;
    text-align: center;
    font-size: 2em;
    color: rgba(0,0,0,.75);
}

I've tried changing the loader.svg with a custom css:
.woocommerce .blockUI.blockOverlay::before {
     background: url(http://www.localhost.de/wp-content/uploads/custom-loader.svg) center center !important;
}

But the icon will not change. So I've googled a bit and found this here:
add_filter( 'woocommerce_ajax_loader_url', 'custom_loader_icon', 10, 1 );
function custom_loader_icon() {
    return __( get_home_path() . 'wp-content/uploads/custom-loader.svg', 'woocommerce' );
}

But the loading spinner icon is still the same. What can I do to change it? I don't know what I should try now...

A: The following code css rules work in Woocommerce last version. I have embedded them in the wp_head hook as it's easy for testing:
You will use this icon for testing, that you will put in your active child theme under an "img" directory, renaming the file my_spinner.gif.
If you use a theme instead of a child theme, you will use get_template_directory_uri() function instead of get_stylesheet_directory_uri() in the code.
The code:
add_action('wp_head', 'custom_ajax_spinner', 1000 );
function custom_ajax_spinner() {
    ?>
    <style>
    .woocommerce .blockUI.blockOverlay:before,
    .woocommerce .loader:before {
        height: 3em;
        width: 3em;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -.5em;
        margin-top: -.5em;
        display: block;
        content: "";
        -webkit-animation: none;
        -moz-animation: none;
        animation: none;
        background-image:url('<?php echo get_stylesheet_directory_uri() . "/img/my_spinner.gif"; ?>') !important;
        background-position: center center;
        background-size: cover;
        line-height: 1;
        text-align: center;
        font-size: 2em;
    }
    </style>
    <?php
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

A: I think CSS only is enough
.woocommerce .blockUI.blockOverlay:before,
.woocommerce .loader:before {
  background-image:url('path/to/your/image.gif');
}

it will work fine

A: Try following code. Assuming your custom-loader.svg is at root of "uploads" directory.
add_filter( 'woocommerce_ajax_loader_url', 'custom_loader_icon', 10, 1 );
function custom_loader_icon($str_replace) {
    $upload_dir = wp_upload_dir();
    $str_replace = $upload_dir['baseurl'].'/wp-content/uploads/custom-loader.svg'
    return $str_replace;
}

Hope this works.


text:
Q: How to view jms queues in activemq after adding failover transport? I seem to be having trouble viewing my jms queues after applying failover transport to activemq. The queues can be viewed from the master using the usual url http://localhost:8162/admin/queues.jsp, but it does not work when tried on the slave. I need to see the queues created when the master is down and the slave takes over. Any idea how to make this work?

A: When both master and slave point to same folder for data repository this arrangement is called 'Master slave configuration with shared database', in this case following things occur

*

*when your master node starts up, it acquires a lock on this database
and it starts up successfully, so you can access this nodes details
from UI.

*but when a slave node starts up, it tries to gain lock of the database
, but as it is already locked by master node, it cant gain the lock
and keeps on polling the DB for lock and doesnt startup(This is an expected and correct behaviour)

*Now whenever master node fails , it releases the lock and this lock
is gained by slave node(as it is continuously polling the DB),now it
gains the lock and starts up, by this only one node is up at any
given time and if that node fails slave node starts up

in your case, if you shut down your master node you will surely be able to access slave node from UI
Hope this helps!
Good luck!


text:
Q: fatal error: botan/botan.h: No such file or directory I've taken the great advice from this answer, checked the file list for libbotan1.10-dev and found /usr/lib/libbotan-1.10.a, so I used the linker flag -lbotan-1.10.
I've successfully been able to code and compile websocket++, json-spirit, connector/c++, and boost::lockfree::spsc_queue.
I'm now trying to use botan's passhash9 to hash passwords.
When I try to compile with
g++  -Ofast -march=native -o btServer broadcast_server_tls.cpp
-I ~/websocketpp-master/ -std=c++0x -D_WEBSOCKETPP_CPP11_STL_
-D_WEBSOCKETPP_NO_CPP11_REGEX_ -lboost_regex -lboost_system
-pthread -L/usr/lib -lssl -lcrypto -ljson_spirit -lmysqlcppconn -lbotan-1.10

g++ gives an error on the #include <botan/botan.h> line, saying "broadcast_server_tls.cpp:12:25: fatal error: botan/botan.h: No such file or directory".
To install on Ubuntu 12.10, I did apt-get install libbotan1.10-dev.
How can I correct this?

A: You should compile as:
g++ "whatever_source_file" "whatever flags you are already using" -I/usr/include/botan-1.10/


text:
Q: Получение списка значения по ключу из вложенного массива JS Возможно вопрос покажется слишком легким, но он меня завел в ступор...
Как мне получить список значений, которые находятся по ключу PHONE - VALUE?
0:
ID: "40"
PHONE: Array(2)
    0: {ID: "186317", VALUE_TYPE: "MOBILE", VALUE: "+3333333333", TYPE_ID: "PHONE"}
    1: {ID: "190893", VALUE_TYPE: "WORK", VALUE: "+22222222222", TYPE_ID: "PHONE"}
TITLE: "Title 1"

1:
ID: "47"
PHONE: Array(3)
    0: {ID: "310047", VALUE_TYPE: "MOBILE", VALUE: "+777777777", TYPE_ID: "PHONE"}
    1: {ID: "310048", VALUE_TYPE: "HOME", VALUE: "+6666666666", TYPE_ID: "PHONE"}
    2: {ID: "310049", VALUE_TYPE: "OTHER", VALUE: "+1111111111", TYPE_ID: "PHONE"}
TITLE: "Title 2"
.....

Я пытаюсь сделать это через цикл:
var numberList = [];

for (data in resultData){
        numberList.push(resultData[data].PHONE);
}

И при выводе через numberList.VALUE получаю undefined

A: const numberList = resultData.map(itm => itm.PHONE.map(ph => ph.VALUE));

В результате, массив numberList должен содержать подмассивы с номерами, т.е. например
[
  ["+3333333333", "+22222222222"],
  ["+777777777", "+6666666666", "+1111111111"]
]

Если же хочется получить одномерный массив (потеряв связанность с resultData по индексу), то такой массив можно получить выражением numberList.flat(1).

A:

const obj = {
  0: {
    ID: "40",
    PHONE: [
            {ID: "186317", VALUE_TYPE: "MOBILE", VALUE: "+3333333333", TYPE_ID: "PHONE"},
            {ID: "190893", VALUE_TYPE: "WORK", VALUE: "+22222222222", TYPE_ID: "PHONE"}
           ],
    TITLE: "Title 1"},

  1: {
    ID: "47",
    PHONE: [
            {ID: "310047", VALUE_TYPE: "MOBILE", VALUE: "+777777777", TYPE_ID: "PHONE"},
            {ID: "310048", VALUE_TYPE: "HOME", VALUE: "+6666666666", TYPE_ID: "PHONE"},
            {ID: "310049", VALUE_TYPE: "OTHER", VALUE: "+1111111111", TYPE_ID: "PHONE"}
           ],
    TITLE: "Title 2"}
}

let arr = []
Object.values(obj).forEach(el1 => el1.PHONE.forEach(el2 => arr.push(el2.VALUE)))
console.log(arr)


text:
Q: Как удалить колонку grid программно по номеру? Grid c множеством колонок и столбцов - они создаются динамически(пользователь вводит их количество и колонки и столбцы программно создаются.), соответственно у них нет названий. Т.е. как удалить программно колонку в grid зная её номар?
A: Вот так вот:
Наш_Grid.RowDefinitions.RemoveAt(index);


text:
Q: dialog Framework is not firing a close event I open dialog in the bean method like that
RequestContext.getCurrentInstance().openDialog("/pageName.xhtml", options, null);

it's inside actionListener of button clicked.
There is also a "close" button on the pageName.xhtml which executes:
RequestContext.getCurrentInstance().closeDialog(null);

But dialog is not being closed. What I need actually is to catch a close event, but I can't use <p:ajax event="close"/> since I don't have p:dialog element and I couldn't manage it with <p:ajax event="dialogReturn"/> placed inside p:commandButton which opens the dialog.
I also tried to add a widgetVar in option-map when opening and call
PF('widgetVarName').hide();

on click. No result.
Option closable set to true puts a cross on right top of the dialog window, which closes the dialog, yes, but, it didn't fire a close event.
So the question is: How can I close the dialog and execute some code after?
Thank you in advance!

A: This code works for me:
index.xhtml
<p:commandButton id="openDialogButton" value="open dialog" action="#{myBean.openDialog('origin')}">
    <!-- dialogReturn event: data could be passed, see page 587 in PF 6.1 manual. -->
    <p:ajax event="dialogReturn" listener="#{myBean.doSthOnDialogReturn}"/>
</p:commandButton>

myDialogPage.xhtml
<p:commandButton id="closeButtonDialog" value="close dialog"
   action="#{myBean.closeDialog('false')}"/>

<p:commandButton id="closeButtonDialog2" value="close dialog 2"
    action="#{myBean.closeDialog('true')}"
    ajax="false" validateClient="true"/>

Note: Example shows how to pass parameter from dialog. You can also notice, that the first button does just return while the second one does validation at first. I think these things can be useful.
myBean.java
public void openDialog(String origin) {
    RequestContext.getCurrentInstance().openDialog("myDialogPage",
    options, null);
}

public void closeDialog(Boolean param) {
    RequestContext.getCurrentInstance().closeDialog(param);
}

public void doSthOnDialogReturn(SelectEvent event) {
    if ((Boolean) event.getObject()) { // retrieve param value
        doSth();
    }
}

A: Hello everybody and future me,
remember to put your Buttons in a From ;-)
<h:form id="myformid">
<p:commandButton id="closeButtonDialog" value="close dialog"
   action="#{myBean.closeDialog('false')}"/>

<p:commandButton id="closeButtonDialog2" value="close dialog 2"
    action="#{myBean.closeDialog('true')}"
    ajax="false" validateClient="true"/>
</h:form>


text:
Q: Scroll dialog after keyboard is on I have some dialog with EditText fields. when i want to fill some EditText the keyboard is opened and I can't fill some fields above. i should close the keyboards and after click on EditText above. How can I make my dialog scrollable when the keyboard is on to avoid closing the keyboard?

A: Try:
dialog.getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

A: Add windowSoftInputMode to activity in manifest
<activity
...
    android:windowSoftInputMode="stateHidden|adjustResize">

A: xml (dialog_layout.xml):
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="10dp"
        android:elevation="5dp">

    </androidx.cardview.widget.CardView>

</androidx.core.widget.NestedScrollView>

java:
final Dialog dialog = new Dialog(this);
            dialog.setContentView(R.layout.dialog_layout);
            dialog.setCanceledOnTouchOutside(false);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    dialog.show();


text:
Q: NSStringEncoding - enum to string to enum So I'm saving the NSString encoding enum value in a database as a string. This is one of the values:
 NSUTF16LittleEndianStringEncoding = 0x94000100,

And I'm saving it as a string with value 0x94000100. My goal is to read this value as an NSString, but then turn it into a value I can use to encode:
        NSString* encodingValueAsString = [object objectForKey:kWSWordlistFilesEncodingKey];

        // Convert 'encodingValueAsString' to variable 'encoding' that can act as enum

        NSString* dataString = [[NSString alloc] initWithData:data
                                                             encoding:encoding];

How do I write that missing line?

A: There's no reason to convert the enum value to/from a string. Just save it and read it back as an int.
But the short answer to your original question is:
NSStringEncoding encoding = [encodingValueAsString intValue];

Wait - that won't work since you are saving the string as the hex value.
You need to use NSScanner:
NSScanner *scanner = [NSScanner scannerWithString:encodingValueAsString];
NSStringEncoding encoding;
[scanner scanHexInt:&encoding];

See why using int instead of a string would be easier?


text: Q: What tags are bots interpreting when creating a preview of the main picture Wondering which tags e.g. Twitter/Telegram/*-bots are using to recognize, that at a given link, there is a main image they want to show inside their preview.


text:
Q: MassTransit/RabbitMQ - Moving rejected messages to dead letter w/ redelivery I'm currently working on a project where we would like the use a dead-letter queue for message redelivery instead of the built-in scheduler of MassTransit.
The idea is simple: If a consumer throws a certain set of exceptions we retry the message several times and then want to re-schedule the message for re-delivery in the (near) future. For instance, if messages arrive in the wrong order. I am trying to accomplish option #2 from this article ( https://engineering.nanit.com/rabbitmq-retries-the-full-story-ca4cc6c5b493 )
Whenever my consumer throws an exception, MassTransit will move the message to the _error queue instead of the dead letter. I'm sure this is a misconfiguration on my part but I'm not really sure how I can accomplish what I want.
My bus is configured like this:
IBusControl ConfigureBus(IBusRegistrationContext provider)
{
    return Bus.Factory.CreateUsingRabbitMq(sbc =>
    {
        sbc.Host("localhost", c =>
        {
            c.Username("guest");
            c.Password("guest");
        });

        sbc.MessageTopology.SetEntityNameFormatter(new EntityNameFormatter("Consumer1"));

        sbc.ReceiveEndpoint("Consumer1.ActionPerformed", ep =>
        {
            ep.Consumer<ActionPerformedConsumer>();
            ep.ExchangeType = ExchangeType.Fanout;

            ep.UseMessageRetry(r => r.Immediate(1));
            ep.BindDeadLetterQueue("deadletter", "dead", cfg =>
            {
                cfg.SetExchangeArgument("x-message-ttl", TimeSpan.FromSeconds(60));
                cfg.Durable = true;
            });
        });
    });
}

A: To change the error queue behavior of MassTransit, you can configure the receive endpoint to propagate errors back up to the transport, which will nack them back to the broker.
ep.RethrowFaultedMessages();

However, I'm pretty sure MassTransit does this with the requeue parameter set to true so that under normal conditions messages are not lost. I don't believe there is currently a way to override it.
It would seem that if this is an approach that works (of course, it won't work with quorum queues, they don't support TTL) with standard queues, it might be worth adding this type of configuration to RabbitMQ so that it builds out the exchanges and such to handle it as an alternative to the delayed exchange scheduler.

Update, I'd consider Option 3 superior to Option 2, and more inline with how MassTransit works.


text:
Q: Group array of object base on one unique property? For example, how can I turn the array of objects shown below into the corresponding result where names are grouped by id? I'd like to do this using vanilla Javascript and without using an external library like lodash if possible.
Example array:
const items = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' },
    { id: 1, name: 'd' },
    { id: 3, name: 'f' },
    { id: 1, name: 'a' },
    { id: 3, name: 'c' },
  ];

Expected result:
 const result = [
   { id: 1, names: ['a', 'd']},
   { id: 2, names: ['b']},
   { id: 3, names: ['c', 'f']}
  ]

A: I'm performing an reduce on the array and it gives me an object in the form of
{
  1: [object Set] { ... },
  2: [object Set] { ... },
  3: [object Set] { ... }
}

where Set is used to keep unique values only.
After that I'm running a map on Object.entries to get the data to the format you wanted.

const items = [{ id: 1, name: 'a' },{ id: 2, name: 'b' },{ id: 3, name: 'c' },{ id: 1, name: 'd' },{ id: 3, name: 'f' },{ id: 1, name: 'a' },{ id: 3, name: 'c' },];

  const a = items.reduce((acc,curr)=> {
    if(!acc[curr.id]){
        acc[curr.id] = new Set();
    }

    acc[curr.id].add(curr.name)

    return acc;
  },{})

  let result = Object.entries(a).map((el) => ({id: el[0],names:[...el[1]]}))

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


text:
Q: Tensorflow Object Detection API GPU memory issue I'm currently trying to train a model based off the model detection zoo for object detection. Running the setup on the CPU works as expected but trying the same on my GPU results in the following error.
2021-03-10 11:46:54.286051: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublas64_11.dll
2021-03-10 11:46:54.751423: E tensorflow/stream_executor/cuda/cuda_blas.cc:226] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2021-03-10 11:46:54.764147: E tensorflow/stream_executor/cuda/cuda_blas.cc:226] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
2021-03-10 11:46:54.764233: W tensorflow/stream_executor/stream.cc:1455] attempting to perform BLAS operation using StreamExecutor without BLAS support

Monitoring the GPU information within task manager it seems that tensorflow (as expected as far as I've understood it) trys to allocate the whole memory. Shortly after reaching a specific peak (roughly 7.3 Gb of 8Gb) TF crashes with the error seen in the snippet above.
Solutions for this specific error within the internet / stackoverflow mention that this problem can be solved allowing the dynamic memory growth. Doing this seems to work and TF manages to create atleast one new checkpoint but in the end crashes with an error of a similar category. In that case the CUDA_OUT_OF_MEMORY error.
System Information:

*

*Ryzen 5

*16 GB RAM

*RTX 2060 Super with 8Gb VRAM

Training Setup:

*

*Tensorflow 2.4

*CUDA 11.0  (also tried several combinations of CUDA cuDNN versions)

*cuDNN 8.0.4

Originally I wanted to use the pretrained EfficientDet D6 model but also tried several others like EfficientDet D4, CenterNet HourGlass 512x512 and the SSD MobileNet V2 FPNLite. All those models were started with different batch sizes but even on a batch size of 1 the problem still occures. The training images aren't large either (in average 600 x 800). Currently there are a total of 30 images, 15 per class for training (I'm aware that the training data set should be bigger, but it's just to test the setup).
Now my question would be if anybody has an educated guess or another approach of finding the cause of this error as I cannot immagine that my 2060 isn't capable of atleast training a SSD with a batch size of 1 and rather small images. Could it be a hardware fault? If so, is there a way to check that?

A: I've done a complete reinstallation of every involving component. I might have done something different this time but I cannot say what. Atleast I'm now able to utilize the GPU for training.


text:
Q: How to Manage location of a Dynamic Download Link I have a small Android application I'm doing for fun. One of the main parts of the application is the ability to download a document from a certain website. However, the link for the download will change frequently and I'd like to have some way to manage which link the application downloads. With little experience, the first thought I had would be an XML file I could download and parse with the necessary links to the documents (note that the documents aren't sensitive and people got to the XML file it'd be worthless). Really it could be any human editable format on the web server.
Some additional info is that I'm using C++ (Qt) for my Android application, but I don't really think this is going to limit it too much. It's mainly the best way to store a dynamic link location. The other, more far-fetched idea I had would be a TcpServer that updates the address, but I feel that's a bit overkill.

A: As others have pointed out in the comments, XML on the webserver is a good solution. Now when I update the links in the XML file, the download link will change dynamically in the Android app (or other places). This is okay because XML is standardized and security isn't an issue.
Thanks for the help and second opinions!


text:
Q: Keeping a AngularJS bootstrap popover visible as element updates I'm using an AngularJS bootstrap popover on an element using popover-trigger='mouseenter'. The element updates using angularFire, and after an update, the popover disappears until I move my mouse (even within the element).
How can I get the popover to remain visible after an update?

A: When the model updates the directive might be getting reinitiated. Therefore, as the mouse is already over the element and stationary the mouseenter event is not fired.
Most likely you will have to edit the popover directive and add a function to the link function which checks the position of the mouse and if the mouse is over the trigger then it will keep the popover visible. However, this might cause flickering.
Or you can silently update the model so that the directive doesn't get reinitiated. If you post some sample code or a jsfiffle/plunker I would be able explain how to do that.


text:
Q: xrandr shows VGA1 as disconnected I have a Thinkpad W520 with Nvidia Optimus graphics. I have disabled the Nvidia card in BIOS (by selecting "integrated graphics"), so I'm running only on the integrated Intel graphics. I get full 3D acceleration, which would suggest the drivers are properly installed. However, I'm not able to use an external monitor. With the external monitor connected and turned on, running xrandr always gives:
$ xrandr
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
LVDS1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 344mm x 193mm
   1920x1080      60.0*+   59.9     50.0
   1680x1050      60.0     59.9
   1600x1024      60.2
   1400x1050      60.0
   1280x1024      60.0
   1440x900       59.9
   1280x960       60.0
   1360x768       59.8     60.0
   1152x864       60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
VGA1 disconnected (normal left inverted right x axis y axis)

What gives? It sees the VGA1 port (to which the external display is connected), but it appears disconnected.
I have tried forcing a resolution as per these instructions, but when I do that X becomes unresponsive and I have to Ctrl-Alt-F1 and restart it.

A: Welcome to the joy of owning a laptop with Optimus. As a fellow sufferer, here's what I've had to do:
These instructions from Sagar Karandikar work on 12.04 and 12.10.
The trick is, that if you're running 12.10, you need to download a version of the intel display patch that is equivalent to the closest driver you can manage from here. I managed to find a driver matching versions for Raring.
Then, set up a script to run the display commands, change the flag from VIRTUAL to VIRTUAL1, and you're set.

A: If you care about having the option to switch between the nVidia and intel chips, try Brian's solution.  If you're fine just using the nVidia chip, select the 'discrete graphics' option in your BIOS.  I've read somewhere that the VGA port is not wired to the intel chip so you'll have to enable the nVidia chip to use the extra port.  I had a problem similar to yours and this seemed to fix my issue.


text:
Q: How to recognize a swipe gesture in a specific area? I'm working on an Air Android app and I would like to show and hide a menu based on a users gesture.
How to set the gesture recognition to a specific area instead to the whole stage? (e.g. the area from y 0 to 100 px)
Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe);

function onSwipe (e:TransformGestureEvent):void{
if (e.offsetY == 1) {
 //User swiped towards bottom
showMenu()
 }
 else if (e.offsetY == -1) {
 //User swiped towards top
hideMenu()
 }
}

A: You should add a component to the stage (empty sprite container lets call it mySprite) with the proper dimensions and location and then you have 2 options:
option 1
http://www.republicofcode.com/tutorials/flash/as3swipegesture/
option 2
add a check to see if swipe was done on mySprite
function onSwipe (e:TransformGestureEvent):void{\
**if (e.target=!mySprite){return}**
if (e.offsetY == 1) {
 //User swiped towards bottom
showMenu()
 }
 else if (e.offsetY == -1) {
 //User swiped towards top
hideMenu()
 }
}

Option 3
Multitouch.inputMode = MultitouchInputMode.GESTURE;

var mySprite = new Sprite();
mySprite.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe);
mySprite.graphics.beginFill(0x336699);
mySprite.graphics.drawRect(0, 0, 100, 80);
var myTextField = new TextField();
myTextField.y = 200;
addChild(mySprite);
addChild(myTextField);

function onSwipe(evt:TransformGestureEvent):void {

    if (evt.offsetX == 1 ) {
    myTextField.text = "right";
    }
    if (evt.offsetY == -1) {
    myTextField.text = "up";
    }
    myTextField.text = evt.phase;

}


text:
Q: Filtering on a Azure service bus topic I have a main application that allows a user to edit all of their data (about 20 fields). When this is updated I add this to a Service Bus topic which I have other areas of the system subscribing to.
One of these subscriptions only cares if a single field is updated (phone number). I'm wondering what is the best way to handle this?
Looking at the GitHub example here, it states:

The cost of choosing complex filter rules is lower overall message throughput at the subscription, topic, and namespace level, since evaluating rules costs compute time. Whenever possible, applications should choose correlation filters over SQL-like filters since they are much more efficient in processing and therefore have less impact on throughput.

So from what I can gather I could add what properties have been updated using the properties property on the BrokeredMessage class and filter based on that but that is not recommended based on the above statement.
I could let the message go through and action it (this would just update a row in a table to the same value) but this seems redundant.
Do I have any other options?

A: If you have predefined values you'd be filtering on for that subscription, use CorrelationFiter. In case it requires conditional match (e.g. a phone number that starts with area code 321), then SqlFilter is absolutely fine. It really depends how much of filtering you're going to perform. My suggestion would be benchmarking and measuring the performance, tweaking your filters to give you the optional result.


text:
Q: Averaging over n lines, outputting to an array and then continuing first time post and probably a bit easy!
I am trying to read in a large data file, where I want to read in the time-stamp from the header and then average the following 128 lines (containing numbers). Once that is done, I want to sort the data with the highest values first. I'm using numpy and scipy.
To do this, I have initially grep'd from the raw data file.
grep "LL" RAW.TXT > LL.TXT

Since I want only the 6th column, I then do this in Python:
DATA_LL = genfromtxt(LL.TXT,usecols = (5))

After this, I want to average the first 128 rows and output this value to an array. I want it to then continue to the next 128 rows and so-on until the end of the file. Outputting, perhaps, to a variable called AVERAGES.
This bit, I'm not sure how to do.
Once this array is created, I want to attach the time-stamps to the array:
for line in RAW.readlines():
  if line.contains("Time of record"):
    AVERAGES.append(line)

The only problem here is that I think it will append directly to the column, when I would prefer it to append to a new column.
After this, sort, using the normal sort command.
I think I'm on the right track, but any help greatly appreciated!
Cheers

A: One fairly straightforward way of doing this would be to track the timestamps in a separate list, then use np.concatenate (the documentation on this function is quite helpful) with the axis=1 keyword argument to join the timestamps array to your averages array. The biggest problem I see with this approach, however, is that as written, your AVERAGES variable will be appended with strings and not floats, whereas NumPy arrays are homogeneous in data type. Without some more details about the problem you are trying to solve, I don't have a concrete suggestion for how to fix this other than to use the strptime and mktime functions of Python's time module to convert timestamps to floats.


text:
Q: Creation of a temporary table in postgres I'm trying to create a temporary table in Postgres (to speed up joining, as there will be a lot of similar queries throughout a session). The SQL that will be called at the beginning of a session is the following:
CREATE TEMPORARY TABLE extended_point AS
SELECT (
  point.id,
  local_location,
  relative_location,
  long_lat,
  region,
  dataset,
  region.name,
  region.sub_name,
  color,
  type)
FROM point, region, dataset
WHERE point.region = region.id AND region.dataset = dataset.id;

The tables point has the columns id::int, region::int, local_location::point, relative_location::point, long_lat:point (longitude, latitude).
Region has the columns id::int, color::int, dataset::int, name::varchar, sub_name::varchar.
Dataset has the columns id::int, name::varchar, type:varchar.
When this is run, I get the error message: [25P02] ERROR: current transaction is aborted, commands ignored until end of transaction block.
As a side, the commands are executed in PyCharm, and is part of a Python project.
Any suggestions?
Thanks in advance :)

A: There is an important difference between these two queries:
select 1, 'abc';
select (1, 'abc');

The first query returns one row with two columns with values 1 and 'abc'. The second one returns a row with one column of pseudo-type record with value (1, 'abc').
Your query tries to create a table with one column of pseudo-type record. This is impossible and should end with
ERROR: column "row" has pseudo-type record
SQL state: 42P16

Just remove brackets from your query.
As a_horse stated, [25P02] ERROR does not apply to the query in question.
Btw, my advice: never use keywords as table/column names.


text:
Q: Iron Router, Collection Helpers, and Session Variables. How to call an item attribute in a javascript function I am working on a Meteor application and am trying to pass an attribute of an item in a collection to a javascript function.  In this instance I working with instafeed.js, a javascript plugin for the instagram API, but I would like to understand the process on a more fundamental level.
I've been able to pull records from my Teams collection into the /teams/:id route, and display attributes of a team using the {{name}} and {{igHandle}} template helpers.
I have also been able to get instafeed.js to work, using this package etjana:instafeed and the demo provided online.  The tag I am pulling is assigned statically via:Session.setDefault('tagName','football');
Eventually I would like to pull the user profiles, but that requires an access token from oauth2.  I think that can be achieved with a {{$.Session.get access_token}} handlebar helper, but I need to figure out to feed a variable into the instafeed.js function first.
Could someone please explain how to pass the {{igHandle}} attribute through to the tagName in the javascript function.  My code is as follows:
Team Template:
<template name="teamView">

{{name}}

            &nbsp{{insta_hndl}}

Instagrams

            {{> igTeamFeed}}

</template>

Everything works, except the {{>igTeamFeed}} render. I am able to get content to show, but it is currently static. (assigned via (Session.setDefault('tagValue','football').
Instafeed Template:
<template name="igTeamFeed">

@{{insta_hndl}} Instagram

</template>

Content is displaying, but again only through the static (Session.setDefault('tagValue','football') code.
Router:
Router.route('/teams/:_id', {
    name: 'teamView',
    template: 'teamView',
    data: function(){
        var currentTeam = this.params._id;
        return Teams.findOne({ _id: currentTeam });
    },
    action: function() {
        if (this.ready()) {
            this.render('teamView');
        } else {
            this.render('loading');
        }
    }
});

Works with template helpers, so I am thinking I am ok here.  Also following the instructions of a user per one of my prior posts.
Instafeed Javascipt: (needs some work)
Template.igTeamFeed.helpers ({
  igData: function() {
    return Session.get('insta_hndl');
  },
});

Template.igTeamFeed.onRendered(function () {
    //clear any previously stored data making the call
    Session.get('insta_hndl'); //extra add-in
    Session.set('insta_hndl', null);
    Session.set('insta_hndl', this.data.insta_hndl); //extra add-in

    var igHandle = this.data.insta_hndl;

});

Tracker.autorun(function(){
    feed = new Instafeed({
        get: 'tagged',
        tagName: Session.get('insta_hndl'),
        clientId: 'xxxxxxxxxxxxxxxxxxx',
        resolution: 'thumbnail',
        sortBy: 'most-liked',
        limit: '15'
    });

    feed.run();
});

*

*I have a helper to get the current insta_hndl for the session.  The session item is passed through the team/:_id tag of the url, and defined in the router

*The onRendered is wiping out the old handle, and inserting the new one.  I added two additional Session.get and Session.set functions since I was getting an error that insta_hndl was undefined (differing from the response on my previous post).  Could be wrong there.

*The tracker.autorun function was code I had working with an instafeed example.  Should it be somewhere else? Maybe in a helper or onRendered function?  Also do I need tracker.autorun to use instafeed? To my understanding it dynamically updates the feed when a tagName changes, but aren't there other ways to do this?

How to Solve
These are some ways I'm thinking I could to solve this.  Please advise on how to do this / what you think is best practice:

*

*Collection Helpers: Was thinking I could call something like Teams.findOne().insta_hndl but didn't have much luck.  Is that the right code block to use? Do I have to define a variable in the template helper, or can I call it directly in the feed js function?

*Handlebars Helpers: Thinking I could do something with a Session helper, but not sure if it would work if one user had two different instances of the instafeed open (two tabs open with different teams selected).

*Reactive Methods: Allows one to call methods synchronously inside Tracker.autorun.  Thought i read something that said Meteor already has this functionality baked in, but please advise.

*Iron Router Query: Part of me still isn't convinced the insta_hndl isn't getting passed through.  I've explored adding the instagram handle as a query param to the URL, but do not think this is a best practice.

If someone could help me get this working that woudld be great, but explanations would even better! Really spending a lot of time on this, and many of the online resources are using depreciated syntax.
Also two more related questions questions:
Should I use a controller? Should i write out a controller separately? Or just include it in Router.route functions?  Seeing some people rely heavily on controllers, but a lot of documentation does everything through Router.route.
Should I break out the instafeed function into a method? If so how should I do this?  I spent a great amount of time tryig to set up the whole instafeed function as a server side method, but couldn't seem to get it to work.  I only foresee myself using this function in one or two other templates, so I figured it was fine to leave as is.  Please advice.

A: Sorry that this was a bit confusing.  The correct javascript is:
Template.igTeamFeed.helpers ({
    teams: function() {
    return Teams.find();
  }
});

Template.igTeamFeed.onCreated( function() {

    var igHandle = Teams.findOne(Router.current().params._id).insta_hndl;

    feed = new Instafeed({
        get: 'tagged',
        tagName: Session.get('insta_hndl'),
        clientId: 'xxxxxxxxxxxxxxxxxxx',
        resolution: 'thumbnail',
        sortBy: 'most-liked',
        limit: '15'
    });

    feed.run(); //run the new Instafeed({})
});

There is no need for any of the things I suggested.  The attribute can be grabbed with Collection.findOne(Router.current().params._id).attrib, where Collection is your collection and attrib is the non-_id value you want to grab.
Also did not need tracker.autorun, that was throwing me off as well.


text:
Q: Create database from liquibase maven plugin I'm able to run liquibase fine against an existing database but I'm trying to also automate the creation of the database.
I'm using the maven plugin with the config below:
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>3.5.0</version>
            <configuration>
                <propertyFile>src/main/resources/liquibase.properties</propertyFile>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>update</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

And my liquibase.properties file has the following:
driver=org.postgresql.Driver
url=jdbc:postgresql://localhost:5432/mydb?createDatabaseIfNotExist=true
username=postgres
password=mypass
changeLogFile=db.changelog.xml
referenceUsername=postgres
referencePassword=${database.password}

According to another question on SO adding the URL parameter createDatabaseIfNotExist=true should create the db when the plugin update goal is run.  However, I get the following error:
[ERROR] Failed to execute goal org.liquibase:liquibase-maven-plugin:3.5.0:update (default-cli) on project accommodation: Error setting up or running Liquibase: liquibase.exception.DatabaseException: org.postgresql.util.PSQLException: FATAL: database "mydb" does not exist -> [Help 1]

A: In general, Liquibase will not create the database if it does not exist. Liquibase uses a JDBC driver to communicate with the database, and JDBC doesn't have an API for creating a database from scratch. Many databases don't allow you to create a database using just SQL either, so I think that is why the feature isn't there.
Postgres does have a SQL command that creates a database, so you could try using a <sql> change tag that was specific to postgres - something like this:
<changeset id="createdatabase" author="steve" dbms="postgres">
  <sql>CREATE DATABASE sales OWNER salesapp TABLESPACE salesspace</sql>
</changeset>

This is not tested at all, and may not work.


text:
Q: comma and space separated number and hyphen separated string regular expression I have to validate the following string using jquery i need regex please help find solution for this,
The valid strings are,
(1)1,2,3,4,1,2-8
(2)1,2, 3, 4, 1, 2-8

Should also accept commas and commas with spaces and also the number should be hyphen separated
I have tried the following regex ,
^([0-9]+(-[0-9]+)?)(,([0-9]+(-[0-9]+)?))*$

A: This one works for the strings you posted:
var rx = new RegExp(/^\(\d\)(\d,\s*){5}\d\-\d$/);

However, it wasn't clear to me whether the (1) and (2) were supposed to be part of the strings. If not, use this:
var r2 = new RegExp(/^(\d,\s*){5}\d\-\d$/);
// a digit, followed by a comma, followed by some whitespace, repeated five times
// with a digit-hyphen-digit sequence at the end


text:
Q: No route matches [PATCH] I'm attempting to submit a form but am running into the error

No route matches [PATCH]

I've seen a variety of posts on this error but but in each one they only set get in their routes or some such error.  I've also had no problem submitting other forms with nearly identical routing and form structure.
So first, Security has_many :stockholders
My Form is as follows (location: views/stockholders/edit.html.erb):
<%=  simple_form_for @stockholder, url: url_for{action:'update', controller:"stockholders"}, html: {id:"stockholderform"}, update: { success: "response", failure: "error"} do |f| %>

                <%= f.grouped_collection_select :entity_id, [Org, Person], :all, :model_name, :to_global_id, lambda {|org_or_person_object| org_or_person_object.instance_of? Org? rescue org_or_person_object.fname + " " + org_or_person_object.lname rescue org_or_person_object.name}, label:"Stockholder", class: "names"%>

                <%= f.input :cert_number, label:"Certificate Number" %>
                <%= f.input :issue_date, Label: "Issue Date" %>

        <%= f.submit %>

<% end %>

And my controller is:
class StockholdersController < ApplicationController
    def edit
        @stockholder=Stockholder.find(params[:id])
        @security=Security.find(params[:security_id])
        @company=@security.company
    end

    def update
        @stockholder=Stockholder.find(params[:id])
        @security=Security.find(params[:security_id])
        @company=@security.company
        if @stockholder.update(stockholder_params)
            redirect_to edit_security_path(@security)
        else
            redirect_to edit_security_stockholder_path
        end
    end

    private

        def stockholder_params
            params.require(:stockholder).perimit(:id, :entity_id, :cert_number, :issue_date, :shares_issued, :shares_repurchased, :shares_canceled, :shares_outstanding)
        end
end

Finally, my routes are:
resources :securities do
    resources :stockholders
end

Can anyone help me understand what's going on here?  I structured two models in exactly this way and didn't run into a problem.
Many thanks in advance

A: Your route expects two more parameters, which are :security_id and :id.
simple_form_for @stockholder, url: { action: 'update', controller: "stockholders", security_id: @security.id, id: @stockholder.id }, ...

where @security may be @stockholder.security if not instantiated in the controller.
Or you can do it more elegantly:
simple_form_for [@security, @stockholder], ...  # url parameter is not needed


text:
Q: What is correct approach to refresh id-token via. AWSMobileClient swift? I am using aws-cognito UserPool (via. AWSMobileClient) for authentication of users to access the AWS Services.
Currently the user may choose to log-in via Phone, Google and Facebook using Hosted UI option, which in return provides the ID-token, Access-token, and Refresh-token.
As per the AWS docs, the id-token is valid maximum for 1hour, and the refresh-token automatically updates the id-token(provided refresh token is valid and not expired).
To request the new id-token when the initial has been expired, I call :
AWSMobileClient.default().getTokens(<#T##completionHandler: (Tokens?, Error?) -> Void##(Tokens?, Error?) -> Void#>)
This works fine when user is logged in via phone number, and successfully returns me updated ID-token.
But if the user is logged in via Social logging method, on calling the said functions brings me the drop-in UI from AWS to sign-in.
How may I stop this behaviour in case of social login?


text:
Q: How to remove multiple meta characters with awk or sed I am trying to remove few metacharacter or special chars from mu command line output with sed, awk or tr or any handy though fast utility. Moreover , i have tried few tricks at my level which are working but in multiple addition of commands.. just what i got below..
1) The first One the exact Output which the command yields..
$ getent netgroup login_access_foxone
login_access_foxone  (-,cacti,) (-,multi,) (-,hipot,) (-,jack,)

2) below is the sed thing which combined with awk to yield the output` desired.
$ getent netgroup login_access_foxone | sed 's/login_access_onefarm//g' | sed 's/)/\n/g' | awk 'BEGIN {FS=","}{print $2}' | grep -v ^$
cacti
multi
hipot
jack

3) The next below One with tr command but again had to use cut to get the output..
$ getent netgroup login_access_foxone | tr -d '(' | tr ')' '\n' | cut -d, -f2
cacti
multi
hipot
jack

4) This is with awk but again into two parts
$ getent netgroup login_access_foxone | awk -v FS="[()]" '{for (i=2;i<=NF;i+=2) print $i }' | awk -F, '{print $2}'
cacti
multi
hipot
jack

5) Few More test with sed but right now unable to  remove "-" & "," and get newline after each name
$ getent netgroup login_access_foxone | sed 's/[(),]//g'
login_access_foxone  -cacti -multi -hipot -jack

$ getent netgroup login_access_foxone | sed 's|[()-]||g'
login_access_foxone  ,cacti, ,multi, ,hipot, ,jack,

6) tried sed with some ugly combination but there is proble with output which contains whitespaces..
$ getent netgroup login_access_foxone | sed 's/[-,()]/\n/g'
login_access_foxone

cacti

multi

hipot

jack

I got it the idea for blank lines to be deleted with below code but agian need to have sed with another pipe..
$ getent netgroup login_access_foxone | sed 's/[-,()]/\n/g'|sed '/^\s*$/d'

A: awk to the rescue!
$ awk -F, '{for(i=2;i<=NF;i+=2) print $i}' file
cacti
multi
hipot
jack

or
$ awk -v RS=, '!(NR%2)' file
cacti
multi
hipot
jack

in the second alternative, we split each line into mini records separated by comma.  Since the required fields are between two commas, we'll print out the even numbered records, meaning record number divisible by two.  The order is naturally preserved (no surprises there).

A: You can try this sed, but it's quite verbose compared to awk :
sed 's/[^(]*(-,\([^,]*\),)/\1\n/g;s/\n$//' file

A: The shortest solution I can think of:
grep -Po ',\K\w*'
Example:
grep -Po ',\K\w*'  <<< 'login_access_foxone  (-,cacti,) (-,multi,) (-,hipot,) (-,jack,)'
cacti
multi
hipot
jack

Explanation:
\K : look-behind
\w : [a-zA-Z_]
*  : Any number of matches


text:
Q: Using Xbee java API I am trying to turn Xbee's pin on and off with a diffrent xbee(XB24-ZB) by using the java api library.
This is my system cunfig:
1.XBEE - Routher API (COM7)
2.XBEE - Coordinator API (COM17)
Two of them are with the same ID.
I am using the exmaple code:
XBee xbee = new XBee();
xbee.open("COM17", 9600);

// this is the Serial High (SH) + Serial Low (SL) of the remote XBee
XBeeAddress64 addr64 = new XBeeAddress64("00 13 A2 00 40 A7 3E 7E");

// Turn on DIO0 (Pin 20)
RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[XBeePin.Capability.DIGITAL_OUTPUT_HIGH.getValue()]);

xbee.sendAsynchronous(request);

RemoteAtResponse response = (RemoteAtResponse) xbee.getResponse();

if (response.isOk()) {
    System.out.println("Successfully turned on DIO0");
} else {
    System.out.println("Attempt to turn on DIO0 failed.  Status: " + response.getStatus());
}

// shutdown the serial port and associated threads
xbee.close();

When I run this block of code the DI0 on xbee #1 does change, but to 0(disabled) and not to 5.
I also get this error:

log4j:WARN No appenders could be found for logger (com.rapplogic.xbee.api.InputStreamThread).
  log4j:WARN No appenders could be found for logger (com.rapplogic.xbee.api.InputStreamThread).
  log4j:WARN Please initialize the log4j system properly.
  log4j:WARN Please initialize the log4j system properly.

The "AP" is set to 2 as said and the response I get is good.
So what am I missing here?
Thank you

A: Try to use these imports:
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

Add this line to you class:
private final static Logger log = Logger.getLogger(YourClass.class);

And, inside the main(), put this line beginning:
PropertyConfigurator.configure("log4j.properties");

I took it from the code examples inside the API src folder, and with it my programs are running just fine.


text:
Q: Does the expected value of the sum of components of a function of a random variable equal the sum of their expected values? Assuming $f:\mathbb R^N \to \mathbb  R^N$ is a differentiable function, and $X \in \mathbb R^N$ a random variable with expectation $\mu$ and finite co-variance matrix $\Sigma$.
Does the following hold true, given the linearity of expectation?
$\mathop{\mathbb E} \left[ \sum_i^N f(X)_i \right ] = \sum_i^N \mathop{\mathbb{E}}\left[ f(X)_i \right]$

A: I will use expectations under the image measure $\mu_X(X \in B),B \in \mathcal{B}(\mathbb{R})$ (i.e. the probability distribution of $X$). Differentiability is not a needed requirement. If $f(X)=[f_1(X),f_2(X),...,f_N(X)]$, then let's just consider the finite sequence $(f_n)_{n=1,2,...N}$ of functions $f_n:\mathbb{R}^N\to \mathbb{R}$. If $(f_n)_{n=1,2,...N} \in \mathcal{L}^1(\mu_X)$, that is if they have finite expectation, then by linearity
$$\sum_{n=1}^N\mathbb{E}_X[f_n(X)]=\sum_{n=1}^N\int_{\mathbb{R}^N}f_n(x)\mu_X(X \in dx)=\int_{\mathbb{R}^N}\sum_{n=1}^Nf_n(x)\mu_X(X \in dx)=\mathbb{E}_X\bigg[\sum_{n=1}^Nf_n(X)\bigg]<\infty$$
and
$$\sum_{n=1}^Nf_n(X) \in \mathcal{L}^1(\mu_X)$$
This is because the set of $\mu_X$-integrable functions $\mathcal{L}^1(\mu_X)$ is a vector space.


text:
Q: Should I clear a Set containing millions of data after using it? function doSomething(fruitsA: string[], fruitsB: string[]) {

  const fruits = new Set(fruitsA.concat(fruitsB))

  const myRottenFrutis = rottenFruits.filter((fruit) => fruits.has(fruit))

  // fruits.clear()

  // ...

  // ...

  // ...

  // ...

}

Now after getting myRottenFruits. I no longer need fruits. The function doesn't end after getting myRottenFrutis. And also fruitsA and fruitsB contains millions of data. So I'm worried if I should clear fruits (fruits.clear())?

A: If doSomething is synchronous - which it appears to be - then no, clearing the set won't help.
The situation in which clearing the set might help if the set would otherwise remain accessible to the code for a number of seconds after it stops processing. The garbage collector usually runs a bit after when the synchronous JavaScript has finished executing. (It will not run while the synchronous JavaScript is still executing.)
Since doSomething is synchronous, once that function ends, as long as the Set isn't used elsewhere (like being returned), fruits will not be accessible to anything else - resulting in the engine automatically garbage collecting it some time after things go idle. So, in that situation, whether or not you do fruits.clear() wouldn't matter because the garbage collector won't run until after the function ends anyway, and because the garbage collector will be able to see that fruits isn't referenced anywhere else after the function ends.
An example snippet in which clearing the set could help:
async function doSomething(fruitsA: string[], fruitsB: string[]) {
  const fruits = new Set(fruitsA.concat(fruitsB))
  const myRottenFrutis = rottenFruits.filter((fruit) => fruits.has(fruit))
  fruits.clear()
  await new Promise(res => setTimeout(res, 20_000));
  // more code here
}

If script execution essentially pauses while waiting for the timeout, there's idle time during which the garbage collector might kick in. (But it's not guaranteed.)
That said, such a massive data comparison is somewhat odd to do in JavaScript, rather than in, for example, SQL of a database, which is more optimized to processing large amounts of data.


text:
Q: Google Analytics Event Tracking - Minimal Interval between the events I want to track multiple events using GA _trackEvent method across multiple domains.
Because of the nature of the report I want to generate, I must do something like this:
for (var i=0; var < books.length; i++)
{
   //showing values for current books[i]
   _gaq.push(['_trackEvent', 'Books Displayed', 'Fantasy', 'Lord of The Rings']);
}

So, when my books list is populated I want to send appropriate GA event. It is important that I send each item separately so I can drill-down on Event Dashboard to preview all items in 'Fantasy' category and so on.
Note, books list is never longer than about 10 items.
The problem I'm experiencing at the moment is that for no good reason Google code is ignoring some of my requests. The way how Google event tracking works, is that with every call to _trackEvent, Google is dropping gif on the page:
http://www.google-analytics.com/__utm.gif

that has loads of parameters, and one of them - utme contains my data:
__utm.gif?utmt=event&utme=5(Books%20Displayed*Fantasy*Lord%20of%20The%20Rings)

Using Fiddler (or Firebug Net tab) I can check if this request is really coming out from the browser.
Unfortunately, it seems like every time about half of my requests are completely ignored by google and _trackEvent is not translated to __utm.gif call.
I have a feeling it has something to do with the frequency of the _trackEvent call. Because I am using them inside a for loop, all events are spawned with minimal interval between. It seems like Google doesn't like it, and ignores my calls.
I did test it, adding 2 seconds interval between each call and it worked. But this solution is unacceptable - I can't make user wait for 20 seconds to send all events.
Unfortunately this flaw makes GA Event Tracking completely useless - I can't just "hope" GA code will correctly record my event because the report won't be precise. The worst thing about it is that there is no proper documentation on Google saying what is the maximum allowed number of requests per second (they only state that max request per session is 500 what is a lot more than what I generate anyway).
My question is - did you experience similar problems with Google Event tracking before and how did you manage to fix it? Or does it mean I must completely abandon GA Tracking because it will never be precise enough?

A: First off, I want to point out that the 500 limit per session is for all requests to Google, not just for events. So that includes any other custom tracking you are doing, and that also includes normal page view hits.
This to me sounds more like a general js issue than a GA issue. Something along the lines of you pushing code for GA to process faster than it can process so some are falling through the cracks.  I don't think there really is anything you can do about that except for delay each push as you have done...though I think you could probably lower that interval from 2s to maybe as low as 500ms...but still, that would at best drop you down to a 5 second wait, which IMO is a lot better than 20s but still too long.
One solution that might work would be for you to skip using _gaq.push() and output an image tag with the URL and params directly for each one. This is sort of the same principle as the "traditional" GA code that came before the async version, and is what most other analytics tools still do today.
If you want my honest opinion though...in my experience with web analytics, I think the most likely thing here is that you need to re-evaluate what you are tracking in the first place.
Judging by the context of your values, (and this is just a guess) it looks to me like you have for instance a page where a user can see a list of books, like a search results page or maybe a general "featured books" page or something similar, and you are wanting to track all the books a user sees on that page.
Based on my experience with web analytics, you are being way too granular about the data you collect.  My advice to you is to sit down and ask yourself "How actionable is this data?" That is, after all, the point of web analytics - to help make actionable decisions.
All day long I see clients fall into the trap of wanting to know absolutely every minute detail about stuff because they think it will help them answer something or make some kind of decision, and 99% of the time, it doesn't.  It is one thing to track as an event individual books a user views, like an individual product details page, where you'd be tracking a single event.
Or for search results page...track it as a "search" event, popping stuff like what the term searched was, how many results given, etc.. but not details about what was actually returned.
I guess if I knew more details about your site and what this tracking is for, I could maybe give you more solid advice :/

A: This is probably due to the 1 event per second limit
"Events Per Session Limit
In addition to general collection limits and quotas, the following limit applies to event tracking in ga.js:
The first 10 event hits sent to Google Analytics are tracked immediately, thereafter tracking is rate limited to one event hit per second.
As the number of events in a session approaches the collection limit, additional events might not be tracked. For this reason, you should:
avoid scripting a video to send an event for every second played and other highly repetitive event triggers
avoid excessive mouse movement tracking
avoid time-lapse mechanisms that generate high event counts
(from https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide)
That is why your 2 seconds delay works. You can theoretically cut that in half, though a factor of safety would probably reduce that cut.


text:
Q: get value of selected checkbox from different questions I am making a online test website in which there are multiple questions . I have check box for selecting the answers . There are more then one question . The problem is how to get the values of the selected checkbox for each question's answers and send them in a form such as
suppose there are four options in first question (a,b,c,d) and question id is 2 . then when a user selects the option b,c then the data should be get via jquery and stored in a variable . I have used each for this . my code is
            var chkArray = [];
            var chkQues = [];
            var answer;
            $(".answer_chk_box:checked").each(function() {
                chkArray.push($.trim($(this).val()));
                chkQues.push($.trim($(this).attr("qid")));
                //alert(chkQues);
            });
            answer = chkArray.join(',');
            Question_id=chkQues

this works fine if there is only one question . the value for answer is "b,c" and question_id is 2 . But when there are multiple questions . everything gets messed up . How can we get values for multiple questions separate such that for one question's answer we can send one ajax call properly .

A: I say you simply create an object to describe a Question and Answer pair.
http://jsfiddle.net/zGQH5/2/
function getQandAs(){
  //Object array to store all of our data
  var questionsAndAnswers = [];
  $(".answer_chk_box:checked").each(function() {
      //This object represents a question ID and all of its selected answers
      var questionAnswer = new Object();
      questionAnswer.answer = $.trim($(this).val());
      questionAnswer.questionId = $.trim($(this).attr("qid"));
      questionsAndAnswers.push(questionAnswer);
  });

  //these lines just demo it working
  $(questionsAndAnswers).each(function(index){
      alert(questionsAndAnswers[index].answer + " & " + questionsAndAnswers[index].questionId);
  });
}

A: just use name="field[]" on the checkbox field:
<form id="questions">

      <input type="checkbox" name="question-1-choice[]" value="A" />
      Choice A

      <input type="checkbox" name="question-1-choice[]" value="B" />
      Choice B

      <input type="checkbox" name="question-1-choice[]" value="C" />
      Choice C

      <input type="checkbox" name="question-2-choice[]" value="A" />
      Choice A

      <input type="checkbox" name="question-2-choice[]" value="B" />
      Choice B

      <input type="checkbox" name="question-2-choice[]" value="C" />
      Choice C

</form>

A: create 2D array of options including questions id rand answer id.
var chkArray = [][];
 $(".answer_chk_box:checked").each(function() {
                chkArray.push($.trim($(this).attr("qid")), $.trim($(this).val()));

            });

A: First of all using custom attributes is not recommended. It is better to use data attributes. So you have inputs like this:
<input type="checkbox" value="something" data-qid="1" class="answer_chk_box" />

You should collect all the answers into hash:
var answers = {};
$(".answer_chk_box:checked").each(function() {
    var qid = $(this).data('qid');
    var answer = $.trim($(this).val());
    if(!answers[qid]){
        answers[qid] = [];
    }

    if(answers[qid].indexOf(answer) === -1){
        answers[qid][] = answer;
    }
});

//console.log(answers);


text:
Q: javascript removing all clones var counter = 0;

function moreFields() {
     counter++;
     var newFields = document.getElementById("input").cloneNode(true);
     newFields.id = counter;
     newFields.style.display = 'block';
     var newField = newFields.childNodes;
     for (var i=0;i<newField.length;i++) {
         var theName = newField[i].id;
         if (theName) {
             newField[i].id = theName + counter;
            }
        }
     var insertHere = document.getElementById("buttons");
     insertHere.parentNode.insertBefore(newFields,insertHere);
}

function clearData() {
     var pricetxt = document.getElementById('price1');
     pricetxt.value = "";
     var qtytxt = document.getElementById('qty1');
     qtytxt.value = "";
     while (counter > 0) {
         var cell = document.getElementById("input"+counter);
         cell.parentNode.parentNode.removeChild(cell.parentNode)
         counter--;
        }
     counter = 1;
}

window.onload = moreFields;

JSFiddle
I would like to delete all of the clones that were dynamically created by the first function when a button is pressed.
I used this to base my script. I know that I could take the easy way out (the way they do it) but I want to learn how to do it this way.
All answers are much appreciated!

A: Well you have a counter, so just delete all nodes up to the counter value and then reset it.
function startOver() {
    var element;
    for (var i = 1; i <= counter; i += 1) {
        element = document.getElementById(i);
        if (element.parentNode) {
            element.parentNode.removeChild(element);
        }
    }
    counter = 0;
    moreFields();
}

Demo: http://jsfiddle.net/AXUbP/1/


text:
Q: Adding a tracer to the surface of a water droplet I have a 2 mm water droplet generated by a syringe and falling down. I am using two perpendicular cameras to capture simultaneous frames from it. I need to track the droplet during the time and reconstruct it (through consecutive frames). However, only the border of the droplet (which is an ellipse) is distinguishable in each frame and I do not have any traceable point on the surface of the droplet to use it as a tracer (each point on the droplet surface will give me a point inside the corresponding ellipse on each frame). I want to add one or few very small particles/tracers in the order of my pixel dimension (e.g. 0.05 mm or even less which are still detectable through my cameras) such that while the droplet wobbling or revolving during falling down, always remain on the surface of the droplet and don't go inside it. Which material or technique do you think is more appropriate for this purpose?
Please let me know if you know any reference or paper used your suggestion.
for more information please see this Phys.SE question as well.

A: I would consider using water with a dye like a deep blue to be nearly opaque. Illuminate with an array of LEDs. Each bright spot reflected from the droplet is an LED. You can add a few strategic red LEDs among all white as reference.
Working out the most convenient geometry will tell if you need the LEDs on some curved surface in space or if a flat panel will do. I think you can get pretty good data this way and quite high resolution as far as number of points on the drop.

A: There may be some problems with Teflon particles. Prior to droplet separation from the syringe, the Teflon particle can roll down along the surface of the droplet, so you'll only have your tracer at the bottom of the droplet. This movement of the particle along the surface will not take place when the droplet is in free fall. This movement will be less important for small particles, but it is more difficult to register a very small particle by a camera. So you may wish to consider using phosphorescent particles (http://www.cospheric.com/PHYGPMS_phosphorescent_yellowgreen_microspheres.htm ; see their note on the surfactant).


text:
Q: Laravel controller return model instance instead data content i have this route:
Route::group(['prefix' => 'comments', 'middleware' => ['auth:api']], function(){
    Route::delete('/delete/{id}', [CommentController::class, 'destroy'])->name('comment.delete');
});

in my controller i have
public function destroy(Comments $comments)
    {
        dd($comments);
    }

normally i must have the data of respective of the id right? but instead i got empty instance of the model

A: To work you need to change route parameter from id to comments

Laravel automatically resolves Eloquent models defined in routes or
controller actions whose type-hinted variable names match a route
segment name.

Route::delete('/delete/{comments}', [CommentController::class, 'destroy'])->name('comment.delete');

Read here : https://laravel.com/docs/8.x/routing#implicit-binding.


text:
Q: Chrome JavaScript Debugging - how to save break points between page refresh or break via code? When using Chrome and it's JavaScript debugger, every time I reload my page / scripts, my breakpoints are lost and I have to go find the script file in the pop-up, find the line of code for my break point, click to add it, etc.
Is there a way to save these breakpoints so it breaks even after a page refresh (other debuggers I have used do this)?
Alternatively, is there a clean way in my JavaScript code I can type something to tell chrome to start tracing (to pause on a line)?

A: You can put a
debugger;

to break in most of the JavaScript environments. They will persist for sure. It's good to have a minifier that rids the debugger and console.log calls for the production environment, if you are using these.
In the recent versions of Chrome browser, there is a "Preserve Log" option on the top of the console panel, next to the filters. In the older versions, right clicking on the empty console window will bring that option ("Preserve log upon navigation"). It's handy when you don't have console.log statements or hard-coded debugger calls.
update: I found a tool on github, called chimney, which takes a file and removes all the console.log calls. it gives a good idea about how to remove debugger calls.

A: Set your breakpoints, switch to the Network tab and select the Preserve Log Upon Navigation toggle button. Now the breakpoints should be there when you refresh.
Or the JavaScript way is to use
debugger;

A: Also, do you send your JavaScript file(s) from the server to the client with an attached query parameter to the URL with the current Epoch time? This is used to prevent caching of the JavaScript file(s).
When this is the case, it seems like the Chrome Developer Tools interprets the file to be a different one after the refresh, which will (correctly) remove the breakpoints.
For me, removing the query parameter made the CDT keep the breakpoints after refresh.

A: You can use the debugger; statement in your source to make the debugger break there.

A: For people using ExtJs 6.x:
instead of disableCaching in the Ext.Loader you could add a "cache" or "disableCacheBuster" query parameter to the page's URL. This will remove the "_dc" parameter from the file and enable chrome debugger to persist the breakpoint.
See bootstrap.js in your application (config parameter disableCaching).

A: This is probably happening for scripts that you're dynamically loading or evaluating from other scripts?  I can say for myself that this scenario really irritated me until I discovered the sourceURL property.  Placing the following specially formatted comment on the last line of the script you want to debug will 'anchor' it within Chrome so it has a frame of reference for it:
//# sourceURL=filename.js
Your manually-placed breakpoints will now persist between page loads!  The convention actually originated from the sourcemap specification, but Chrome at least honors it as a standalone technique.  Here's a reference.

A: Chrome Developer Tools should behave the way you expect but you can put debugger; statements in your (development!) code to pause the execution.

A: You can put debugger; before the code where you want to start debugging. Once the page starts loading,it would stop at the debugger; statement. Then you can easily apply the debugging point as per your requirement.

A: As said by @jtrick, use the comment:
//# sourceURL=filename.js
it is the best way to obtain the persistence of breakpoints between page refreshes and also between closing and reopening of chorme, even in versioned  (to have control over browser cache) or dynamically included javascript/css files.
This is the updated reference link:

While not part of the Source Map spec, the @sourceURL allows you to
make development much easier when working with evals. This helper
looks very similar to the //# sourceMappingURL property and is
actually mentioned in the Source Map V3 specifications.
By including the following special comment in your code, which will be
evaled, you can name evals and inline scripts and styles so they
appear as more logical names in your DevTools.
//# sourceURL=source.coffee

If you have a server-side cache for the versioned files served to the browser, you can append the comment in the source code at the time of the cache generation, without having to modify the original source files.
NOTE: on the comment you can also specify a virtual path to the file, this way you can organize your dynamically loaded or versioned content on a tree displayed in chrome devtools > navigator panel > sources > page treeview. I.e.:
//# sourceURL=https://yourdomain.com/libs/ui/widget.js


text:
Q: release version of app throwing c1083 cannot open include file error I have a project that I have been running in debug mode and compiles and works fine.  However, when I try and do a release version I now get the following error:
"fatal error C1083: Cannot open include
 file: 'QtCore/qchar.h': No such file or directory
 f:\testing_dev\repo\hello_test\Qt\4.6.0\src\corelib\tools\qstring.h
 45 HelloWorld"

I am wondering why it works in debug but not in release and how to remedy it?
Thanks.

A: The compiler settings are different for each build configuration.
You have probably set the Additional Include Directories setting in the Project Properties for the Debug configuration but not for the Release configuration.


text:
Q: How to change mimetype of google drive files using java     try {
        log.info(contentType + " " + title + " " + parentId);

        com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();

        body.setName(title);
        body.setMimeType("application/vnd.google-apps.document");
        List<String> parents = Arrays.asList(parentId);
                        body.setParents(parents);
    com.google.api.client.http.AbstractInputStreamContent in1 = new AbstractInputStreamContent(
                contentType) {

            @Override
            public boolean retrySupported() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public long getLength() throws IOException {
                // TODO Auto-generated method stub
                return inputStream.available();
            }

            @Override
            public InputStream getInputStream() throws IOException {
                // TODO Auto-generated method stub
                return inputStream;
            }
        };

        com.google.api.services.drive.model.File file = getDriveClient()
                .files().create(body, in1).setFields("id, webContentLink, webViewLink, parents").execute();
        System.out.println("File ID:::::::::::::: " + file.getId());

        return file;
    } catch (Exception exp) {
        exp.printStackTrace();
    }
    return null;
}

when i am using this mimetype ,i am getting an error as
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)

I am using googledrive V3 Api and i want open my files in google docs.So, i am using this mimetype.If u want refer this url
https://developers.google.com/drive/api/v3/mime-types
plz suggest me what the reason for this error or any code.


text:
Q: Spring MCV - Removing element for DOM not resulting null because int Person Object
public class Person {
    public Person() {

    }

    @Id
    @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int personId;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="tb_person_phonelist", joinColumns={ @JoinColumn(name="person_id", referencedColumnName="person_id") }, inverseJoinColumns={ @JoinColumn(name="phonelist_id", referencedColumnName="phonelist_id") })
    private List<PhoneList> phoneList = LazyList.decorate(new ArrayList<PhoneList>(), FactoryUtils.instantiateFactory(PhoneList.class));

//getter & setter
}

PhoneList Object
public class PhoneList {
    public PhoneList() {

    }

    @Id
    @Column(name="phonelist_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int phoneListId;
    @Column(name="provider")
    private String providerName;
//getter & setter
}

So far I'm successfull to load, add new, and edit in the project. but for deletion I'm still confused. So far what I do is by deleting the DOM using
jquery (Please note that the scenario of deletion can't be postback to server, so i need to use javascript to manipulate the object via DOM manipulation)
let say the generated bind is

<input name="personEntity.phoneList[1].phoneListId" id="personEntity.phoneList1.phoneListId" type="hidden" abp="257" value="24"/><input name="personEntity.phoneList[1].providerName" class="form-control" id="inputProviderName" type="text" placeholder="Provider Name" abp="268" value=""/>

so what do is just
$('tr').remove();

assuming that removing the DOM makes the object will be changed depend on the latest DOM.
but when i submit/post into the controller, the phoneList object is not empty, I suspect it because phoneListId is type integer, which it will never be null.
is there any way to make it null?

A: It never should be empty what here happening is you are using here container must be creating some model object here ,by which you are getting your form data.
so its first creating a object and initialize its properties to default values and than its passing it to container
that's why its not empty you need to check if phone list is having value 0 which is integer have default 0 values you should delete it .


text:
Q: How to prove that a dynamic programming algorithm is a monotonic function I've written an algorithm, which is based on the Needleman-Wunsch algorithm for matching sequences of proteins. This algorithm is a dynamic programming approach, where the optimal matching of two sequences A and B, with length m and n is being calculated by first solving the same problem for the respective substrings.
Currently I'm working on a proof of optimality and one lemma I (think I) need to prove first, is that my algorithm (lets call it A) always yields a score which is higher or equal to the score, than when applying the algorithm to substrings of A and B.
These are my main problems:

*

*The algorithm/function has two dimensions (the "size" of the two substrings)

*Every cell value of the value matrix used in the algorithm is defined to be the maximum of some values, based on values calculated before (overlapping subproblems)

I've found some help regarding multidimensional induction in a blogpost, but I don't know how to approach the max-function.
It would be great if you could give me a hint or a topic I should read about!
Thanks in advance,
das_weezul
EDIT:
Here is a simplified version of the algorithm (Lets call it MATCH). $a_m$ is the m-th symbol of string A, and $b_n$ is the n-th symbol of string B. $SIM(a_m,b_n)$ is the similarity of $a_m$ and $b_n$, which is 1 if $a_m$ and $b_n$ are equal and -1 if not:
$
SIM(a_m,b_n) = \begin{cases}
1, a_m = b_n\\
-1, otherwise
\end{cases}\\
MATCH(0,0) = 0\\
MATCH(0,n) = 0\\
MATCH(m,0) = 0\\
MATCH(m,n) = max \begin{cases}
MATCH(m-1,n-1)+ sim(a_m,b_n)\\
MATCH(m,n-1)\\
MATCH(m-1,n)
\end{cases}
$
What I want to show is something like this:
$MATCH(m-i,n-j) \leq MATCH(m,n), 0 \leq i \lt m \wedge 0 \leq j \lt n $

A: Isn't that obvious?
$$
MATCH(m,n) = max \begin{cases}
(a): MATCH(m-1,n-1)+ sim(a_m,b_n)\\
(b): MATCH(m,n-1)\\
(c): MATCH(m-1,n).
\end{cases}
$$
Apply (b) recursively, we get
\begin{align}
MATCH(m,n) &\ge MATCH(m,n-1)\\
&\ge MATCH(m,n-2)\\
&\ge \ldots\\
&\ge MATCH(m,n-j).
\end{align}
Now apply (c) recursively and get
\begin{align}
MATCH(m,n-j) &\ge MATCH(m-1,n-j)\\
&\ge MATCH(m-2,n-j)\\
&\ge \ldots\\
&\ge MATCH(m-i,n-j).
\end{align}
Put this two sequences of inequalities together, we obtain
$$MATCH(m,n)\ge MATCH(m-i,n-j).$$
In other words, you first traverse from the node $(m,n)$ horizontally to the left until you reach $(m,n-j)$, then traverse vertically down to the node $(m-i,n-j)$. By the defintion of the $MATCH$ function, the value of the node will decreases along this path.

A: user1151 showed a lot of patience and pushed me into the right direction, so this answer is just for the sake of completeness. Here is the proof I'm using now, feel free to add comments on how to improve it!
Lemma (Monotonicity)
$
MATCH(m,n) \geq MATCH(m-1,n-1), 0 \lt i \leq m \wedge 0 \lt j \leq n
$
Proof
Case 2 max
Per definition: $MATCH(m,n) = MATCH(m-1,n)$
Case 3 max
Per definition: $MATCH(m,n) = MATCH(m,n-1)$
Case 1 ($a_m \equiv b_n \Rightarrow SIM(a_m,b_n) = 1$) max
$MATCH(m,n) = MATCH(m-1,n-1) + 1 \Rightarrow MATCH(m,n) \gt MATCH(m-1,n-1)$
Case 1 ($a_m \neq b_n \Rightarrow SIM(a_m,b_n) = -1$) max
$
MATCH(m,n) = MATCH(m-1,n-1) - 1 \\
$
$
\Rightarrow MATCH(m-1,n-1) -1 \geq MATCH(m-1,n) \\
\wedge MATCH(m-1,n-1) -1 \geq MATCH(m,n-1)
$
$
\Rightarrow MATCH(m-1,n-1)  \gt MATCH(m-1,n) \\
\wedge MATCH(m-1,n-1)  \gt MATCH(m,n-1) \\
$
$
MATCH(m-1,n) \lt MATCH(m-1,n-1) \\
\Rightarrow\Leftarrow MATCH(m-1,n) = MATCH(m-1,n-1)
$ (Contradiction to Case 2 max)
$
MATCH(m,n-1) \lt MATCH(m-1,n-1) \\
\Rightarrow\Leftarrow MATCH(m,n-1) = MATCH(m-1,n-1)\\
$ (Contradiction to Case 3 max)
Q.E.D
The last part of the proof shows that the algorithm will never match two different symbols.


text:
Q: Highcharts - area "appearance" but not start at 0 This might be a strange request but is it possible to have a single line chart "display" as area, as in have the shaded part below the line, however not rescale the y axis from 0?
So for example this chart: http://jsfiddle.net/29shP/1/
Is chart type line...

But if I change type: 'area'
Then it displays like this:

Is it possible for the series to stay as it is in the first image, but with the shaded colour below?
Thanks

A: I advice familiar with this https://github.com/highslide-software/highcharts.com/issues/1401 thread which describe this issue.
Here is the answer given in the thread:
The difference is that the threshold is set to 0 by default for areas. You'll find the same for columns. See http://api.highcharts.com/highcharts#plotOptions.area.threshold. You can disable that behaviour by setting the threshold to null.

A: yes you can do that
highcharts allow you to keep separate series options in the navigator there you can change
navigator: {
            series: {
                data: ADBE,
            type: 'line'
            }
        },

here is a jsfiddle for your reference  http://jsfiddle.net/GhA5d/
updated your fiddle at http://jsfiddle.net/29shP/2/
Hope this will be useful for you

A: Use "min"
yAxis: {
            startOnTick: false,
            endOnTick: false,
            min: 0
        },

Example: http://jsfiddle.net/29shP/4/
If you want multiple yAxis min, you can do this:
yAxis: [{
            min: 0
            },
        {
            min: 0
}],

Check this: Highcharts - Multiple Y Axis Stacked Charts (include jsFiddle in comments)


text:
Q: JavaScript, Google Sheets script - problem with date comparing I am new in Apps Script, and had never a chance previously to write in JavaScript.
So, I have a dataset in one sheet in Google about personal information of clients (ID, name, mail, contact). I have another dataset in another Sheet about clients payment (date of payment of the first installment, date of payment of the second installment and amount.
The last sheet that is in focus is the third one relating to unpaid bills.
Now, what I want is to copy columns about personal information from the first sheet into the third one. Here condition would be to copy only information about clients where difference between date of payment of the second installment and today() is greater than 45. Here is what I have tried:

function Neplacena2Novi() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheetFrom=ss.getSheetByName("Podaci o polaznicima"); //Data entry Sheet
var sheetTo=ss.getSheetByName("Neplaceni racuni"); //Data Sheet
var condition=ss.getSheetByName("Uplate novoupisani");
var range1=ss.getRangeByName("Prva rata");
var range2=ss.getRangeByName("Druga rata");

var startRow=3;
var endRow=ss.getLastRow();

function Neplacena2Novi(){
  for var(i=startRow; i<(endRow+1)< i++) {
  var startDate=new Date(condition.getRange(range1+1).getValue());
  var endDate= new Date(condition.getRange(range2+1).getValues());

  var difference=parseInt(endDate-startDate)/1000); //Dates are in format dd.mm.yyyy.
      if(difference>45){

      var values=sheetFrom.getRange(2, 1, sheetFrom.getLastRow(), 4).getValues();

      sheetTo.getRange(3,1,1184,4).setValues(values);
      }
}
var ui = SpreadsheetApp.getUi();
var potvrda = ui.alert("Odredili ste lica koja treba da se pozovu.");
}

function DugmeDodajKlijenta (){
var ui = SpreadsheetApp.getUi();

}

This code works but I didn't get anything in sheet! And I didn't now how to include today() function in formula for difference. But what I really want is to make a condition where difference would be today()-startDate().
Can someone please help me?

A: The code is not working because endDate is not a primitive value but a 2D array. Use Range.getValue() instead of Range.getValues(), like this:
  const startDate = new Date(condition.getRange(row, startDateColumn).getValue());
  const endDate = new Date(condition.getRange(row, endDateColumn).getValue());

...but that is not enough to make the code work. There is a syntactical error in the for loop line, and the i variable is not referenced in the loop. The whole thing is very inefficient because it reads and writes data row by row instead of doing just one read and just one write.
The new Date() calls are superfluous unless the "dates" in the spreadsheet are not numeric dates but text strings that just look like dates. The parseInt() call is also superfluous (plus, it is missing the radix parameter.)
JavaScript dates internally contain  the number of milliseconds that have elapsed since 1 January 1970 0:00 UTC. To get the difference between two dates in days, try (endDate-startDate) / 1000 / 60 / 60 / 24. Note that there are many caveats — see Date.
The whole loop could be replaced with Range.getValues().filter(). It looks like the code should best be totally rewritten.
It is unclear why you would need a script in the first place, since the same can be done with a spreadsheet formula using e.g. filter() or query(). The personal info can be added to the missing payments data with a lookup e.g. arrayformula(vlookup()).


text:
Q: when i try to use npm to install some package in my win8, it always gives me error like this
This example shows the bcrypt package. But my friends tells me it installs ok on a macbook. Anyone know how to fix this?

A: node.bcrypt.js depends on node-gyp to compile it's native modules. Unfortunately, node-gyp has further dependencies on Python and Visual Studio C++, which are not installed on Windows by default. You'll need to install those dependencies manually before node-gyp will work. See the node-gyp installation guide for further details.
node.bcrypt.js is well-known for being hard to install on Windows. An alternative, much easier work-around is to use bcrypt.js, which is a drop-in replacement for node.bcrypt.js. It has no dependency on node-gyp, as it has no native modules.


text:
Q: Position navbar on the vertical center of a div I need to do something like this:

I have written this code:
HTML:

  <title>{% block title %} {% endblock %}</title>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="{{ url_for('static', filename='styles/style.css')}}">

        home

        account_box

        settings

        work

        email

  {% block content %}
  {% endblock %}

CSS:
html{
    margin-left: 75px;
}

.nav{
    position: fixed;
    left: 0;
    width: 75px;
    height: 100%;
    background: #181818;
    font-size: 16px;
    font-family: sans-serif;
}

.menu{
    justify-content: center;
}

.menu__item{
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px 0;
    text-decoration: none;
    color: #a5a5a5;
    transition: background 0.3s;
}

However, the navbar is still showing up at the top of the parent div:

Does anyone know how I can fix this issue? What am I doing wrong. I usually don't work in html and css so this is probably something quite simple.
NOTE: I am using a python framework to manage the html so don't question the {% %} parts in the code. They are not the reason this is not working.


text:
Q: Titanium - uisegmentedcontrol I'm trying to do something in titanium that is similar to the iphone uisegmentedcontrol
I'm currently using buttons in arrays but it's not an efficient method if there needs to be position shifting. Because position shifting would require me to go to each button to shift them.
So there's a huge problem with alignment.
Is there a way to implement uisegmentcontrol in titanium? Google doesn't give me anything related to titanium.

A: You can use the TabbedBar for this purpose.
var segment = Titanium.UI.iOS.createTabbedBar({
    labels:['One', 'Two', 'Three'],
    backgroundColor:'#336699',
    top:50,
    style:Titanium.UI.iPhone.SystemButtonStyle.BAR,
    height:25,
    width:200
});
myWindow.add(segment);

Please check these links for more options:

*

*TabbedBar

*ButtonBar


text:
Q: Como restringir o valor da variável com apenas duas casas decimais? Quero o r com apenas duas casas decimais.
double r = Math.abs ((aux5 - ((aux1*aux2)/previsoes.length))/ (Math.sqrt(Math.abs((aux3 - ((aux1 * aux1) / previsoes.length)) * (aux4 - ((aux2 * aux2) / previsoes.length))))));

A: Você pode utilizar esses dois métodos que deixam os valores truncados
Se você quer que o resultado for um double:
public static double truncate(double value) {
    return Math.round(value * 100) / 100d;
}

Se você quer um String:
public static String truncate(double value) {
    DecimalFormat df = new DecimalFormat("#.00");
    return df.format(value);
}

Agora é só chamar o método passando como atributo o valor de r, que ele será transformado para um valor com apenas duas casas depois da virgula


text:
Q: How to construct a mathematical formula corresponding to the index with the presented values I have this function to centralize a item in Flatlist (horizontal):
centralizeItem = (index) => {
 const WIDTH = scale(95)
 let centerSize

 if (index === 0) centerSize = (WIDTH*1.5) * -1

 if (index === 1) centerSize = (WIDTH/2) * -1

 if (index === 2) centerSize = (WIDTH/2)

 if (index === 3) centerSize = (WIDTH*(index/2))

 if (index === 4) centerSize = (WIDTH*(index/2+0.5)) // 2.5

 if (index === 5) centerSize = (WIDTH*(index/2+1)) // 3.5

 if (index === 6) centerSize = (WIDTH*(index/2+1.5)) //4.5

  return centerSize
}

This formula return a Offset value to scroll in y-value using
this.refs.listRef.scrollToOffset({offset: this.centralizeItem(index) })

The above code fires when the item is selected
But, the Flatlist render a lot of data, not just 7 index, and this formula are impracticable.
I need a formula that follow the variations above in the function

A: You could take a formula and calculate the factor.
centralizeItem = index => scale(95) * (index - 1.5);