text:
Q: Oracle - using is not null inside Case when.... then.... inside Where i am here to ask again
i being confused with Oracle , its seems that when i use is null inside a case when function , it wont work , my code is like this :
it went wrong around the
"CASE WHEN :idSalesman is not null then enabled = null and deleted=0 else enabled =1 and deleted =0" condition
SELECT a.id_outlet as idOutlet , a.name , a.plant as plant, a.segment, a.street1 as alamat, a.nota_retur
 FROM (SELECT id_outlet, name, plant, segment, street1, nota_retur FROM outlet WHERE plant = :idPlant
 AND (id_outlet || ' ' || name || ' ' || street1) like :request
 AND enabled = 1 AND deleted = 0 and rownum = :limits ) a
 INNER JOIN wilayah_kerja b ON b.id_salesman = nvl(:idSalesman, b.id_salesman) AND  b.id_outlet = a.id_outlet
 AND b.enabled = 1 AND b.deleted = 0
 GROUP BY a.id_outlet
 UNION
 SELECT
    A.Id_Outlet AS Idoutlet,A.Name,A.Plant AS Plant,A.Segment,A.Street1 AS Alamat,A.Nota_Retur
FROM ( SELECT Id_Outlet,Name,Plant,Segment,Street1,Nota_Retur
        FROM Outlet
    WHERE Plant =:Idplant
    AND (CASE WHEN :idSalesman is not null then enabled = null and deleted=0 else enabled =1 and deleted =0 )
    AND rownum >=:limits
    AND (Id_Outlet || ' ' || Name || ' ' || Street1) LIKE :Request
    )a
 LEFT JOIN wilayah_kerja b ON b.id_outlet = a.id_outlet
 and rownum = :limits
 AND b.enabled = 1
 AND b.deleted = 0
 WHERE B.Id_Outlet Is NULL Group By A.Id_Outlet Order By Name Limit 10;

i tried to change the union to :
 SELECT a.id_outlet as idOutlet , a.name , a.plant as plant, a.segment, a.street1 as alamat, a.nota_retur
 FROM (SELECT id_outlet, name, plant, segment, street1, nota_retur FROM outlet WHERE plant = :idPlant
 AND (id_outlet || ' ' ||  name || ' ' || street1 ) like :request
 AND rownum = :limits
 AND enabled = 1 AND deleted = 0 AND NVL(:idSalesman , enabled = null AND deleted = 0))a
 LEFT JOIN wilayah_kerja b ON b.id_outlet = a.id_outlet AND b.enabled = 1 AND b.deleted = 0
 WHERE B.Id_Outlet Is NULL Group By A.Id_Outlet Order By Name Limit 10

using NVL2 , but it give me error near "a"
NVL(:idSalesman , enabled = null AND deleted = 0))a

A: Oracle doesn't support a separate boolean type in SQL statements.  One problem (at least) is:
WHERE Plant = :Idplant AND
      (CASE WHEN :idSalesman is not null then enabled = null and deleted = 0 else enabled = 1 and deleted = 0 ) AND
      rownum >= :limits AND
      . . .

The solution is just to phrase this as boolean logic:
WHERE Plant = :Idplant AND
      deleted = 0 AND
      (:idSalesman is not null and enabled is null OR
       :idSalesman is null and enabled = 1
      ) AND
      rownum >= :limits AND
      . . .

Also note that = null is not a valid comparison (unless you never want something to evaluate to true).


text:
Q: Pull out sections from XML in Python Please note that I have some Python experience but not a lot of deep experience so please bear with me.
I have a very large XML file, ~100 megs, that has many, many sections and subsections.  I need to pull out each subsection of a certain type (and there are a lot with this type) and write each to a different file.  The writing I can handle, but I'm staring at ElementTree documentation trying to make sense of how to traverse the tree, find an element declared this way, yank out just the data between those tags and process it, then continue down the file.
The structure is similar to this (slightly obfuscated).  What I want to do is pull out each section labeled "data" individually.
<filename>
    <config>
        <collections>
        <datas>
            <data>
            ...
            </data>
            <data>
            ...
            </data>
            <data>
            ...
            </data>
        </datas>
        </collections>
     </config>
</filename>

A: I think you can read in each data element using iterparse and then write it out, the following simply prints the element using the print function but you could of course instead write it to a file:
import xml.etree.ElementTree as ET
for event, elem in ET.iterparse("input.xml"):
  if elem.tag == 'data':
    print(ET.tostring(elem, 'UTF-8', 'xml'))
    elem.clear()

A: Consider an XSLT solution with Python's third-party module, lxml. Specifically, you xpath() for the length of <data> nodes and then iteratively build a dynamic XSLT script parsing only the needed element by node index [#] for outputted individual XML files:
import lxml.etree as et

dom = et.parse('Input.xml')
datalen = len(dom.xpath("//data"))

for i in range(1, datalen+1):

    xsltstr = '''<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output version="1.0" encoding="UTF-8" indent="yes" />
    <xsl:strip-space elements="*"/>

    <xsl:template match="datas">
        <xsl:apply-templates select="data[{0}]" />
    </xsl:template>

    <xsl:template match="data[{0}]">
        <xsl:copy>
            <xsl:copy-of select="*"/>
        </xsl:copy>
    </xsl:template>
    </xsl:transform>'''.format(i)

    xslt = et.fromstring(xsltstr)
    transform = et.XSLT(xslt)
    newdom = transform(dom)

    tree_out = et.tostring(newdom, encoding='UTF-8', pretty_print=True,
                           xml_declaration=True)

    xmlfile = open('Data{}.xml', 'wb')
    xmlfile.write(tree_out)
    xmlfile.close()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove colored lines on XML edditor I don't know why but the empty lines on the xml editor of android studio are colored dark green, could you please tell me how to remove this feature?
Also, there is black square box on the start of the line 88 (see photo), could you please tell me what it is?
Thank you very much in advance..![Colored Lines]

A: Ok, I've found how to disable it. Preferences -> Editor -> Color & Fonts search for Injected language fragment and uncheck background.
edit: I have found another question similar with this one: The exact answer was: The green lines show areas interpreted by IDE as different language injection.
In those areas you end up with different code completion rules etc.
So assuming you used the language injections by mistake, clicking the lightbulb and choosing "Un-inject Language/Reference" removes those areas.
It's quicker than going through the settings and prevents any inconsistent highlighting and code completion when editing the file later.


text:
Q: Postgresql - password authentication failed for user Well, I've been working on a project on Django, but a friend of mine was facing a problem so he sent me his project (The entire folder). Anyway, I tried to run the server but it didn't work. I tried to change the password and the username from the settings file, and when I tried to access the user, the username was changed (as the sql shell recognized it, I think ¯_(ツ)_/¯), but whenever I try to login with the password I wrote in the settings file it produces the following error:
django.db.utils.OperationalError: FATAL:  password authentication failed for user "Youssef"
Here's the DATABASE part in the settings.py file:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'Boards_django',
        'USER': 'Youssef',
        'PASSWORD': '000000',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

BTW, the database is recognized by the PgAdmin4:

Any idea what should I do???
Side note: I can't access the user, hence I'm not able to use any of the commands of postgresql
Also, when I try to run the server or make anything on the database from VS Code, It raises the following error:
django.db.utils.OperationalError: FATAL:  password authentication failed for user "Youssef"
Here's the data in the pg_hba.conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     scram-sha-256
# IPv4 local connections:
host    all             all             127.0.0.1/32            scram-sha-256
# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     scram-sha-256
host    replication     all             127.0.0.1/32            scram-sha-256
host    replication     all             ::1/128                 scram-sha-256

A: There are several possibilities:

*

*you used the wrong password

*there is no SCRAM-SHA-256 password set for the user
This could be either because no password is set, or because the password_encryption parameter is set to md5, or because the password has not been changed after password_encryption was changed.
To see the current setting:
SHOW password_encryption;

To see the password:
SELECT rolpassword
FROM pg_authid
WHERE rolname = 'Youssef';

A: well, the problem was that my friend had a slight spelling difference in his database, when I added it to my databases in the PgAdmin page, It worked perfectly.
Thanks to anyone who tried to help


text:
Q: Want to search string in the array of objects? I want to search this employee array which is consisted of objects and i should be able to search any text like if i pass ---> search_for_string_in_array ('aaron', employees) ; it should display me 'Value exists in array' or if its the way please help me..
//here is the employeee  array ...
  var employees =[{
                          name:"jacob",
                          age :23,
                          city:"virginia",
                          yoe :12,
                          image :'a.jpg'
                       },
                       {
                          name:"aaron",
                          age :21,
                          city:"virginia",
                          yoe :12,
                          image :'b.jpg'
                       },
                       {
                          name:"johnny",
                          age :50,
                          city:"texas",
                          yoe :12,
                          image :'c.jpg'
                       },
                       {
                          name:"jacob",
                          age :12,
                          city:"virginia",
                          yoe :12,
                          image :'a.jpg'
                       }];

here is the function which performs searching functionality inside an array.
    function search_for_string_in_array(search_for_string, employees)
            {
                for (var i=0; i < employees.length; i++)
                {
                    if (employees[i].match(search_for_string))
                    {
                        return 'Value exists in array';
                    }
                }
               return 'Value does NOT exist in array';
            }

Simply pass the value to search for and the array to the function and it will tell you whether the string exists as a part of an array value or not.

A: If you know the structure of the Array, you should probably just loop through it and test each value. If you don't know the structure, you can stringify the array into JSON and regexp it (although it won't be as safe):
function search_for_string_in_array(str, arr) {
    var json = JSON.stringify(arr);
    return new RegExp(':\"'+str+'\"','g').test(json);
}

A: just replace the line
if (employees[i].match(search_for_string))

with this:
if (employees[i].name.match(search_for_string))

A: Try
function search(text) {
    text += '';
    var i, obj;
    var array = [];
    for (i = 0; i < employees.length; i++) {
        var obj = employees[i];
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (('' + obj[key]).indexOf(text) >= 0
                        || ('' + key).indexOf(text) >= 0) {
                    array.push(obj);
                    break;
                }
            }
        }
    }

    return array.length > 0;
}

Demo: Fiddle1 Fiddle2


text:
Q: Is possible to drop a database in ADO.NET or create a new one I've been search for example to drop a database and create a new one in C# using ADO.NET or etc for SQL Server.
The problem is I need to create a instance of a new database for every new licensee, the customer wants a separate database for each new licensee, I've never tried this before and I'm finding it difficult to gauge the feasibility.

A: It is possible. It's actually an article on MSDN knowledge base.
http://support.microsoft.com/kb/307283
You basically just connect to 'master' or any database really, and send a SQL Command to create the database.
That should get you started.

A: I'd be looking at SQL SMO for this.
There are examples everywhere on how this works. For example, check out this one (http://www.codeproject.com/KB/tips/CreateSQLDV.aspx).
Anything you can do manually in SQL Management Studio you can do programatically, with SMO.


text:
Q: How to stop UIButton from highlighting/flash each time its title is reset? I'm using a UIButton as a label to display some number in its title. Every time the function is called to reset the title of this button, it flashes. It does not affect the functionality but hurts user experience. I'm wondering if there is a way to stop UIButton from this highlighting behavior?
Thanks in advance!
Edit: Following are the code where I'm simply calling a delegate method updateDigits to refresh the button's title.
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, DigitsEntryViewDelegate {

    @IBOutlet weak var tipField1: UIButton!
    @IBOutlet weak var tipField2: UIButton!

    var buttonsArray = [UIButton]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tipField1.tag = 0
        self.tipField2.tag = 1

        self.tipField1.addTarget(self, action: "inputFieldClicked:", forControlEvents: UIControlEvents.TouchUpInside)
        self.tipField2.addTarget(self, action: "inputFieldClicked:", forControlEvents: UIControlEvents.TouchUpInside)

        self.buttonsArray.append(self.tipField1)
        self.buttonsArray.append(self.tipField2)
    }

    func inputFieldClicked(sender: UIButton) {
        let anchor: UIView = sender

        let viewControllerForPopover = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("DigitEnter") as! DigitsEntryViewController

        // set popover API values
        viewControllerForPopover.currentDigitsString = sender.currentTitle
        viewControllerForPopover.tagNumber = sender.tag

        viewControllerForPopover.delegate = self
        viewControllerForPopover.preferredContentSize = CGSizeMake(240, 320)
        let popover = UIPopoverController(contentViewController:viewControllerForPopover)
        popover.presentPopoverFromRect(anchor.frame, inView: anchor.superview!, permittedArrowDirections: UIPopoverArrowDirection.Down, animated: false)
    }

    func updateDigits(returnedDigits: String, tagNumber: Int) {
        self.buttonsArray[tagNumber].setTitle(returnedDigits, forState: UIControlState.Normal)
    }
}

A: Try setting the button type to Custom, not System.

A: I could be mistaken, but the flashing looks like it may be caused by a data delivery delay; you are attempting to change the title while the new title is still being retrieved, hence the flash.
I would:

*

*Retrieve the data and store it in a temporary, but purpose created string.

*After the delivery of data is made, call a method to change the text of the button to that of the stored string.

A: This should fix your issue:
[UIView performWithoutAnimation:^{
  [self.myButton setTitle:text forState:UIControlStateNormal];
  [self.myButton layoutIfNeeded];
}];


text:
Q: Replacing WebAPI JSON.NET(Newtonsoft.Json) with Jil as Default Serializer I recently read up on Jil, claiming to be the faster Serializer than JSON.Net.
I would like some help on creating a Customer MediaTypeFormatter for Jil.
Take note: I'm using .NET framework 4.7.1
Any advice for codes to make Jil able to have such codes as well?
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

((DefaultContractResolver) config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
config.MessageHandlers.Add(new Library.Api.Authentication.Logs.LogRequestAndResponseHandler());

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));

Therefore, I want to try replacing JSON.Net with Jil as the Default Serializer for my WEBAPI.
Here are some references that helped me --> [1] & [2]


text:
Q: ./xsum: Permission denied make: *** [xsum.out] Error 126 I  am trying to insall f2c/f77 compiler on mac osx using the instructions given http://www.webmo.net/support/fortran_osx.html and I get the following error :
./xsum: Permission denied
 make: *** [xsum.out] Error 126

please help , as in installation it misses to create : /usr/local/bin/f2c
I followed the folowing :
chmod +x install_f2c_osx.csh
sudo ./install_f2c_osx.csh

PS : the install_f2c_osx.csh contains the following code :
`#! /bin/csh
setenv INSTALL /usr/local
curl "http://netlib.sandia.gov/cgi-bin/netlib/netlibfiles.tar?filename=netlib/f2c" -o       "f2c.tar"
tar -xvf f2c.tar
gunzip -rf f2c/*
cd f2c
mkdir libf2c
mv libf2c.zip libf2c
cd libf2c
unzip libf2c.zip
cp makefile.u Makefile
make
cp f2c.h $INSTALL/include
cp libf2c.a $INSTALL/lib
cd ../src
cp makefile.u Makefile
make
cp f2c $INSTALL/bin
cd ..
mkdir -p $INSTALL/share/man/man1
cp f2c.1t $INSTALL/share/man/man1
cp fc $INSTALL/bin/f77
chmod +x $INSTALL/bin/f77
cd ..
rm -rf f2c
echo "==================SUMMARY=================="
echo $0 " has built and installed:"
find $INSTALL -name '*f2c*' -mmin -5
find $INSTALL -name '*f77*' -mmin -5

A: For me, @Steele's solution didn't work. Just to document this here: the second solution posted on Superuser actually worked for me, i.e. my xsum binary was not useable by the system, for some reason. In that case, delete the xsum binary that came with f2c and build your own using the xsum.c source. That is, edit the initial code to be:
#! /bin/csh
setenv INSTALL /usr/local
curl "http://netlib.sandia.gov/cgi-bin/netlib/netlibfiles.tar?filename=netlib/f2c" -o "f2c.tar"
tar -xvf f2c.tar
gunzip -rf f2c/*
cd f2c
mkdir libf2c
mv libf2c.zip libf2c
cd libf2c
unzip libf2c.zip
cp makefile.u Makefile
make
cp f2c.h $INSTALL/include
cp libf2c.a $INSTALL/lib
cd ../src
cp makefile.u Makefile
rm xsum                 #Added
cc -O xsum.c -o xsum    #Added
chmod +x xsum           #Added
make
cp f2c $INSTALL/bin
cd ..
mkdir -p $INSTALL/share/man/man1
cp f2c.1t $INSTALL/share/man/man1
cp fc $INSTALL/bin/f77
chmod +x $INSTALL/bin/f77
cd ..
rm -rf f2c
echo "==================SUMMARY=================="
echo $0 " has built and installed:"
find $INSTALL -name '*f2c*' -mmin -5
find $INSTALL -name '*f77*' -mmin -5


text:
Q: Angular - Filtrar resultados - Recorriendo una propiedad array de strings de cada producto en una Base de Datos local tengo uno resultados que obtengo con *ngFor de una base de datos, y muestro algunas propiedades en el html.
Hay varias más que no se muestran con de talles.
Una de esas es un array. La base de datos esta e archibo products.ts
        export class productsDB {
        private static _Product = [
       {
     id: 1,
      detalles:["detalle1","detalle2","detalle3"],
      empresa : "interprise"
    },
    {
      id: 2,
      detalles:["detalle1","detalle5","detalle8"],
      empresa : "interprise1"
    },....
    ]

en product-list.component.html
tengo un input
  <div class="col-span-6 sm:col-span-3">
        <select name="categories" [(ngModel)]="empresa">
          <option>Enterprise</option>
          <option>Enterprise1</option>
    <div *ngFor="let product of products | filter: SearchEmpresa:'empresa'>
    <ll-product-card  *ngIf="view === 'grid'" [product]="product">
   </ll-product-card>
   </div>
  </div>

y el pipe es
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
 transform(value: any[], filterString: string, propName: string): any[] {
    const resultArray = [];
    if (value.length === 0 || filterString === '' || propName === '' || filterString === 'Empresa') {
      return value;
    }

    for (const item of value) {
      if (item[propName] === filterString) {
        resultArray.push(item);
      }
    }
     return resultArray;
 }
}

el archivo del componente product-list.com.ponent.ts
 import { Component, OnInit } from '@angular/core';
 import { productsDB } from '../../shared/data/products';

 @Component({
   selector: 'll-product-list',
   templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss']
 })
export class ProductListComponent implements OnInit {
isLoaded: boolean;
advanceSearchExpanded: boolean = false;
view = 'grid';
products = [];
empresa = '';
SearchEmpresa = '';
SortbyParam = '';
SortDirection = 'asc';
showFiller = false;

 constructor() {}

ngOnInit(): void {
setTimeout(() => {
  this.products = productsDB.Product;
  this.isLoaded = true;
}, 8000);
 }
 onEmpresaFilter() {
this.SearchEmpresa = this.empresa;
 }

 onEmpresaFilterClear() {
  this.SearchEmpresa = '';
  this.empresa = 'Empresa';
  }

  onSortDirection() {
if (this.SortDirection === 'desc') {
  this.SortDirection = 'asc';
} else {
  this.SortDirection = 'desc';
    }
  }
  }

Lo que necesito hacer es otro input para filtrar recorriendo el array detalles: ingresando alguno de los strings y que queden solo los que contienen esa string.
Se puede hacer algo similar al caso que busca emprersa.
Si es así, cómo debería ser.?
Y si no, sería otra manera distinta, con filter tal vez.
Gracias por interesarse en la consulta.


text:
Q: Same code base for WPF and Silverlight? I'm willing to build a simple database application using Silverlight. Is it possible to use that code base as a WPF application? Final goal is to have exactly one code base to serve both as a Desktop application and as a Web application.

A: There are differences between the XAML that Silverlight and WPF support so you won't be able to do it this way.
What you will be able to do though is create a Full Trust Application in Silverlight that can be installed onto the desktop.

A: Yes don't bother building the WPF application.  Build it all in Silverlight and allow the Silverlight app to be installed as an Out of browser app.

A: I agree with the other answers on just do Silverlight in a Full Trust. WPF is not limited to HTTP and that is a good thing.  I have an application that is primarily used internally with WPF clients.  For external clients (on the other side of the firewall) I a will build Silverlight client.  What I did was build business objects that can hopefully be consumed by both WPF and Silverlight.  For performance and features I need WPF.  Silverlight has some stuff WPF does not - e.g. autocomplete but for the most part WPF is beefier.


text:
Q: Switch that turns one lamp on while keeping the other one off - Mystery We tried to connect outside light bulp (AC) to a switch where an another light bulb is already connected. We did a parallel connection. Roughly like in the schematic. (I'm not an engineer so the schematic can be wrong).

simulate this circuit – Schematic created using CircuitLab
If I understand it right it should work like this: When the inside light is ON the outside light should be also ON. Because both lights are connected to the same switch. Or If I understand it right the outside light should light all the time.
But the lights work like so: When outside light is ON the inside light is OFF and vice versa.

A: If the schematic is correctly drawn, the circuit works like this:
When SW1 is closed, all the current passes through Inside Lamp, and through the switch which can be considered 0 Ohm. Outside Lamp is shunted out, no current passes through it. (But it should still be considered live.)
When SW1 is open, the current has to go through both lamps. The lamps are in series. If the resistance of each lamp is the same (this resistance is temperature dependent), each lamp will have half the voltage it should. Probably enough to light them up, but not at full brightness.
If one lamp is emitting light and not the other, it's probably because of a temperature difference, or minute differences in the filaments during production. Both lamps are effectively passing current, but one of them is cool enough that you don't see the glow.
It is highly unlikely that this is how the lamps are supposed to be wired.
I suggest that you hire a professional for this job. Doing electrical wiring when you don't know exactly what you're doing is dangerous. It can lead to the house burning down. Or someone getting electrocuted. It's not somehing to be taken lightly.


text:
Q: cannot create web site in Netbeans I have just installed JDK 7u45 & NetBeans 7.4 together .But When i try to create a java web application
File -> New Project ->Categoies

There is no Java web application option.So  I have followed these  steps But in the Available Plugins There is  no checkbox named Java Web Applications .What am i doing wrong

A: I guess, you did not download correct Netbeans bundle. You should use Java EE enabled Netbeans.
Go to the Netbeans download link. Download Java EE supported Netbeans and than try again.


text:
Q: Is there a to change the value of an element using JavaScript I'm trying to change the value of an element on a third-party web page using a JavaScript Add-on to display a hyperlink
I already have the link on the page i would like to be able to click it
I think I'm on the right track using document.getElementById although I'm not sure how to then change the id into a "a href" and then how to pass it back into the value.
Sorry, this is a bit of a tricky situation so I'll try my best to explain it. On a third-party web-page which we use for our HR related tasks, there is a section titled "File Link" although this isn't a link. When you copy and paste the address into a browser it displays the file. What i am trying to do is create a hyperlink on the "File Link" section to remove the need to copy and paste the link. Because this is a third party website. We have access to the JavaScript on the website and need to change the address into a hyperlink. I'm not entirely sure this is possible.The element id is "__C_cb_file_link" and i would like to insert the link address into the element using a variable then add the link parameters into the variable then reinsert it into the element/value.

function linkIt() {
        var intoLink = document.getElementById("__C_cb_file_link");
        var hLink = "<a href="+intoLink+";
        intoLink.value = hLink;
 }
window.onload = linkIt();

m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674

<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674"/>

A: In below code first we read input value with new link (however we can read this value from other html tags), then we remove this element (and button) and add to parent element (of removed input) the new link

function linkIt() {
  let intoLink = __C_cb_file_link.value;
  let parent  = __C_cb_file_link.parentNode;
  __C_cb_file_link.remove();
  btn.remove();
  parent.innerHTML += `<a href="${intoLink}">${intoLink}</a>`;
}
<input id="__C_cb_file_link" value="https://example.com">
<button id="btn" onclick="linkIt()">Link It</button>

A: [UPDATE] I supose that your "__C_cb_file_link" was a paragraph so I get the previous text http://mylink.com and create a link with,  is it what you want, right?

function linkIt() {

            let fileLink = document.getElementById("__C_cb_file_link");
            let hLink = fileLink.textContent;
            fileLink.innerHTML =  ""+hLink+"";

    }
      linkIt();

http://myLink.com

A: There are a number of issues with your code:
1) The code snippet in your question doesn't run because of a missing " at the end of the second line of the linkIt() function.
2) intoLink is a hidden field so anything you add to it will not be visible in the page
3) Even if point 2 were not true, setting the value of a form field will not cause HTML to appear on the page (at best you might get some plain text in a textbox).
4) "<a href="+intoLink+"" doesn't work because intoLink is a complex object which represents the entire hidden field element (not just its value property). You can't convert a whole object into a string directly. You need to extract the value of the field.

A better way to do this is by creating a new element for the hyperlink and appending it to the page in a suitable place. Also I recommend not adding your event via onload - when written using this syntax only one onload event can exist in a page at once. Since you're amending another page which isn't under your control you don't want to disable any other load events which might be defined. Use addEventListener instead, which allows multiple handlers to be specified for the same event.
Demo:

function linkIt() {
  var intoLink = document.getElementById("__C_cb_file_link");
  var hLink = document.createElement("a");
  hLink.setAttribute("href", intoLink.value);
  hLink.innerHTML = "Click here";
  intoLink.insertAdjacentElement('beforebegin', hLink);
}
window.addEventListener('load', linkIt);

m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674

  <input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674" />

P.S. m-files:// is not a standard protocol in most browsers, unless some kind of extension has been installed, so even when you turn it into a hyperlink it may not work for everyone.


text:
Q: How to use whose to ask who did what? I would like to know how to properly construct a sentence with the following idea:

*

*There's a completed project, and I wanna ask who came up with the project (using the word idea)

Do I ask like this? Does below sound correct and is grammatically correct?
... And whose idea was to build this project again?


text:
Q: Implementing strategy pattern when we need to modify the context class I have a Genome class that contains an array of bits ("genes"), and I would like to implement different mutation methods to change the genes. I'm currently implementing the mutation method using a Strategy Pattern, but the mutation method changes the Genome class directly.
Is this consider breaking encapsulation if I pass in the genes array into the Strategy and it modifies the array directly (naiveMutationStrategy)? I was reading some arguments that the Strategy pattern should not modify the state of the context calling it?
What if I directly passed in the Genome class (naiveMutationStrategy2) - I assume this is a no-no since the strategy pattern shouldn't store a reference to the context object?
function Genome(genes, mutationStrategy) {
  this.genes = genes; //an array
  this.mutationStrategy = mutationStategy;
}

Genome.prototype.mutate = function() {
  this.mutationStategy.execute(this.genes);
}

function naiveMutationStrategy() {};

//converts '1' into '0' and vice versa
mStrategy.prototype.execute = function(genes) {
  _.each(genes, function(element) {
    if (element === '0') {
      element = '1'
    } else element = '0';
  });
};

function naiveMutationStrategy2() {};

//converts '1' into '0' and vice versa
naiveMutationStrategy2.prototype.execute = function(genome) {
  _.each(genome.genes, function(element) {
    if (element === '0') {
      element = '1'
    } else element = '0';
  });
};

A:
I'm currently implementing the mutation method using a Strategy Pattern

Good idea, but don't try to reproduce the pattern you've learned for a class-based language too closely. Your constructor functions for the strategies are empty - they're unnecessary (unless you want some kind of "StrategyFactory"). Even those prototype objects with their methods are unncessary, they have only a single method.
JavaScript is a functional language, with first-class function objects. In a functional language, a "strategy" is just a function. Pass functions, not Strategy instances.

but the mutation method changes the Genome class directly.

Not really - it does not assign to the properties of Genome instances. All it does is to mutate the arguments that it got passed, which is (more or less) fine.

Is this consider breaking encapsulation if I pass in the genes array into the Strategy and it modifies the array directly (naiveMutationStrategy)?

No. The contracts are "the strategy expects an array argument" and "the strategy might modify its argument" - if you don't like the latter than use a different one. Really breaking encapsulation would be if the strategy got passed the Genome instance and would modify its properties from outside. As long your mutate method controls what is going on, I can't see a problem.

I was reading some arguments that the Strategy pattern should not modify the state of the context calling it?

Yes, it certainly is a good idea. If the genes were immutable and the strategy did create a new sequence of genes, your code would benefit.

_.each(genes, function(element) {
  if (element === '0') {
    element = '1'
  } else element = '0';
});

Notice that you're actually not mutating anything here. element is a local variable, not a reference to the array element. If you'd really wanted to mutate the array, you'd use
for (var i=0; i<genes.length; i++)
  if (genes[i] === '0')
    genes[i] = '1'
  else
    genes[i] = '0';

and if you wanted to create a new sequence, you'd use
return _.map(genes, function(element) {
  return (element === '0') ? '1' : '0';
});

A:
Is this consider breaking encapsulation

I don't think so but it depends on whether or not you want genes to be considered as a part of a public genome interface (contract) or not. In other words, if the world is aware that genome has genes then it is not against encapsulation to access this public property. If genes is a private implementation detail, then yes, it is against encapsulation to modify this private property from outside.

I was reading some arguments that the Strategy pattern should not modify the state of the context calling it

I would consider this as a "good practice" rather than strict requirement. It is just easier to think about strategy as something that only uses the object rather than modify it.


text:
Q: Backing up Tortoise SVN files Hi
Thank you for the responses
I'm new to this
I am trying to find out, where is the physical path of the SVN repository is on my Window Server so that I am able to back the files up.
Does someone know where they could be stored and the best way of backing them up.
Thank you

A: Committed files are stored in a SVN repository. Typically repositories are managed (and backed up) by the IT guys somewhere on a server on your network. However, you can also create repositories on your local file system if you want.
To discover the location of your repository, right-click on a folder in your working copy and open the TortoiseSVN repository browser. At the top of the repository browser is a URL. The start of this URL is also repeated in the treeview on the left: this should point at the location of your repository. If it is a file: URL, then your repository is probably stored on your local filesystem somewhere. If it is a svn: or http: URL, then most likely the repository is on another server.

A: On Windows: run the repo browser and look at the URL on top of the window.


text:
Q: How to create Frustum in DXF format for Autocad? I am trying to create a frustum using DXF file with my text editor, but unable to find any good solution or way to create it. If anyone knows and would be obliged to help me find a solution DXF file or an example, that would be a great help. Thank You

A: A frustum is a 3-dimensional figure.  While the DXF file format does contain provisions for coordinates in the Z-direction(3rd dimension), you cannot use it to define a true solid model. There are 3DFACE and 3DSOLID entities available, but they do not give you solid model objects like the IGES or STEP file formats would.
That being said, you have a tremendously large task ahead of you to create a valid DXF file in a text editor.  There is a huge amount of header information required in a DXF file for even the simplest shapes.
If you are serious about it, your best bet will be to start with a blank (no entities drawn) DXF file that has been created in a CAD package and use that as your base.  Then you can add entities to it as needed.  You will need the DXF file specification.  I use the R2000 spec since it has all the needed functionality while still being backwards compatible with the largest number of systems.
If you are doing a conic frustum, you will need to investigate the ELLIPSE entity, and if you are doing a pyramidal frustum, you will need the LINE entity.  Depending on the level of complexity you want and the version of the DXF spec that you work from, you can also use the SURFACE entity, but in a DXF file, this will just be represented as a series of lines forming a grid(polyface mesh).
You can also use the 3DFACE and 3DSOLID entities, but if you really want solid geometry, you're better off using a 3D file format as mentioned above.


text:
Q: Where and how to store database account credentials on PHP/ASP/JSP side? Lets suppose we have a virtual www host in a cloud. We cannot install anything and cannot create new users. This host has MySQL and PHP/ASP/JSP pointed to some www_root_dir. We have all privileges to MySQL and can write to www_root_dir.
The database contains table "Companies" with N companies inside. We want to create N admins - each to a corresponding company. We cannot create them as database users, since each one has then full access to a table and can peek/modify other companies, which we try to restrict.
So, we create a single database Manager account and a PHP/ASP/JSP Authorizer class that will approve or deny SQL requests from N admins and fetch requested information via Manager account.
The question is: how our Authorizer can authenticate itself by database?
In the case of "with Manager account login/password" then Authorizer class needs to store this password somewhere. Where exactly? If within an encrypted file then the only file storage is the www_root_dir directory that is publicly available to anyone. So anyone can download this file and bruteforce it offline.
Any ideas?


text:
Q: SDL_image won't install I'm trying to install the SDL-image library for Haskell, a set of bindings for the original C library of the same name. I've already built and installed the SDL library and its corresponding Haskell package, and dropped the files from the SDL-image library into the directory where SDL was installed. Now when I try to install the SDL-image bindings I get the following error:
$ runghc Setup.lhs configure
Configuring SDL-image-0.6.1...
configure: WARNING: unrecognized options: --with-compiler, --with-gcc
checking for sdl-config... /usr/bin/sdl-config
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.exe
checking for suffix of executables... .exe
checking whether we are cross compiling... no
checking for suffix of object files... .o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for IMG_Load in -lSDL_image... no
configure: error: *** SDL_image lib not found! Get SDL_image from http://www.libdsl.org/projects/SDL_image/index.html

Some cursory googling told me I should be telling configure exactly where to find the lib file, but I'm not sure how to go about doing this. I've tried using the gcc flag -l[directory], but got the same result.
I'm using MinGW on Win7x64. Thanks in advance for any help, and apologies if I haven't included enough information, I'm not sure what's important because I don't understand the problem very well.

A: I'm not sure about SDL_image, but I've successfully built SDL for Haskell. There's no need to go editing the cabal files.
Assuming you have the Haskell Platform, MINGW and MSYS installed, and the MINGW version of SDL somewhere, you just need to set the C_INCLUDE_PATH and LIBRARY_PATH environment variables to point to the headers and libs of SDL.
Once you've done that, you can use a MINGW shell to run cabal install SDL.


text:
Q: Displaying available strongly typed resource classes in Property Window I'm extending the Gridview Web Control as my first attempt at creating a custom control.
As part of the extension I am encapsulating the localization of the grid column headers within the control. Among others, I'm exposing a couple of properties to enable this feature:
bool AutoLocalizeColumnHeaders - enables the feature
string HeaderResourceFile - identifies a strongly typed resource class from which to get the header text
I'm overriding the OnRowDataBound handler and getting the appropriate ResourceManager using Reflection to populate the header text. This is all working nicely but I would like to display a list of the available Strongly Typed Resource Classes in the Property window for the user to choose from, rather than them having to type in the name manually.
I've created a TypeConverter for displaying a dropdown in which to display the available classes but can't work out how to get the list of available class names to display?
I've been trying for quite a while now without success and am at the point of losing my sanity. I'm assuming that there must be some way to achieve this using Reflection?

A: I think I've found the solution now.
Running the following from inside a Page_Load event gave me the Resource class names:
String[] resourceClassNames = (from type in assembly.GetTypes()
   where type.IsClass && type.Namespace.Equals("Resources")
   select type.Name).ToArray();

So I thought I'd be able to do something similar from inside the GetResourceFileNames(ITypeDescriptorContext context) function of the TypeConverter, using the context parameter to get hold of the correct assembly. Unfortunately, I could only seem to get the Custom Control's assembly or the System.Web assembly.
So, instead I've created a UITypeEditor which has an IServiceProvider passed into the EditValue routine. From this I was able to create an instance of ITypeDiscoveryService which I then used to get all of the types from the correct assembly:
public override object EditValue(ITypeDescriptorContext context,
                                 IServiceProvider provider, object value)
{
    // Check if all the expected parameters are here
    if (context == null || context.Instance == null || provider == null)
    {
        // returning with the received value
        return base.EditValue(context, provider, value);
    }

    // Create the Discovery Service which will find all of the available classes
    ITypeDiscoveryService discoveryService = (ITypeDiscoveryService)provider.GetService(typeof(ITypeDiscoveryService));
    // This service will handle the DropDown functionality in the Property Grid
    _wfes = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;

    // Create the DropDown control for displaying in the Properties Grid
    System.Windows.Forms.ListBox selectionControl = new System.Windows.Forms.ListBox();
    // Attach an eventhandler to close the list after an item has been selected
    selectionControl.SelectedIndexChanged += new EventHandler(selectionControl_SelectedIndexChanged);
    // Get all of the available types
    ICollection colTypes = discoveryService.GetTypes(typeof(object), true);
    // Enumerate the types and add the strongly typed
    // resource class names to the selectionControl
    foreach (Type t in colTypes)
    {
        if (t.IsClass && t.Namespace.Equals("Resources"))
        {
            selectionControl.Items.Add(t.Name);
        }
    }
    if (selectionControl.Items.Count == 0)
    {
        selectionControl.Items.Add("No Resources found");
    }
    // Display the UI editor combo
    _wfes.DropDownControl(selectionControl);

    // Return the new property value from the UI editor combo
    if (selectionControl.SelectedItem != null)
    {
        return selectionControl.SelectedItem.ToString();
    }
    else
    {
        return base.EditValue(context, provider, value);
    }
}

void selectionControl_SelectedIndexChanged(object sender, EventArgs e)
{
    _wfes.CloseDropDown();
}

This seems to work well although I expect there's a more stylish way to get the types required using LinQ, but I've only just started looking at LinQ and I can't seem to get the correct syntax when querying against a collection rather than an array as in the earlier example.
If anyone can suggest the LinQ syntax that would do this or indeed, a better way of accomplishing the whole thing, then it would be most welcome.

A: Interesting idea.  I imagine that your property is currently set as a string?
i wonder if you set your property as an Enum, then create an Enum with the strongly typed resource classes, will it be smart enough to show those in the property window. it is smart enough to show it in the code behind, cant see why it couldnt load it in the properties window.

A: In my solution posted previously, I wanted to find a way to do the following using LinQ:
    // Get all of the available types
    System.Collections.ICollection colTypes = discoveryService.GetTypes(typeof(object), true);
    // Enumerate the types and add the strongly typed resource class names to the selectionControl
    foreach (Type t in colTypes)
    {
        if (t.IsClass && t.Namespace.Equals("Resources"))
        {
            selectionControl.Items.Add(t.Name);
        }
    }

This seems to do the business:
    // Get all of the available class names from the Resources namespace
    var resourceClassNames = from Type t in discoveryService.GetTypes(typeof(object), true)
                        where t.IsClass && t.Namespace.Equals("Resources")
                        select t.Name;

    selectionControl.Items.AddRange(resourceClassNames.ToArray());

It certainly looks a lot cleaner and I would guess better performing as it's not looping through all of the available Types, checking for ones that meet the criteria in my code; although I suppose that LinQ would be doing this for me, albeit in a more efficient way?


text:
Q: Python execution and sleep timing variance I'm running a script to gather data, and I'm noticing some weird variations in the timing.
I've got a script that polls for data off of the I2C via the FTDI library, and it pulls data in at 3.5 HZ. It's solid and works great. Here it is (let's call it poll_data.py):
while time.time() < start_time + duration_in_seconds:
    if not stop_queue.empty():
        if stop_queue.get():
            logger.debug('Break received, exiting collection after {0} seconds'.format(time.time() - start_time))
            break
    data = get_data()
    cache.append(",".join(str(x) for x in [time.time() - start_time] + data]))
    counter += 1
    if len(cache) == 50:
        write_to_log_file(file_id, cache)
        cache = []

The queue was added so this script can be run asynchronously and stopped via some outside timing.
After running some tests, I noticed that I get weird stop times. Say I have a simple test:
import time
from threading import Thread
from poll_data import polling, stop_queue

start_time = time.time()
test_time = 60
duration = 80
process = Thread(target=polling, args=duration)
process.start()
interval = test_time - (time.time() - start_time)
time.sleep(interval)
stop = time.time()
stop_queue.put(True)
while process.is_alive():
    pass
end = time.time()
run_information.append((start_time, interval, stop - start_time, end - start_time))

After running this 105 times (in reality it's in a loop that runs x times, shortened here for ease of reading), I see some weird variations in execution times. Here's a small sample
                         Run information
     Start      |    Interval     |   Process End   |    Finished
1402934605.5525 |         59.9994 |         61.5621 |         64.3632
1402934670.9171 |         59.9991 |         60.5022 |         62.8066
1402934734.7252 |         59.9995 |         71.3656 |         77.0946
1402934812.8211 |         59.9996 |         61.4797 |         61.6411
1402934875.4637 |         59.9995 |         60.7879 |         60.7954
1402934937.2605 |         59.9995 |         60.2218 |         60.5099
1402934998.7719 |         59.9995 |         62.2200 |         65.0900
1402935064.8633 |         59.9994 |         60.0802 |         60.4974
1402935126.3622 |         59.9994 |         61.5364 |         63.3869
1402935190.7505 |         59.9995 |         61.5147 |         61.9220

Average Interval 59.99951714    Max 59.9998     Min 59.9991
                 62.28667048        71.3757         60.0485
                 64.23963714        77.0946         60.2074

I'm curious why the sleep interval always seems to be the same, but the stop time is very different, and the finish time is as well. The process ends immediately after the item is put in the queue, but that seems to take a while?
What's going on here?
EDIT: Added process.start() in appropriate place.

A: This may not be a satisfying answer, but I think it's just based on the operating system scheduling since the code you've shown doesn't look like it can cause any other delays. You have a couple important factors in play here. You are using the sleep function which itself says it may take less or more time depending:
https://docs.python.org/2/library/time.html#time.sleep
You are using threads which in Python are not run concurrently because of the GIL. And finally what was the computer running these tests doing while you ran them? Maybe the python process wasn't getting scheduled as often as it should. My comment before was a little wrong since the interval shows that the thread creation time is pretty constant. If you aren't showing all of the code involved it's possible there are other factors (ex. file reading/writing causing IO waits).
Maybe try a quick sanity check:
import time
start = time.time()
time.sleep(60)
stop = time.time()
print stop - start

Edit
And to bring up join again from my comment, if you use join then the main thread will be blocked on waiting for the thread and won't be running any actual code. This way any processing time can be given to the thread to catch the stop signal.


text:
Q: java, How can I show a list when choose a item in the combobox(GUI)? I have a doubly linkedlist that contains "Drivers","Tickets","Buses","Passengers" info and I want to print if I choose a item in the combobox for example when I pick driverlist, use my print method to print the information, if its any way to show each list by a chooser, please tell me, thanks.
 private static void Listframe() {
     JFrame f = new JFrame("Lists");
     String Lists[]={"Drivers","Tickets","Buses","Passengers"};
     JComboBox box = new JComboBox(Lists);
     JButton b = new JButton("show");

     JLabel label = new JLabel();
     f.setTitle("Lists");
     f.setForeground(Color.white);
     f.setBackground(Color.black);
     f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
     f.setSize(new Dimension(600,500));
     f.setLocation(new Point(20, 50));
     f.setVisible(true);
     f.setLayout(new GridLayout(1,3));
     f.add(box);
     f.add(label);
     f.add(b);
     b.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             String data = "picked list for: " + box.getItemAt(box.getSelectedIndex());
             label.setText(data);
         }
     });
}


text:
Q: Facebook App Can not be published I am using Facebook login and share in my android app.Facebook login is working. While sharing I am getting the following message '(#200)The user hasn't authorized this application to perform this action'.
I am using open graph share for customizing the share view.While submitting the Facebook app, I am getting the following message

Why this happens?What should i do to overcome this? can anyone please help. What is my mistake?


text:
Q: htaccess conditional for RequestHeader is it possible to have in .htaccess (Apache 2.2) a url condition that when met it executes the RequestHeader directive? Something like:
if ( %{HTTP_HOST} == "example.com" ){
  RequestHeader unset Set-Cookie
}

A: You can use mod_setenvif directive for this:
SetEnvIf Host ^(www\.)?example\.com$ NO_COOKIE
RequestHeader unset Set-Cookie env=NO_COOKIE


text:
Q: Cocoa OpenGL always white Everytime I run my Cocoa App with an OpenGL view I get a white window.  What I expect to happen is a black window will show up.
I've verified with a breakpoint that my drawRect method gets called.
Code below.
.h
#import <Cocoa/Cocoa.h>
#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>

@interface OpenlGLTest : NSOpenGLView

- (void) drawRect:(NSRect)dirtyRect;
@end

.m
#include <OpenGL/gl.h>
#import "OpenlGLTest.h"

@implementation OpenlGLTest

- (void)drawRect:(NSRect)bounds
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();
    [self setNeedsDisplay:YES];
}
@end

My project builds without warnings and errors.  I'm at a loss as to why my screen is white and not black.

A: Try glClearColor(0.0, 0.0, 0.0, 1.0);. That last 0 in your code is the alpha coefficient, so it's just showing whatever is behind the GLView.


text:
Q: ncurses detect when mouse leaves window When I research mouse interfacing with ncurses, I see many options, but I do not see any way to detect when the mouse has left the program window. The window is the window of the terminal emulator, not an ncurses window.

A: That's not in the repertoire of ncurses' mouse interface, but for some terminals you could set them up to send xterm's leave- and enter-window control sequences, which your program could read either byte-by-byte using getch, or by using define_key to associate the responses as a "function key".
XTerm Control Sequences lists in the section on FocusIn/FocusOut:

FocusIn/FocusOut can be combined with any of the mouse events since it
  uses a different protocol.  When set, it causes xterm to send CSI I
  when the terminal gains focus, and CSI O  when it loses focus.

That is enabled with
CSI ? Pm h
          DEC Private Mode Set (DECSET).
...
            Ps = 1 0 0 4  -> Send FocusIn/FocusOut events, xterm.

for instance,
printf("\033[?1004h");
fflush(stdout);

(a few other terminals implement this, but since they do not document their behavior, you'll have to experiment to find out whether this applies to the terminal you happen to be using).
In ncurses, you could associate the responses with define_key, e.g.,
#define KEY_FOCUS_IN     1001
#define KEY_FOCUS_OUT    1002

define_key("\033[I", KEY_FOCUS_IN);
define_key("\033[O", KEY_FOCUS_OUT);

and (if keypad is enabled), detect those values in your program as the return value from getch.


text:
Q: Using HttpContextAccessor in a .NET 4.6 project I've created a .NET Core project (a class library) that also targets .NET 4.6, which needs to be able to access the current HTTP context. I see that we can no longer use the static HttpContext.Current, and have to inject an instance of IHttpContextAccessor. Is this something I can still use inside something like a Web API project targeting .NET 4.6? So far, I can't get HttpContextAccessor.HttpContext to return anything but null.

A: For the class library I think you might want to pass the relevant variables/objects via constructor or methods.  It's good practice, because your class library wont break if you reference it in a console app without a httpcontext, for example.
If you're inside a controller method, you can just use Request or Response.


text:
Q: CMake error in FindTerminfo with clang-15 on MacOS I'm using llvm in my project and find it with cmake's find_package(LLVM REQUIRED CONFIG).
Configuration fails with message:
[cmake] CMake Error at /Applications/CMake.app/Contents/share/cmake-3.23/Modules/Internal/CheckSourceCompiles.cmake:44 (message):
[cmake]   check_source_compiles: C: needs to be enabled before use.
[cmake] Call Stack (most recent call first):
[cmake]   /Applications/CMake.app/Contents/share/cmake-3.23/Modules/CheckCSourceCompiles.cmake:76 (cmake_check_source_compiles)
[cmake]   /usr/local/lib/cmake/llvm/FindTerminfo.cmake:21 (check_c_source_compiles)
[cmake]   /usr/local/lib/cmake/llvm/LLVMConfig.cmake:242 (find_package)
[cmake]   tools/driver/CMakeLists.txt:6 (find_package)
[cmake]
[cmake]
[cmake] -- Could NOT find Terminfo (missing: Terminfo_LINKABLE)
[cmake] -- Configuring incomplete, errors occurred!

How to fix it?

A: It's actually a well-known issue in clang-14 and greater.
Temporary solution is to use C language in your project.
project(test LANGUAGES C CXX) # instead of project(test LANGUAGES CXX)


text:
Q: Storm is crashing due to zookeeper status changing I have very basic storm topology which contains 1 unreliable spout + 1 bolt. Spout is fed by Kafka broker via zookeeper. The Spout sends tuples to a bolt witch in its role do nothing ( has empty execute method).
The topology run in local cluster mode and it crashes after a while from run.
I tried to increase the app memory by -Xmx parameter many times, but the problem still appears.
please help!
Here is the code snippet that build the topology:
builder.setSpout("kafka_forwarding_spout", new KafkaForwardingSpout(),1);
      builder.setBolt("fake_bolt", new FakeBolt(),1).localOrShuffleGrouping("kafka_forwarding_spout");

Here is a snippet from storm log:
1318482 [Thread-37-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
1319574 [CuratorFramework-9] INFO  com.netflix.curator.framework.state.ConnectionStateManager - State change: LOST
1312307 [Thread-39-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
1307441 [Thread-25-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
1227216 [Thread-29-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
1191153 [Thread-31-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
1771836 [Thread-39-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
1688630 [ConnectionStateManager-0] WARN  com.netflix.curator.framework.state.ConnectionStateManager - There are no ConnectionStateListeners registered.
1650422 [Thread-35-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
1635500 [Thread-19-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
1616369 [CuratorFramework-11] ERROR com.netflix.curator.framework.imps.CuratorFrameworkImpl - Background exception was not retry-able or retry gave up
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
  at com.netflix.curator.ConnectionState.getZooKeeper(ConnectionState.java:72) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.CuratorZookeeperClient.getZooKeeper(CuratorZookeeperClient.java:74) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl.getZooKeeper(CuratorFrameworkImpl.java:353) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.BackgroundSyncImpl.performBackgroundOperation(BackgroundSyncImpl.java:39) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.OperationAndData.callPerformBackgroundOperation(OperationAndData.java:40) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl.backgroundOperationsLoop(CuratorFrameworkImpl.java:547) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl.access$200(CuratorFrameworkImpl.java:50) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl$2.call(CuratorFrameworkImpl.java:177) [curator-framework-1.0.1.jar:na]
  at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_05]
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_05]
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_05]
  at java.lang.Thread.run(Thread.java:745) [na:1.8.0_05]
1617025 [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2001] WARN  org.apache.zookeeper.server.NIOServerCnxn - EndOfStreamException: Unable to read additional data from client sessionid 0x149dd7eb6a2000b, likely client has closed socket
1600212 [Thread-23-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
1584086 [Thread-21-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
1570224 [Thread-9] INFO  backtype.storm.daemon.worker - Shutting down receive thread
1569786 [ConnectionStateManager-0] WARN  com.netflix.curator.framework.state.ConnectionStateManager - There are no ConnectionStateListeners registered.
2158302 [Thread-5] ERROR backtype.storm.event - Error when processing event
java.lang.RuntimeException: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
  at backtype.storm.util$wrap_in_runtime.invoke(util.clj:44) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
  at backtype.storm.zookeeper$get_children.invoke(zookeeper.clj:133) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
  at backtype.storm.cluster$mk_distributed_cluster_state$reify__2385.get_children(cluster.clj:101) ~[na:na]
  at backtype.storm.cluster$mk_storm_cluster_state$reify__2814.assignments(cluster.clj:243) ~[na:na]
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_05]
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_05]
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_05]
  at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_05]
  at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93) ~[clojure-1.4.0.jar:na]
  at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28) ~[clojure-1.4.0.jar:na]
  at backtype.storm.daemon.supervisor$assignments_snapshot.invoke(supervisor.clj:39) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
  at backtype.storm.daemon.supervisor$mk_synchronize_supervisor$this__6251.invoke(supervisor.clj:298) ~[na:na]
  at backtype.storm.event$event_manager$fn__2921.invoke(event.clj:39) ~[na:na]
  at clojure.lang.AFn.run(AFn.java:24) [clojure-1.4.0.jar:na]
  at java.lang.Thread.run(Thread.java:745) [na:1.8.0_05]
Caused by: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
  at com.netflix.curator.ConnectionState.getZooKeeper(ConnectionState.java:72) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.CuratorZookeeperClient.getZooKeeper(CuratorZookeeperClient.java:74) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl.getZooKeeper(CuratorFrameworkImpl.java:353) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:180) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.GetChildrenBuilderImpl$3.call(GetChildrenBuilderImpl.java:173) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.RetryLoop.callWithRetry(RetryLoop.java:85) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.GetChildrenBuilderImpl.pathInForeground(GetChildrenBuilderImpl.java:169) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:161) ~[curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.GetChildrenBuilderImpl.forPath(GetChildrenBuilderImpl.java:36) ~[curator-framework-1.0.1.jar:na]
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_05]
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_05]
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_05]
  at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_05]
  at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93) ~[clojure-1.4.0.jar:na]
  at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28) ~[clojure-1.4.0.jar:na]
  at backtype.storm.zookeeper$get_children.invoke(zookeeper.clj:131) ~[storm-core-0.9.1-incubating.jar:0.9.1-incubating]
  ... 13 common frames omitted
2117747 [Thread-4] ERROR com.netflix.curator.ConnectionState - Connection timed out
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
  at com.netflix.curator.ConnectionState.getZooKeeper(ConnectionState.java:72) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.CuratorZookeeperClient.getZooKeeper(CuratorZookeeperClient.java:74) [curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl.getZooKeeper(CuratorFrameworkImpl.java:353) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl$2.call(ExistsBuilderImpl.java:149) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl$2.call(ExistsBuilderImpl.java:138) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.RetryLoop.callWithRetry(RetryLoop.java:85) [curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl.pathInForeground(ExistsBuilderImpl.java:134) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl.forPath(ExistsBuilderImpl.java:125) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl.forPath(ExistsBuilderImpl.java:34) [curator-framework-1.0.1.jar:na]
  at backtype.storm.zookeeper$exists_node_QMARK_$fn__2170.invoke(zookeeper.clj:96) [na:0.9.1-incubating]
  at backtype.storm.zookeeper$exists_node_QMARK_.invoke(zookeeper.clj:93) [na:0.9.1-incubating]
  at backtype.storm.zookeeper$mkdirs.invoke(zookeeper.clj:107) [na:0.9.1-incubating]
  at backtype.storm.cluster$mk_distributed_cluster_state$reify__2385.set_ephemeral_node(cluster.clj:69) [na:0.9.1-incubating]
  at backtype.storm.cluster$mk_storm_cluster_state$reify__2814.supervisor_heartbeat_BANG_(cluster.clj:315) [na:0.9.1-incubating]
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_05]
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_05]
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_05]
  at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_05]
  at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93) [clojure-1.4.0.jar:na]
  at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28) [clojure-1.4.0.jar:na]
  at backtype.storm.daemon.supervisor$eval6298$exec_fn__1459__auto____6299$heartbeat_fn__6301.invoke(supervisor.clj:378) [na:0.9.1-incubating]
  at backtype.storm.timer$schedule_recurring$this__2141.invoke(timer.clj:92) [na:0.9.1-incubating]
  at backtype.storm.timer$mk_timer$fn__2124$fn__2125.invoke(timer.clj:48) [na:0.9.1-incubating]
  at backtype.storm.timer$mk_timer$fn__2124.invoke(timer.clj:41) [na:0.9.1-incubating]
  at clojure.lang.AFn.run(AFn.java:24) [clojure-1.4.0.jar:na]
  at java.lang.Thread.run(Thread.java:745) [na:1.8.0_05]
2078727 [Thread-16] ERROR com.netflix.curator.ConnectionState - Connection timed out
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
  at com.netflix.curator.ConnectionState.getZooKeeper(ConnectionState.java:72) ~[curator-client-1.0.1.jar:na]
  at com.netflix.curator.CuratorZookeeperClient.getZooKeeper(CuratorZookeeperClient.java:74) [curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.CuratorFrameworkImpl.getZooKeeper(CuratorFrameworkImpl.java:353) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl$2.call(ExistsBuilderImpl.java:149) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl$2.call(ExistsBuilderImpl.java:138) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.RetryLoop.callWithRetry(RetryLoop.java:85) [curator-client-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl.pathInForeground(ExistsBuilderImpl.java:134) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl.forPath(ExistsBuilderImpl.java:125) [curator-framework-1.0.1.jar:na]
  at com.netflix.curator.framework.imps.ExistsBuilderImpl.forPath(ExistsBuilderImpl.java:34) [curator-framework-1.0.1.jar:na]
  at backtype.storm.zookeeper$exists_node_QMARK_$fn__2170.invoke(zookeeper.clj:96) [na:0.9.1-incubating]
  at backtype.storm.zookeeper$exists_node_QMARK_.invoke(zookeeper.clj:93) [na:0.9.1-incubating]
  at backtype.storm.zookeeper$exists.invoke(zookeeper.clj:141) [na:0.9.1-incubating]
  at backtype.storm.cluster$mk_distributed_cluster_state$reify__2385.set_data(cluster.clj:85) [na:0.9.1-incubating]
  at backtype.storm.cluster$mk_storm_cluster_state$reify__2814.worker_heartbeat_BANG_(cluster.clj:291) [na:0.9.1-incubating]
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_05]
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_05]
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_05]
  at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_05]
  at clojure.lang.Reflector.invokeMatchingMethod(Reflector.java:93) [clojure-1.4.0.jar:na]
  at clojure.lang.Reflector.invokeInstanceMethod(Reflector.java:28) [clojure-1.4.0.jar:na]
  at backtype.storm.daemon.worker$do_executor_heartbeats.doInvoke(worker.clj:53) [na:0.9.1-incubating]
  at clojure.lang.RestFn.invoke(RestFn.java:439) [clojure-1.4.0.jar:na]
  at backtype.storm.daemon.worker$eval5665$exec_fn__1459__auto____5666$fn__5669.invoke(worker.clj:367) [na:0.9.1-incubating]
  at backtype.storm.timer$schedule_recurring$this__2141.invoke(timer.clj:92) [na:0.9.1-incubating]
  at backtype.storm.timer$mk_timer$fn__2124$fn__2125.invoke(timer.clj:48) [na:0.9.1-incubating]
  at backtype.storm.timer$mk_timer$fn__2124.invoke(timer.clj:41) [na:0.9.1-incubating]
  at clojure.lang.AFn.run(AFn.java:24) [clojure-1.4.0.jar:na]
  at java.lang.Thread.run(Thread.java:745) [na:1.8.0_05]
2079838 [CuratorFramework-11] INFO  com.netflix.curator.framework.state.ConnectionStateManager - State change: LOST
2052508 [Thread-37-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
1948998 [yassin-long-d_localhost.localdomain-1416760311632-aa3d627e_watcher_executor] INFO  kafka.consumer.ZookeeperConsumerConnector - [yassin-long-d_localhost.localdomain-1416760311632-aa3d627e], exception during rebalance
java.lang.NullPointerException: null
  at org.I0Itec.zkclient.ZkConnection.readData(ZkConnection.java:103) ~[zkclient-0.3.jar:0.3]
  at org.I0Itec.zkclient.ZkClient$9.call(ZkClient.java:770) ~[zkclient-0.3.jar:0.3]
  at org.I0Itec.zkclient.ZkClient$9.call(ZkClient.java:766) ~[zkclient-0.3.jar:0.3]
  at org.I0Itec.zkclient.ZkClient.retryUntilConnected(ZkClient.java:675) ~[zkclient-0.3.jar:0.3]
  at org.I0Itec.zkclient.ZkClient.readData(ZkClient.java:766) ~[zkclient-0.3.jar:0.3]
  at org.I0Itec.zkclient.ZkClient.readData(ZkClient.java:761) ~[zkclient-0.3.jar:0.3]
  at kafka.utils.ZkUtils$.readData(ZkUtils.scala:461) ~[kafka_2.10-0.8.1.jar:na]
  at kafka.utils.ZkUtils$$anonfun$getCluster$1.apply(ZkUtils.scala:505) ~[kafka_2.10-0.8.1.jar:na]
  at kafka.utils.ZkUtils$$anonfun$getCluster$1.apply(ZkUtils.scala:504) ~[kafka_2.10-0.8.1.jar:na]
  at scala.collection.Iterator$class.foreach(Iterator.scala:727) ~[scala-library-2.10.1.jar:na]
  at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) ~[scala-library-2.10.1.jar:na]
  at scala.collection.IterableLike$class.foreach(IterableLike.scala:72) ~[scala-library-2.10.1.jar:na]
  at scala.collection.AbstractIterable.foreach(Iterable.scala:54) ~[scala-library-2.10.1.jar:na]
  at kafka.utils.ZkUtils$.getCluster(ZkUtils.scala:504) ~[kafka_2.10-0.8.1.jar:na]
  at kafka.consumer.ZookeeperConsumerConnector$ZKRebalancerListener$$anonfun$syncedRebalance$1.apply$mcVI$sp(ZookeeperConsumerConnector.scala:407) ~[kafka_2.10-0.8.1.jar:na]
  at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:141) [scala-library-2.10.1.jar:na]
  at kafka.consumer.ZookeeperConsumerConnector$ZKRebalancerListener.syncedRebalance(ZookeeperConsumerConnector.scala:402) [kafka_2.10-0.8.1.jar:na]
  at kafka.consumer.ZookeeperConsumerConnector$ZKRebalancerListener$$anon$1.run(ZookeeperConsumerConnector.scala:355) [kafka_2.10-0.8.1.jar:na]
1872056 [Thread-39-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
1853312 [Thread-35-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
1840380 [Thread-31-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
1808599 [Thread-41-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
1799622 [Thread-25-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
2287292 [Thread-41-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
2287075 [Thread-37-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
2286862 [yassin-long-d_localhost.localdomain-1416760311632-aa3d627e_watcher_executor] INFO  kafka.consumer.ZookeeperConsumerConnector - [yassin-long-d_localhost.localdomain-1416760311632-aa3d627e], end rebalancing consumer yassin-long-d_localhost.localdomain-1416760311632-aa3d627e try #0
2280400 [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2001] WARN  org.apache.zookeeper.server.NIOServerCnxn - EndOfStreamException: Unable to read additional data from client sessionid 0x149dd7eb6a20005, likely client has closed socket
2280180 [ConnectionStateManager-0] WARN  com.netflix.curator.framework.state.ConnectionStateManager - There are no ConnectionStateListeners registered.
2267345 [Thread-9] INFO  backtype.storm.messaging.loader - Shutting down receiving-thread: [events_topology-1-1416760309, 1027]
2242225 [Thread-19-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
2224569 [Thread-29-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
2226559 [Thread-21-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
2209276 [Thread-23-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
2296607 [Thread-41-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
2293718 [Thread-37-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Expired)
2292830 [Thread-25-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (SyncConnected)
2498572 [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2001] WARN  org.apache.zookeeper.server.NIOServerCnxn - EndOfStreamException: Unable to read additional data from client sessionid 0x149dd7eb6a20003, likely client has closed socket
2540517 [Thread-41-kafka_forwarding_spout-EventThread] ERROR org.apache.zookeeper.ClientCnxn - Error while calling watcher
java.lang.OutOfMemoryError: Java heap space

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main-SendThread(localhost:2001)"
2637439 [Thread-35-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
2647739 [Thread-39-kafka_forwarding_spout-EventThread] INFO  org.I0Itec.zkclient.ZkClient - zookeeper state changed (Disconnected)
2672605 [main-SendThread(localhost:2001)] ERROR org.apache.zookeeper.ClientCnxn - from main-SendThread(localhost:2001)
java.lang.OutOfMemoryError: Java heap space
2764243 [Thread-25-kafka_forwarding_spout-SendThread(zoo2:2182)] ERROR org.apache.zookeeper.ClientCnxn - from Thread-25-kafka_forwarding_spout-SendThread(zoo2:2182)
java.lang.OutOfMemoryError: Java heap space
2720032 [main-SendThread(localhost:2001)] ERROR org.apache.zookeeper.ClientCnxn - from main-SendThread(localhost:2001)
java.lang.OutOfMemoryError: Java heap space
2731157 [Thread-8] ERROR org.apache.zookeeper.server.NIOServerCnxn - Thread Thread[Thread-8,5,main] died
java.lang.OutOfMemoryError: Java heap space
2800693 [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2001] ERROR org.apache.zookeeper.server.NIOServerCnxn - Thread Thread[NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2001,5,main] died

A: Seems like a java heap size problem. Check there are many other configurable memory related parameters.

A: This issue is being caused due to the Java Virtual Machine running out of available Heap memory in the system. Depending on on which underlying operating system that you are using, you can use the -Xmx parameter followed by the amount of memory you want to allocate. For example, if you want to allocate 2GB of memory then you need to mention -Xms2048m and the maximum heap size to be set as -Xmx2048m. However, remember that increasing the heap size after getting an OutofMemoryError is generally a short-term solution and it is highly probable to occur again in the future. It is generally an indicator  for optimising your code to be memory efficient.


text:
Q: How to store user input in Array I'm trying to create a sort of math quiz which prompts the user to answer one question before moving onto the next. At the end of the quiz, a popup window should list all of the problems along with the user's answers to each problem. I have it pretty much in place, but I can't figure out how to store each of the user's answers into an array in order to display these answers in the popup window. Any help would be greatly appreciated!
HTML:

    <form>

    <input id="carryOver">

    48

    +
    16

    <input id="userAnswer" type="text">

      <input type="button" onclick="submitAnswer()" value="Submit" />

    </form>

JavaScript:
// first number in addition problem
var numOne = [48,39,16,43,37,23,44,13,37,28,48,16];

// second number in addition problem
var numTwo = [16,22,25,18,46,49,18,39,25,17,9,28];

// counter variable
var i = 0;

function submitAnswer() {
    // validate the answer was a number
    var guessed = Number(document.getElementById('userAnswer').value);
    var checkAnswer = 'Correct!';

    // if the answer is incorrect, change result to Incorrect
    if (guessed != numOne[i]+numTwo[i]) {
        checkAnswer = 'Incorrect!\nThe answer is'+' '+Number(numOne[i]+numTwo[i])+'.';
    }
    // will show the string in the result variable
    if(confirm(checkAnswer) && i<1) {
        // next question
        i++;
        document.getElementById('firstNum').innerHTML=numOne[i];
        document.getElementById('secondNum').innerHTML=numTwo[i];

        // reset the answer and carry over to blank
        document.getElementById('userAnswer').value = '';
        document.getElementById('carryOver').value = '';
    } else if(i=1) {
        var results=window.open('','name','height=400,width=500');

        results.document.write('<title>Results</title>');
        results.document.write('<link rel="stylesheet" href="style.css">');
        results.document.write('');
        results.document.write('1) '+numOne[0]+' + '+numTwo[0]+' = ' + 'user input for Problem 1');
        results.document.write('
');
        results.document.write('2) '+numOne[1]+' + '+numTwo[1]+' = ' + 'user input for Problem 2');
        results.document.write('
Close the popup.
');
        results.document.write('');
        results.document.close();
    }
}

A: var answers = [];
answers.push(document.getElementById('userAnswer').value); //or something else to push

And replace if(i=1) with if(i==1)


text:
Q: Symfony 6 Doctrine relationship self-referencing uni-directional with linking table doesn't return data Please let me assure you I could not find response anywhere, maybe there is one, but I was unable to locate it.
What I want to do is self-referencing relationship but with LINKING TABLE because I find them easier to read than self referencing foreign key. So I used the only example of this I found in Doctrine documentation
So here it is, this is class User which implements Userinterface too (Manager and Employee is just a USER with different roles)
 /**
 * Manager can have many employees
 * @ORM\ManyToMany(targetEntity="User", mappedBy="managers")
 */
private $employees;
/**
 * Employee can have many managers
 * @ORM\ManyToMany(targetEntity="User", inversedBy="employees")
 * @ORM\JoinTable(
 *     name="manager_employee",
 *     joinColumns={@ORM\JoinColumn(name="employeeId", referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="managerId", referencedColumnName="id")}
 * )
 */
private $managers;

Now the problem is - I am 99% positive I loaded my fixtures with Managers who have multiple employees and 99% positive I use getEmployees on a correct manager. I quinduple checked. Yet when I use this method I get empty collection. I dumped collection, I checked with Xdebug. Empty. Why? I have them in DB, db works flawlessly. There must be something wrong with this relationship part but its beyond me to think of any more reason.
I would be grateful for your help, I would not have asked if it was not my last resort. Thank you!


text:
Q: Pick only the alphabets and not the description from a given string I am a newbie to Regex and require help with the following:
I have strings like - B - Comp-Band Disk,C - Check Oncoming Private,D - DL Procurement Outer. Is there a Regex expression which I could use to change string to B,C,D?

A: You can use
(?:(?:^|,)(\w))

Regex Explanation

*

*(?: Non-capturing group

*

*(?: Non-capturing group

*

*^|, Match start of the string or ,

*) Close non-capturing group

*( Capturing group

*

*\w Match any word character

*) Close group

*) Close non-capturing group

See the demo


text:
Q: Using shell globbing with Ansible templates Is it a way to use shell globing to specify several files as a src in template module?
- name: Copy keys
  template:
    src: "{{ item }}"/RPM-*
    dest: /etc/pki/{{ item }}/
  loop:
    - gf

A: You can use Ansible's fileglob loookupto do this. You would pass in your patterns as a list of arguments to with_fileglob, like this (rather than putting the pattern in the src argument of the template module):
- hosts: localhost
  gather_facts: false
  tasks:
    - name: Copy keys
      template:
        src: "{{ item }}"
        dest: "./pki/{{ '/'.join(item.split('/')[-2:]) }}"
      with_fileglob:
        - "gf/RPM-*"
        - "xz/RPM-*"

This copies files into ./pki/gf/RPM-... and ./pki/xz/RPM-.... The expression '/'.join(item.split('/')[-2:]) takes a pathname like /some/path/to/gf/RPM-foo and transforms it into gf/RPM-foo.
Note that you need to ensure the target directories exist first, which is probably going to require a separate task preceding this one to create them.


text:
Q: Sqlite display table with informations about the databas They are asking me to write a query that display the following table:

*

*Select each table as a string

*Select the number of attributes as an integer (count the number of attributes per table).

*Select the number of rows using the COUNT(*) function

*Use the compound-operator UNION ALL to bind these rows together.

How do I do that?
I knew that for getting the name of each table I have to use
SELECT name AS table_name
  FROM sqlite_schema
 WHERE type = 'table'

but the rest is a mistery to me.
Would you help me?
Thank you!!!
Here you can find the database

A: Just had the same question, and the answer boiled down to 'manually' (looking at the schema visualisation or the aforementioned query for inputs). >_<
SELECT 'Customers' AS table_name,
       13 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM Customers

UNION ALL

SELECT 'Products' AS table_name,
       9 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM Products

UNION ALL

SELECT 'ProductLines' AS table_name,
       4 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM ProductLines

UNION ALL

SELECT 'Orders' AS table_name,
       7 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM Orders

UNION ALL

SELECT 'OrderDetails' AS table_name,
       5 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM OrderDetails

UNION ALL

SELECT 'Payments' AS table_name,
       4 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM Payments

UNION ALL

SELECT 'Employees' AS table_name,
       8 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM Employees

UNION ALL

SELECT 'Offices' AS table_name,
       9 AS number_of_attribute,
       COUNT(*) AS number_of_row
  FROM Offices;


text:
Q: ERR_CONNECTION_RESET Azure CDN Custom Domain HTTPS Hope someone can assist me in correcting this. I am on the last step to enable my CDN endpoint with a custom domain. currently the static website on storage works correctly the following ways.
1 - Storage Account endpoint
2 - Azure CDN xxxxxx.azureedge.net
CNAME is created and correctly configured and validated in azure for my cdn.customdomain.com but when I try to connect to it I get a ERR_CONNECTION_RESET when using a browser or 404 using curl. Any advice anyone can provide.

A: You could verify the followings:

*

*Configuration. Make sure you select the Custom origin as the origin type and static website URI as the origin hostname.

*Networking related. ISP blocks some websites. Firewall blocks specific websites. Internet connection is disabled or interrupted. Refer to this.

*Browser error like Chrome. Clear your browser's cache and all locally stored data including cookies or try to use another browser. Refer to this.

Moreover, you could verify this via accessing the cdn.customdomain.com in an Azure VM, which is a different environment from the on-premise network.


text:
Q: iOS: Can I have a location based Launch Screen? My app behaves differently based on the city you're currently in.
I would like to display the city's name on the Launch Screen.
I will at first only support a few cities, so all I'd need would be the current location of the user and then match it against some hard coded locations in the app.
I'm pretty sure it's next to impossible to do this on the first app launch, since I will have to request user permission for the location, right?
But is it possible on the following launches, when I have the permission?

A: No. The LaunchScreen is static. You cannot change any displayed text or color or whatever at runtime. The only option is to use a launch screen where the city label is empty and create a splash screen (the first screen of your app) where you display the city name.
While your app is launching / starting there will not be a city name displayed, only after iOS finished starting your app you are able to do anything dynamic.


text:
Q: Find the critical points and say whether they are maxima, minima or saddle points I have this problem:
Find the critical points and say whether they are maxima, minima or saddle points
$$f(x,y)=x^2y(2−x−y)$$
My answer:
$f_x = xy (4-3 x-2 y) $
$f_y = -x^2 (-2+x+2 y)$     then
$xy (4-3 x-2 y)=0 , -x^2 (-2+x+2 y)=0$ the solutions are:
1)x=0 and $y \in{} \mathbb{R}$
2)x=1 and y=1/2
3)x=2 and y=0
I have three critical points,
$f_{xx} = -2 y (-2+3 x+y) $
$f_{yy} = -2 x^2 $
$f_{xy} = x (4-3 x-4 y) $, using
$D=f_{xx}f_{yy}-(f_{xy})^2 = -16 x^2+24 x^3-9 x^4+24 x^2 y-12 x^3 y-12 x^2 y^2$
x=1 , y=1/2 then D=0 but $f_{xx}=-2y (-2+3 x+y)= -2/3$ concluding (1,1/2) is a maxima point
x=2 , y=0 then D=-16 we say that (2,0) is a saddle points
x=0 , $y \in{} \mathbb{R}$ then D=0 the point  (x,a) with $a \in{} \mathbb{R}$ is a saddle points because for example if x=0 , a=-8 $fxx=-160$ (maxima) but if x=0 , a=1 then $f_{xx}=2$ (minima)
Is my exercise correct?

A: Look at the Hessian matrix and consider its eigenvalues. If the determinant is negative, then you get a saddle point. If the determinant is zero, the test is inconclusive; if the determinant is positive and $f_{xx} > 0$, then you get a minima; and if the determinant is positive and $f_{xx} < 0$ , then you have a maxima.
Now, can you see whether you are correct?
Hessian matrix is just the matrix
\begin{pmatrix}
f_{xx} & f_{xy} \\
f_{yx} & f_{yy} \\
\end{pmatrix}


text:
Q: When dealing with an improper antiderivative, why do you take the limit from the left? The example I have is $$\left[\tan x+\frac{1}{\cos x}\right]_0^{\frac{\pi }{2}}$$
In my mind, you treat it as a limit as $x \rightarrow \frac{\pi}{2}$
However, apparently it its $$\lim _{x\to \left(\frac{\pi }{2}\right)^-}\left(\tan x+\frac{1}{\cos x}\right)$$ because "you approach $\frac{π}{2}$ from the left".
Why is that so? The source is here: https://www.youtube.com/watch?v=TJzAp_NSsbM&t=0s (timestamp 4:45)

A: Because the integral
$$\int_{0}^{a} \frac{1}{1-\sin{x}}dx$$
is not defined on the interval $[0,a]$ with $a > \pi/2$, so you are considering it on the interval $[0,a]$, $a < \pi/2$, and letting $a \to \pi/2^{-}$.

A: Suppose that you want to compute$$\int_0^{\pi/2}\frac{1+\sin(t)}{\cos^2(t)}\,\mathrm dt.\tag1$$Note that this is an improper integral, since $\frac{1+\sin(t)}{\cos^2(t)}$ is undefined at $\frac\pi2$. So, $(1)$ actually means$$\lim_{x\to\pi/2^-}\int_0^x\frac{1+\sin(t)}{\cos^2(t)}\,\mathrm dt\tag2$$and therefore, since $\tan+\frac1\cos$ is a primitive of $\frac{1+\sin}{\cos^2}$, $(2)$ is equal to$$\lim_{x\to\pi/2^-}\left[\tan(t)+\frac1{\cos(t)}\right]_{t=0}^{t=x}.$$

A: Imagine that you decide to compute the integral as the Reimann sum
$$\lim_{n \to \infty} \sum_{k=1}^n g(k) \times \frac{\pi/2}{n},$$
where $g(k)$ is the value of the function $f(x)$ at $x= (k−1) \frac{π/2}{n}$.
Then in this Reimann sum, the value of $f(x)$ at any value $x \geq (\pi/2)$ is totally irrelevant.
Consequently, when examining the limit as $x$ approaches $\pi/2$ of the anti-derivative $F(x)$, you dismiss the limit as $x$ approaches $\pi/2$ from above as totally irrelevant.


text:
Q: Matrices - are they Row Echelon Form or Reduced Row Echelon Form? Help with the definitions I have a math problem in an excercise book which says
"In each part, determine whether the matrix is in row echelon form, reduced row echelon form, both, or neither."
Then I have the two following matrices.

*

*\begin{bmatrix}1&6&3&4\\0&1&1&0\end{bmatrix}

*\begin{bmatrix}0&0\\0&0\end{bmatrix}
My thought was that 1) above is in row echelon form and the reduced row echelon form would be:
\begin{bmatrix}1&0&-3&4\\0&1&1&0\end{bmatrix}
but the answer back in the book states the answer is "both".
For the 2nd one I thought it was in reduced row echelon form as it fulfils:

*

*All zero rows are at the bottom of the matrix

*The leading entry of each nonzero row subsequently to the first is right of the leading entry of the preceding row.

*The leading entry in any nonzero row is a 1.

*All entries in the column above and below a leading 1 are zero

but the book states it is only "row echelon" and not "reduced row echelon".
Can someone please give me a brief explanation how this is the case?
Many thanks


text:
Q: numpy boolean indexing multiple conditions I have a two dimensional numpy array and I am using python 3.5. I am starting to learn about Boolean indexing which is way cool. I can do this with my two dimensional array, arr.
mask = arr > 127
arr[mask] = 0
This works perfect but now I am trying to change this logic to use boolean indexing
for x in range(arr.shape[0]):
    for y in range(arr.shape[1]):
        if arr[x,y] < -10:
            arr[x,y] = 0
        elif arr[x,y] < 15:
            arr[x,y] = arr[x,y] + 5
        else:
            arr[x,y] = 30

I tried multiple conditional operators for my indexing but I get the following error:
ValueError: boolean index array should have 1 dimension boolean index array should have 1 dimension.
I tried multiple versions to try to get this to work. Here is one try that produced the ValueError.
 arr_temp = arr.copy()
 mask = arry_temp < -10
 mask2 = arry_temp < 15
 mask3 = mask ^ mask3
 arr[mask] = 0
 arr[mask3] = arry[mask3] + 5
 arry[~mask2] = 30

I received the error on mask3. I am new to this so I know the code above is not efficient trying to work out it.
Any tips would be appreciated.

A: This might help.  Consider a numpy array of floating point values foo.
import numpy as np
foo=np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])

foo yields
array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 0.8])

This is how you get the values in foo > 0.3
foo[np.where( foo > 0.3)]

yields
array([0.4, 0.5, 0.6, 0.7, 0.8])

This is how to do the same with multiple conditions.  In this case, values > 0.3 and less than 0.6.
foo[np.logical_and(foo > 0.3, foo < 0.6)]

yields
array([0.4, 0.5])

Alternatively using boolean mask array
mask_1 = foo > 0.3
mask_2 = foo < 0.6
mask_3 = np.logical_and(mask_1, mask_2)
mask_3

Yields a boolean mask array
array([False, False, False,  True,  True, False])

Which you can then use to slice the array via
foo[mask_3]

Yields
array([0.4, 0.5])


text:
Q: UIButton in CollectionViewCell "IndexPath doesn't work" I made a simple app add uibutton to collectionviewcell but when i give action an error occurs. Here is a screenshoot.
Error 1
Error 2
and my code of class: UIbuton {}
import Foundation
import UIKit

class KeypadUIButton: UIButton {
    var qIndex : NSIndexPath?
}

and my cell class is :
import UIKit

class ConverterCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var keypadButton: KeypadUIButton!
}

and error in :
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = padCollectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ConverterCollectionViewCell
        let index = indexPath.row
       // -> cell.keypadButton.qIndex = indexPath as NSIndexPath
return cell
}

Where is my mistake. can you help me ?

A: I have try with your code its work fine , please check that you give action to your button as well as custom class name to your button
class KeypadUIButton: UIButton {
   var qIndex : NSIndexPath?
}

class ConverterCollectionViewCell: UICollectionViewCell {

   @IBOutlet weak var keypadButton: KeypadUIButton!
}

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from
    a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

extension ViewController : UICollectionViewDataSource{

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 16
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let identifier : String = "test"
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ConverterCollectionViewCell
    cell.keypadButton.qIndex = indexPath as NSIndexPath?
    cell.keypadButton.setTitle("\(indexPath.row + 1)", for: .normal)

    return cell

}

}

A: Oh! I've got your error, it seems you missed this:

Type in your class name: KeypadUIButton
Also you don't need to use NSIndexPath in swift. Just use IndexPath instead. So you won't need to down cast it.

A: You had taken
qIndex as? NSIndexPath
you can take as
qIndex as? Indexpath
It avoid unnecessary downcasting in cellforitem.


text:
Q: Can I resume training of my neural network in Keras? (Without saving, just in the next cell of Jupyter) I've trained my model on 30 epochs. I just want continue training. I didn't save model state. Its state is saved in object. Can I just fit my NN in the next cell and continue training safely like on the picture?

A: Yes, successive calls to fit will incrementally train the model
keras github issue link


text:
Q: Google cloud ML without trainer Can we train a model by just giving data and related column names without creating trainer in Google Cloud ML either using Rest API or command line interface

A: Yes. You can use Google Cloud Datalab, which comes with a structured data solution. It has an easier interface and takes care of the trainer. You can view the notebooks without setting up Datalab:
https://github.com/googledatalab/notebooks/tree/master/samples/ML%20Toolbox
Once you set up Datalab, you can run the notebook. To set up Datalab, check https://cloud.google.com/datalab/docs/quickstarts.

A: Instead of building a model and calling CloudML service directly, you can try Datalab's ml toolbox which supports structured data and image classification. The ml toolbox takes your data, and automatically builds and trains a model. You just have to describe your data and what you want to do.
You can view the notebooks first without setting up datalab:
https://github.com/googledatalab/notebooks/tree/master/samples/ML%20Toolbox
To set up Datalab and actually run these notebooks, see https://cloud.google.com/datalab/docs/quickstarts.