Q: Android Studio - Cardview must click twice even i change android:focusableInTouchMode="false" im sorry. im begginer on android. i jus write a code with 4 cardview and the first one must click twice to work. But, the others cardview work with 1 click :(
And 3 others cardview can work without i give focusableInTouchMode property. Im confused with this issue and i have read about button clicked twice, it doesn't for me too. Please help me :)
Would you help me?
Here it;s my code :
...
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <android.support.v7.widget.CardView
            android:id="@+id/bangunan_menu"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_margin="10dp"
            android:focusableInTouchMode="false">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center"
                android:focusableInTouchMode="false">

                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:src="@drawable/bangunan"
                    android:focusableInTouchMode="false"/>

                <TextView
                    android:gravity="center"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Data Bangunan"
                    android:textSize="12sp"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:focusableInTouchMode="false"/>
            </LinearLayout>

        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:id="@+id/penyewa_menu"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_margin="10dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">

                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:src="@drawable/penyewa"/>

                <TextView
                    android:gravity="center"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Data Penyewa"
                    android:textSize="12sp"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"/>
            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>

</LinearLayout>

...
Thank you :)


Q: .net Word Interop closing issue I'm developing an application in vb.net that use Microsoft.Office.Interop.Word for printing an output in a Word document. If I close the application I want to close the doc (with the "Save As..." dialog). If the user wants to close the doc before the application ends this should be possible. Everything seems work fine, but after the closing (in both the case) I get this error:

This file is in use by another application or user.
(C:...\Templates\Normal.dotm)

I supposed the problem is that the doc owner is the application so the user can't close it... But the error also happens when the doc is closed by the application (with the quit method).
The code I run in frmMain_FormClosing is:
If _objWord IsNot Nothing Then
    Try
        _objWord.Quit()
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_objDoc)
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_objWord)
    Catch ex As Exception
    End Try
End If

I do the same with Excel and I don't have any problem.

A: When adding a document, make sure you use
Dim d As Word.Document = w.Documents.Add()

and not
d = New Word.Document 'this syntax can cause a memory leak!'


Q: Qt Widget temporarily fullscreen Consider a QWidget, normally a child in some Layout.
Supposed I want to make it fullScreen for a while, then have it return to it's old spot.
QWidget::setFullScreen() requires that the widget needs to be an independent window - any ideas how to work it out?

A: The simplest way I can see is to reparent to 0. Something like this:
#include <QApplication>
#include <QPushButton>

class MyButton : public QPushButton
{
public:
   MyButton(QWidget* parent) : QPushButton(parent) {}

   void mousePressEvent(QMouseEvent*) {
      this->setParent(0);
      this->showMaximized();
      this->show();
   }
};

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);

   QWidget mainWidget;
   MyButton button(&mainWidget);
   mainWidget.show();

   return a.exec();
}

A: I have modified the previous example. The previous example never goes back to normal screen.
Just copy paste the code and it will run.
        #include <QApplication>
        #include <QPushButton>

        class MyButton : public QPushButton
        {
        public:
           MyButton(QWidget* parent) : QPushButton(parent) {
               m_pParent = parent;
               maxMode = false;
           }
           QWidget * m_pParent;
           bool maxMode;
           Qt::WindowFlags m_enOrigWindowFlags;
           QSize m_pSize;

           void mousePressEvent(QMouseEvent*) {
               if (maxMode== false)
               {
                   m_enOrigWindowFlags = this->windowFlags();
                   m_pSize = this->size();
                    this->setParent(0);
                    this->setWindowFlags( Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
                    this->showMaximized();
                    maxMode = true;
               }
               else
               {
                   this->setParent(m_pParent);
                   this ->resize(m_pSize);
                   this->overrideWindowFlags(m_enOrigWindowFlags);
                   this->show();
                   maxMode =  false;
               }
           }
        };

        int main(int argc, char *argv[])
        {
           QApplication a(argc, argv);

           QWidget mainWidget;
           MyButton button(&mainWidget);
           mainWidget.show();

           return a.exec();
        }


Q: How to delete complete records from all tables in SQL Server I want to delete User table, Fruit table and UserFruitMapping table based on UserID.
How can I achieve this?

A: All these answers are poor and honestly none of you would be touching my databases. You are teaching him the wrong way. Tell me why should you delete from a table when there is no relationship between Fruit and User table? You DELETE only from the HREF/link table for there is the only relationship. Otherwise your database Architecture is badly designed. There should be A CASCADE DELETE on UserID on the Mapping table.

A: Create a simple stored procedure for this
CREATE PROCEDURE Delete_ThreeTablesData
    @UserId INT
AS
BEGIN
    DELETE FROM Fruit
    WHERE FruitId = (SELECT TOP 1 FruitId
                     FROM UserFruitMapping
                     WHERE UserId  = @UserId)

    DELETE FROM UserFruitMapping
    WHERE UserId  = @UserId

    DELETE FROM User
    WHERE UserId  = @UserId
END

A: Deleteing records from all tables can be a really messy task. Especially when there are lots of Foregin Key constraints.
If I find myself in a similar situation, I prefer to Script out the database obviously without the data and just drop the old database.
Finally create a new Fresh database using the script.
Where to find Advance Scripting options

To select "Schema Only" when generating scripts


Q: Rails / Factory Girl: Uninitialized constant FactoryGirl (NameError) I installed the factory_girl gem, and when I run my tests I get an error:

`block in ': uninitialized constant FactoryGirl (NameError)

This is my spec_helper.rb
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end

How can it be fixed?

A: In spec/spec_helper.rb, try adding
FactoryGirl.find_definitions

under
require 'factory_girl_rails'

or make sure you follow factory_bot's Getting Started guide.

A: This must be your answer.
The required addition should be made in spec/support/factory_girl.rb
https://stackoverflow.com/a/25649064/1503970

A: I'm just putting this here for anyone clumsy like me. Everything was fine, but I was calling FactoryGirl in one place, when I only have FactoryBot installed. Newbie error. Hope it might help.


Q: How to show data in FlatList in React-Native I am learning react-native and trying to fetch data from API and showing it in the flat list but I am not getting an idea of how can I do that in functional component as I have been through many tutorials on the internet but all of them uses class-based components.
Below is my code:
import React, {useEffect,useState} from 'react';
import {View,Text,StyleSheet} from 'react-native';

const List = () => {

const[post,setPost] = useState([]);

useEffect(() => {

    const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
    fetch(url).then((res) => res.json())
    .then((resp) => console.warn(resp))
    .catch((err) => console.warn(err));
},[]);

    return(
      <View>
          <Text style={styles.textStyle}>Hello there</Text>
      </View>
    );

};

const styles = StyleSheet.create({
 testStyle:{
     flex: 1,
     justifyContent:"center",
     alignItems:"center"
   }
});

export default List;

Data I have successfully retrieved from the server but How can I show this data in FlatList.

A: First you need to save your response in your state to refer later on. And then use Flatlist component of react-native
const List = () => {

const[post,setPost] = useState([]);

useEffect(() => {

    const url = 'http://api.duckduckgo.com/?q=simpsons+characters&format=json';
    fetch(url).then((res) => res.json())
    .then((resp) => setPost(resp.RelatedTopics))
    .catch((err) => console.warn(err));
},[]);

const renderItem = ({ item }) => (
    <Text style={styles.textStyle}>{item.Text}</Text>
  );

    return(
      <View>
        <FlatList
          data={post}
          renderItem={renderItem}
          keyExtractor={item => item.FirstURL}
        />
      </View>
    );
};

Refer this official doc with example for more detail

A: First you'd want to take a look at the docs. I didn't read the docs when I started playing around with FlatList and wrote my own buggy, confusing code to figure out what items were on-screen. While trying to make it less buggy, I found an amazingly simple way of doing that. It will save you time, I promise.
With that said you are going to want a few items

*

*Your list (you have).

*a component that renders a single item of your list. This component will have two relevant props: index and item. Index is as you have probably guessed, and item is data the list item has
So assuming you have a list like this
const data = [
  {name:"Harry Potter", phone:1234},
  {name:"Ron Weasley", phone:4321}
]

Your renderItem component may look like:
const renderItem=({index,item})=>{
let style = [{fontSize:14}]
// if first item give it spacing at top
if(index == 0)
  style.push({paddingTop:5})
return(
  <View style={style}>
    <Text>Name:{item.name}</Text>
    <Text>Phone:{item.phone}</Text>
  </View>
)
})

*A keyExtractor function, which should generate a string unique for all components in your app for each item of your list.
Bring this all together and you get:
 <FlatList
     data={data}
     renderItem={renderItem}
     keyExtractor={(item,key) => item.id || 'harry-potter-character'+i}
 />


Q: how to open app store with in our ipad or iphone application? Hi i want to open app store with in our application with the specific publisher search or specific application types..on clicking of button..let's say More App's...

A: To generate a link that is universal and not specific to an App Store Country do the following
Use
itms-apps://**ax.itunes**.apple.com/app/yourAppLinker

where yourAppLinker is the part of the link generated in (http://itunes.apple.com/linkmaker), as in Matthew Frederick's post, which contains your application name and id
it worked for me
cheers

A: For IOS7 and later for example:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/id547101139"]];

A: *

*You can get the appropriate URL to your app here:

http://itunes.apple.com/linkmaker

If you enter the name of your company the linkmaker will provide an "artist link" that shows all of your apps.

*If you use the itms-apps:// prefix the user is sent directly to the
App Store App with the specified app showing rather than the ugly
first-Safari-then-the-App-Store-App shuffle that you get without that
UTI. A la:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:
                                            @"itms-apps://yourAppLinkHere"]];


Q: Is there a way to generate XmlSchema from XML serializable class in C#? I have following class:
[Serializable]
public class Person
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlAttribute]
    public int Age { get; set; }
}

Now when I get an XML file from somewhere (eg. web service) I need to deserialize it to the instance of this class. Before doing that I'd like to check the XML file against schema to ensure XML has proper structure. I know I can create schema via XSD.exe tool like this:
xsd.exe  MyAssembly.dll /type:Person

This will create a physical .xsd schema file that I can then load to XmlSchema object. However I want to skip this manual generation of schema file and instead create XmlSchema dynamically in memory for a given class. This way when Person class is changed the code that generates XmlSchema directly from it will always have the schema that matches the current definition of the class. This is preferred way for me instead of always manually invoking xsd.exe tool every time Person class is changed.
So is it possible to programmatically create XmlSchema from a Person class?


Q: Unity - Why particle system gets transparent? I just created an particle system where you see a blinking add-icon. The problem is that if something gets behind the particle system, it gets transparent and I dont know why. I read that changing the shader could fix it, but it didnt work. I tried every shader in "Particles/..."
Here you how it looks like:

A: I seems that your object doesn't get transparent, but rather that it is being covered by the other object even though it should be in front of it.
Sorting is a common problem with objects that use some sort of blending:
In this case this is probably due to the other object being in a ui element. You could try to enforce the draw order by modifying the render queue in the material, or force it to use depth testing by using an alpha cutout shader instead (but its edges will not look as nicely anti-aliased without an extra MSAA or FXAA)


Q: Get the row number of a named Excel cell in MATLAB I'm working with a quite big Excel file in MATLAB with the xlsread function. I'm particularly interested in a named cell, let's say it's called FIRST_DATA. So in MATLAB I call:
[num, txt, raw] = xlsread(filename,sheet,'FIRST_DATA')
But I'm not interested in the data that this cell contains, but in the number of the row of this cell. How can I get this information?
My first guess is reading the data in the cell first, then reading the whole sheet and finally searching the resulting matrix for the cell data to find the row. But I hope for a more convenient way or one with less effort.
Thank you for your help!

A: There is a way using ActiveX, as suggested by Adiel in the Comments. Code example:
excelapp = actxserver('Excel.Application');
workbook = excelapp.Workbooks.Open('myspreadsheet.xlsx');
worksheet = workbook.Sheets.Item('sheet_with_data');
worksheet.Activate;
row_number = worksheet.Range('FIRST_DATA').Row;
Close(workbook);
Quit(excelapp);
delete(ExcelApp);

You should be closing everything properly to to prevent potential memory leaks.


Q: How do I keep the publisher from being stripped from fpassthru exes files? I am creating a simple proxy downloader that just passes the file stream through the server.  It seems to work with most files alright, but exe seems to have a problem in that the 'publisher' is some how stripped.
$url = "http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe"
$bname = basename($url);
$ext = pathinfo($url, PATHINFO_EXTENSION);
header('Content-type: application/'.$ext);
header('Content-Disposition: attachment; filename="'.$bname.'"');
fpassthru(fopen($url, 'rb'));

I've tried using different header information for exes:
    header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");

This does not make a difference.  In both cases, the exe files is downloaded, and it can be run but windows 8 complains about it having an 'unknown' publisher.  This does not happen when downloading the exe directly.  It seems like I am just about there, but something is slightly off.  In what step is the exe being modified (the reading or the output)?  How do I do this properly?  Thank you!


Q: Timthumb returning 404 on remote images only I am using timthumb to present images inside a Wordpress theme. It works fine when showing images from the same server but as soon as I try to load external images (in this case youtube thumbnails) it returns a 404 as if the script itself couldn't be found. The script is there though, if I load local images it behaves as expected. I have t set to allow external images, and specifically those from img.youtube.com
The strange thing is the exact same theme works as expected on my localhost and the external images show up fine, so I'm guessing it's something wrong on the hosting. Any suggestions as to what this may be?

A: IS your host allows to load images from external source. means out side of server ? This may be a problem.

A: HostGator do not allow absolute paths to use with TimThumb (even if it's hosted in your own account) as described in this article: http://support.hostgator.com/articles/specialized-help/technical/timthumb-basics.
To fix the absolute path issue, you'll would need to hack your theme functions to strip off your domain from the image path:
$url = "/path/to/timthumb.php?src=" . str_replace(site_url(), '', $path_to_image);


Q: How to invoke unit test a Print Event handler in c# I have below method which will get invoked when I call Print() method. I need to unit test the same. Is there any suggestions on how to do this?
internal PrintRemovalController(IApplicationContextHelper applicationContextHelper)
{
  _applicationContextHelper = applicationContextHelper;

  using (PrintDocument)
    _printDocument.PrintPage += PrintDocument_PrintPage;
}

public void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
  Font printFont = null;
  try
  {
    PrintDetails pd;
    do
    {
        pd = _printLines[_printPosition];
        printFont = new Font("Courier New", 11, pd.Style);

        if (pd.Text != "PAGE~~END")
            e.Graphics.DrawString(pd.Text, printFont, Brushes.Black, pd.XPos, d.YPos);

        _printPosition++;
    }
    while (pd.Text != "PAGE~~END");

    e.HasMorePages = _printPosition < _printLines.Count;
 }
 finally
 {
   if (printFont != null)
    printFont.Dispose();
 }
}


Q: To access the text area in the html rendered using Iframe which itself is loaded withing a cshtml page I have an iframe loaded within a Cshtml page. The Iframe contains an html form. i need to add an image in front of each text area of the form when the main page(cshtml page) is loaded. Have tried a lot of things but nothing has worked as such. Below is the code i am trying:
$("#iframe").ready(function() {
    $.each($('input[type=text],textarea'), function() {

        var idOfCurrentElement =  $(this).attr('id');
        var classNameOfCurrentElement =  $(this).attr('class');
        var visibilityOfCurrentElement = $(this).css('visibility');

        if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible")
            $("<img src='~/images/pic' alt='Pic'>");
    });
});

A: You must access iframe content, not your page.
$("#iframe").ready(function() {
      $.each($('#iframe').contents().find('input[type=text],textarea'), function() {
         var $thatButton =  $(this);
         var idOfCurrentElement = thatButton .attr('id');
         var classNameOfCurrentElement =  thatButton ).attr('class');
         var visibilityOfCurrentElement = thatButton .css('visibility');

     if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible")
         //do what you want.
      });
});


Q: How to get all orders data from flipkart seller api Can someone help me to get all order data from Flipkart seller API?
Currently, I am using this but it fetches the Orderitmes list of different orders. Is there any API to fetch directly all orders?
$url  = "https://api.flipkart.net/sellers/v2/orders/search";
    $curl = curl_init();
    $json = '{
              "sort": {
    "field": "dispatchByDate",
    "order": "desc"
  }
            }';
    curl_setopt($curl, CURLOPT_URL,$url);

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json',
    'Authorization:Bearer '.$tokan['access_token'],
    ''
    ));
    $result = curl_exec($curl);
    $ee = curl_getinfo($curl);
    echo "<pre>";
    //print_r($ee);
    curl_close($curl);

    $result = json_decode($result,true);
     print_r($result);

Please revert if anybody has any solution.
Thanks in advance!!


Q: Is There a dict with User Provided Key Function in Python? Some objects, numpy const arrays for example, are perfectly hashable but happened not to be (due to __eq__ being repurposed as an arithmetic operator, in the numpy case). Some objects, numpy arrays again for example, have multiple defintions of equility (id-equility and value-equility). For those object, a dict with user provided key function (as in sorted) would be very useful.
My question is: Is there a dict with user provided key function, either builtin or implemented in few lines, in Python?


Q: Conditional xpath using precompiled xpath I am using XPATH in my project and i need to traverse through the nodes conditionally
public static String getNodeContentForMultipleTag1(XPathExpression expr,Document doc) {
    try {

        NodeList typeResult = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < typeResult.getLength(); i++) {
            Node typeResultNode = typeResult.item(i);
            System.out.println(typeResultNode.getTextContent());
        }
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Failed parsing expression",e);
    }
    return null;
}

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    String s="<ex><DtTm><TxDtTm><Cd>ABCD</Cd>
1234
</TxDtTm><TxDtTm><Cd>XYZ</Cd>
891
</TxDtTm></DtTm></ex>";
    InputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
    DocumentBuilder db= XpathInstanceUtil.getDocumentBuilderFactory().newDocumentBuilder();
    Document doc = db.parse(inputStream);
    XPath xpath = XpathInstanceUtil.getXPathFactory().newXPath();
    XPathExpression expr = xpath.compile("/ex/DtTm/TxDtTm");
    inputStream.close();
    long st = System.currentTimeMillis();
    getNodeContentForMultipleTag1(expr, doc);
    long end = System.currentTimeMillis();
    System.out.println(end-st);

    long st1 = System.currentTimeMillis();
    getNodeContentForMultipleTag1(expr, doc);
    long end1 = System.currentTimeMillis();
    System.out.println(end1-st1);

}

if the Cd value is ABCD i should get 1234 as result.
I have tried the following
public static String getNodeContentForMultipleTag(String expresssion,String expectedNode,String expectedExpressionTag,Document doc) {
    try {
        XPath xpath = XpathInstanceUtil.getXPathFactory().newXPath();
        NodeList typeResult = (NodeList) evaluateXPath(doc,expresssion,xpath,XPathConstants.NODESET);
        NodeList valueResult= (NodeList) evaluateXPath(doc,expectedExpressionTag,xpath,XPathConstants.NODESET);
        //NodeList typeResult = (NodeList) xpath.evaluate(expresssion,doc, XPathConstants.NODESET);
        //NodeList valueResult = (NodeList) xpath.evaluate(expectedExpressionTag,doc, XPathConstants.NODESET);
        for (int i = 0; i < typeResult.getLength(); i++) {
            Node typeResultNode = typeResult.item(i);
            typeResultNode.getParentNode().removeChild(typeResultNode);
            Node valueResultNode = valueResult.item(i);
            if(typeResultNode.getTextContent().equals(expectedNode) && valueResultNode!=null){
                valueResultNode.getParentNode().removeChild(valueResultNode);
                return  valueResultNode.getTextContent();
            }
        }
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Failed parsing expression"+expresssion,e);
    }
    return null;
}

This is how expressions look like
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        String s="<ex><DtTm><TxDtTm><Cd>ABCD</Cd>
1234
</TxDtTm><TxDtTm><Cd>XYZ</Cd>
891
</TxDtTm></DtTm></ex>";
        InputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
        DocumentBuilder db= XpathInstanceUtil.getDocumentBuilderFactory().newDocumentBuilder();
        Document doc = db.parse(inputStream);
        String ss = getNodeContentForMultipleTag("/ex/DtTm/TxDtTm/Cd", "XYZ", "/ex/DtTm/TxDtTm/dt", doc);
        System.out.println(ss);
    }

But the its performance is very low.How it should be changed to parse efficiently

A: This code seems completely bizarre. Why are you doing all this work in Java rather than in XPath? Why are you modifying the DOM tree as you search it?
You just need to execute the XPath expression /ex/DtTm/TxDtTm[Cd='ABCD']/dt and you're there.


Q: Apache Camel message exchange does not wait for the response I have following code for publishing message to activeMQ and reading response via exchange. But code seem to be returning instantaneously and not waiting for the response. Could you please point what is wrong with the following Scala code.
def sendAndReceiveExtractionDetails(request:String, header: String) : String = {
    val exchange: DefaultExchange = new DefaultExchange(camel, ExchangePattern.InOut)
    exchange.getIn.setBody(request)
    exchange.getIn.setHeader("meshId", header)
    producer.send("activemq:queue:extractor-jobs?requestTimeout=1400000", exchange)
    val out: apache.camel.Message = exchange.getOut()
    out.getBody().toString
}

A: It seems to ignore the ExchangePattern you set. Have you tried to set it on your JMS URI as activemq:queue:...&exchangePattern=InOut?
I am not sure if you also need to define the JMSReplyTo header on the message or if this is done automatically when the exchangePattern is InOut.

A: Use the request method on the producer as that is for InOut

A: Following code works for me:
  def sendAndReceiveExtractionDetails(request:String, header: String) : String = {
    camel.createProducerTemplate()
      .sendBody("activemq:queue:extractor-jobs?requestTimeout=1400000", ExchangePattern.InOut, request).toString
  }


Q: AttributeError: Movie instance has no attribute 'number_of_seasons' i'm learning to code with python and i'm stuck on a error:
AttributeError: Movie instance has no attribute 'number_of_seasons'

So the problem is clear but i'm not sure how to solve it. Basically i created some classes and i would like to display some Movie and Series that has different attributes.
this is the media.py file where i created my classes and attributes:
class Video():
    """This class created for both common info movies and series"""
    def __init__(self, movie_title, story_line, url_poster, url_trailer, badge):
        self.title = movie_title
        self.storyline = story_line
        self.poster = url_poster
        self.trailer = url_trailer
        self.badge = badge

    def show_trailer(self):
        webbrowser.open(self.trailer)

# here i define the class called Film for all movies
class Movie(Video):
    """This class is used to create all movies"""
    def __init__(self, movie_title, story_line, url_poster, url_trailer, badge, movie_duration, movie_actors):
        Video.__init__(self, movie_title, story_line, url_poster, url_trailer, badge)
        self.duration = movie_duration
        self.actors = movie_actors

# here i define the class called Series for all series with episodes and seasons
class Series(Video):
    def __init__(self, movie_title, story_line, url_poster, url_trailer, badge, number_of_seasons, number_of_episodes):
        Video.__init__(self, movie_title, story_line, url_poster, url_trailer, badge)
        self.number_of_seasons = number_of_seasons
        self.number_of_episodes = number_of_episodes

Then i have the enterteinment_center.py file where i added only 1 movie and 1 serie:
import media
import fresh_tomatoes

ironman = media.Movie("Ironman",
                      "Genius, billionaire, and playboy Tony Stark, who has inherited the defense contractor Stark Industries from his father",
                      "http://cdn.collider.com/wp-content/uploads/2015/04/iron-man-1-poster.jpg",
                      "https://www.youtube.com/watch?v=8hYlB38asDY",
                      "http://i.imgur.com/45WNQmL.png",
                      "126 minutes",
                      "English")

games_of_thrones = media.Series("Games Of Thrones",
                                "The series is generally praised for what is perceived as a sort of medieval realism.",
                                "https://vignette3.wikia.nocookie.net/gameofthrones/images/2/2c/Season_1_Poster.jpg/revision/latest?cb=20110406150536",
                                "https://www.youtube.com/watch?v=iGp_N3Ir7Do&t",
                                "http://i.imgur.com/45WNQmL.png",
                                "7 Seasons",
                                "12 episodes")

movies = [ironman, games_of_thrones, ironman, games_of_thrones, ironman, games_of_thrones]
fresh_tomatoes.open_movies_page(movies)

and the last file that creates the html is fresh_tomatoes.py but i will paste here only the piece of code that i think is useful for the fix:
    def create_movie_tiles_content(movies):
    # The HTML content for this section of the page
    content = ''
    for movie in movies:
        if isinstance(movie, Movie):
            # Extract the youtube ID from the url
            youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer)
            youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer)
            trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None

            # Append the tile for the movie with its content filled in
            content += movie_tile_content.format(
                movie_title=movie.title,
                poster_image_url=movie.poster,
                trailer_youtube_id=trailer_youtube_id,
                film_badge=movie.badge,
                film_description=movie.storyline
            )
        elif isinstance(movie, Series):
            # Extract the youtube ID from the url
            youtube_id_match = re.search(r'(?<=v=)[^&#]+', movie.trailer)
            youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', movie.trailer)
            trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None

            # Append the tile for the movie with its content filled in
            content += movie_tile_content.format(
                movie_title=movie.title,
                poster_image_url=movie.poster,
                trailer_youtube_id=trailer_youtube_id,
                film_badge=movie.badge,
                film_description=movie.storyline,
                serie_season=movie.number_of_seasons
            )

    return content

def open_movies_page(movies):
  # Create or overwrite the output file
  output_file = open('fresh_tomatoes.html', 'w')

  # Replace the placeholder for the movie tiles with the actual dynamically generated content
  rendered_content = main_page_content.format(movie_tiles=create_movie_tiles_content(movies))

  # Output the file
  output_file.write(main_page_head + rendered_content)
  output_file.close()

  # open the output file in the browser
  url = os.path.abspath(output_file.name)
  webbrowser.open('file://' + url, new=2) # open in a new tab, if possible

So basically movie and series has some different attributes so if i want to display for example numbers of seasons for Games of Throne i will get an error telling that the movie Ironman don't have any attribute called numbers of season.
hope somebody can help on this! thanks a lot !

A: You cannot use the same function to extract values for classes with different attributes.
You need to assign a default value for each attribute in each class , or change the function to check the type of the movie in your loop.
For example :
for movie in movies:
    if isinstance(movie, Movie):
        # add movie attributes to the content
        content += movie_tile_content.format(
            movie_title=movie.title,
            poster_image_url=movie.poster,
            trailer_youtube_id=trailer_youtube_id,
            film_badge=movie.badge,
            film_description=movie.storyline,
            serie_seasons='no season'
            )

    elif isinstance(movie, Series):
        # add series attributes to the content
        content += movie_tile_content.format(
            movie_title=movie.title,
            poster_image_url=movie.poster,
            trailer_youtube_id=trailer_youtube_id,
            film_badge=movie.badge,
            film_description=movie.storyline,
            serie_seasons=movie.number_of_seasons
            )

This pattern allow you to change the content depending on the type of the media/video.
You may need to import the types in your second file:
from media import Movie, Series


Q: How can i split a column based on a condition in Python pandas My one of the columns consist following data -
Numbers
100 K
25.20 K
250 K
33.45 K
250
100
10
5
4
1

In the above Numbers column, I want to multiply numbers with K with 1000's and the other numbers without K, i want to leave them as it is.
How can I perform this conditional splitting and multiplication of column Numbers
Thanks in advance.

A: You could use numpy.where() with a boolean mask to identify your rows that contain 'K':
mask = df['Numbers'].str.contains('K')

df['Numbers'] = np.where(mask, df['Numbers'].str.extract(r'([\d\.]+)', expand=False).astype(float)*1000, df['Numbers'])

Yields:
  Numbers
0  100000
1   25200
2  250000
3   33450
4     250
5     100
6      10
7       5
8       4
9       1

A: Here's a way to do using a custom function:
import re
def func(s):
    # extract the digits with decimal
    s = float(re.sub('[^0-9\\.]', '', s))*1000
    return s

is_k = df['col'].str.contains('K')
df.loc[is_k, 'col2'] = df.loc[is_k, 'col'].apply(func)

df['col2'] = df['col2'].combine_first(df['col'])

       col    col2
0    100 K  100000
1  25.20 K   25200
2    250 K  250000
3      250     250
4      100     100
5       10      10

Sample Data
s=["100 K", "25.20 K", "250 K", "250", "100","10"]
df = pd.DataFrame({'col': s})


Q: Where are api documentation and demo for JAVA OCR? I want to use the JAVA OCR : http://sourceforge.net/p/javaocr/
I can't find the api documentation and the demo. In the download file, I have only the jars.
Can somebody help me?
Thanks

A: You can find demo code at OCRScannerDemo for old api, for new api new api demo
About api javadoc you can generate it with maven.
To get source code : git clone http://git.code.sf.net/p/javaocr/source javaocr-source


Q: Java Socks5 client and UDP support with Dante server I am writing SOCKS5 client
Ive got autorization and udp associate ready over TCP
Ive got address and port of the relay server but i am missing something with udp transmition...
   clientSocket = new DatagramSocket();
   IPAddress = InetAddress.getByName(serverHostname);

   byte[] sendData = new byte[1024];
   byte[] receiveData = new byte[1024];

   String sentence = "xxx";
   sendData = sentence.getBytes();

   DatagramPacket sendPacket =  new DatagramPacket(
                                     sendData,
                                     sendData.length,
                                     IPAddress,
                                     sCon.getDstPort());

   byte[] addr = sendPacket.getAddress().getAddress();

   byte[]head = new byte[6+addr.length];
   head[0] = (byte) 0x00; //RSV
   head[1] = (byte) 0x00; //RSV
   head[2] = (byte) 0x00; //frag
   head[3] = (byte) 0x01; //Address type
   //Put Address
   System.arraycopy(addr,0,head,4,addr.length);
   //Put port
   head[head.length - 2] = (byte) (sendPacket.getPort() >> 8);
   head[head.length - 1] = (byte) (sendPacket.getPort());

   byte[] buf = new byte[head.length + sendPacket.getLength()];
   byte[] data = sendPacket.getData();
   //Merge
   System.arraycopy(head,0,buf,0,head.length);
   System.arraycopy(data,0,buf,head.length,sendPacket.getLength());

   DatagramPacket updated = new DatagramPacket(
                                     buf,
                                     buf.length,
                                     relayAddr,
                                     relayPort);
   clientSocket.send(updated);

Socks5 srever -> 192.168.11.52
serverHostname -> 192.168.11.39
client IP -> 192.168.11.49
Example situation
Target /192.168.11.39, port 9876
SOCKS5 RelayAddr /192.168.11.52, RelayPort 56945

Dante log
block(0): udp: expected from 192.168.11.39.148, got it from 192.168.11.49.59124

Every time there is 192.168.11.39*.148* and i dont understand where is something wrong.
DatagramPacket never reaches the destination host


Q: Add value to a row in MySQL if it's greater than another value I have a table, Users, that contains a unique id, an integer 'econ', and some other irrelevant data. I'm trying to create a SQL statement for a simple gambling implementation. I have access to the user id, the amount bet, and the amount they potentially win. I need to verify that the user currently possesses more money than the total bet and if so UPDATE the row to Users.econ + winnings. (If the user lost the bet I'm simply using a negative number as the winnings value). I can do this with a couple separate statements but I'd prefer to use one so I don't have to deal with transactions.
Model:
User: id (varchar), econ (integer), other
Current implementation:

*

*SQL: SELECT econ from Users WHERE id = 'xyz'

*Logic: if (econ > bet) newEcon = econ + winnings, else throw error

*SQL: UPDATE Users SET econ = newEcon WHERE id = 'xyz'

Desired Result:
Example 1:

User model: id: 10, econ: 300
SQL request: id: 10, bet: 200, winnings: 300
Result: User: id: 10, econ: 600

Example 2:

User model: id: 5, econ: 50
SQL request: id: 5, bet: 100, winnings: 500
Result: User: id: 5, econ: 50 (unchanged)

Example 3:

User model: id: 12, econ: 200
SQL request: id: 12, bet: 100, winnings: -100
Result: User: id: 12, econ: 100

A: this query is working :
update accbalance set econ = econ + @winnings where id=@id and econ > @bet ;

Next time please create a sqlfiddle , it can help .
the query was tested in :
http://sqlfiddle.com/#!9/960009/1 .

A: You should be able to integrate the comparison into your UPDATE query:
UPDATE users
SET econ = econ + ?
WHERE econ > ? AND id = ?

Here I've used placeholders on the assumption you would prepare the query, in order they are for winnings, bet and id


Q: rownum & aliasing in HQL Need help...
how to translate this SQL query to HQL :
select "row" from (select rownum as "row", globalId from globalTable where valid='T') where globalId = "g123";

globalTable  :
globalId _ valid
g000 _ T
g111 _ F
g222 _ T
g123 _ T

it should return 3.
Thanks.

A: your query can be converted one query:
select rownum as "row" from globalTable where valid='T' and globalId = "g123"


Q: Multiple tables, eliminate data Suppose there are three tables T1, T2 and T3.

*

*T1 has columns Ordernum and bizdate

*T2 has columns Ordernum and Orderitem

*T3 has columns Orderitem and Catid
FYI: there are multiple orderitems under each ordernum; each ordertiem has multiple catids.
I want to eliminate ordernums where any itemnum has catid=100.
As I said, each ordernum has multiple orderitem, so I would like to eliminate all orderitem even if only one orderitem in a ordernum has catid=100 .
In other words, I want to print only ordernum where catid != 100

A: You can use a subquery that picks out the orders with that category and use to filter out those orders:
select
  OrderNum
from
  T1 as t
where
  not exists(
    select *
    from T1
    inner join T2 on T2.Ordernum = T1.Ordernum
    inner join T3 on T3.Orderitem = T2.Orderitem and T3.Catid = 100
    where T1.Ordernum = t.Ordernum
  )

A: You can to use EXISTS clause:
SELECT T1.OrderNum
FROM T1
WHERE NOT EXISTS
     (SELECT * FROM T2 INNER JOIN T3 ON T2.Orderitem = T3.Orderitem
      WHERE T1.OrderNum = T2.OrderNum AND T3.Catid != 100)

A: you need to select all and then exclude them on where statement. I think this will work.
SELECT a1.OrderNum FROM T1 a1
INNER JOIN T2 a2 ON a1.OrderNum = a2.OrderNum
INNER JOIN T3 a3 ON a2.Orderitem = a3.Orderitem
WHERE not a1.OrderNum in
(select ordernum from T2 where orderitem in
  (select Orderitem from T3 where T2.OrderItem = OrderItem and Catid = 100))
or maybe with subjoin is better:
WHERE not a1.OrderNum in
(select sa2.ordernum from T2 sa2 where sa2.orderitem in
  (select sa3.Orderitem
  INNER JOIN T3 sa3 on sa2.OrderItem = sa3.OrderItem and sa3.Catid = 100))

A: here it is ;
select *
  from T1
 where ordernum not in (select ordernum
                          from t2,t3
                         where t2.Orderitem=t3.Orderitem
                           and t3.catid=100)


Q: How to Get Tables Data in out parameters of Store Procedures in mysql I was trying to get data into the Output parameters of Stored Procedure in mysql but I am not getting it back.
HERE IS THE QUERY
Creation
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_initial_data`(
out usersData varchar(500),
out employeesData varchar(500)
)

BEGIN

SELECT * into usersData FROM users;

SELECT * into employeesData FROM employees;

END

Calling
Call get_initial_data(@users, @employees)

select @users

select @employees

I tried this and I am able to create the Store Procedure but not able to call, its giving me this Error...
Error Code: 1172. Result consisted of more than one row
Can you help me in this, am I passing the Output parameters correctly and also the Data type of that?
Please let me know your response on this....

A: An output parameter can contain only a single value. You are trying to return result sets via the output variable. This is not how output parameters work.
You read the result sets coming from the procedure; no need to use output variables.
CREATE PROCEDURE get_initial_data()

BEGIN

SELECT * FROM users;
SELECT * FROM employees;

END

Output parameters are useful in a situation where you have a procedure calling another procedure and use the output of the called procedure. Even then, you can only use single values with output parameters.


Q: how to extract text in each line of a pdf file using python I have gone through many solutions for extracting data from pdf file but could not find a solution to this particular problem
I have a pdf file that has the following data format in it
UPC             Product Description              Subcategory Name   Pkg type

018894300199    Big Y Mozzarella String  16oz       16oz Pkg Cheese    PKG

I need to extract the UPC, Product description and Sub name for each line of the pdf file using python
I was able to extract the text from the pdf file using the code below
from PyPDF2 import PdfFileReader, PdfFileWriter

pdfFileObj = open('grocery2.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

print(pdfReader.numPages)

pageObj = pdfReader.getPage(1)
pagecontent = pageObj.extractText()

I have more than 500 pages of product data. what is the most efficient way of extracting the UPC, Product description  and Sub name for each line of the page?

A: Since they are distinguished by spaces and your strings themselves have spaces using the extracted text will probably not be too helpful. I would have to see the full pdf to know if this would work but try:
From tabula import read_pdf

df = read_pdf("grocery2.pdf")

Then you can do any dataframe operations to extract different values ie.
df1 = df[['UPC', 'Product Description']]


Q: Get CameraId from Camera object in android I am developing on Nexus 7 that only has a front-facing camera. Thus, most of the default camera-related retrievals fail as they try to return information for first back-facing camera. What I would like to know is whether it is possible to retrieve the camera ID from an already retrieved camera object?
Please, understand that I do not want to iterate over the list of cameras in order to match one to the current camera. Also, I did retrieve the camera using that method but didn't need to persist the ID of the camera.
In one of my classes, separate from camera acquisition class, I am trying to get a hold of the camcorder's profile. I invoke it with CamcorderProfile.get(CamcorderProfile.HIGH_QUALITY); Documentation states that get(int quality):

Returns the camcorder profile for the first back-facing camera on the device at the given quality level. If the device has no back-facing camera, this returns null.

Thus, I need a cameraId for the currently open (front-facing) camera.
Thanks for any help!


Q: Does cached-resources plugin work with Grails 1.3.7 Maybe a dumb question...? (I think only Grails 1.2.* is supported?)
Im trying to use cached-resources with grails 1.3.7 following the simple example for the jquery plugin
E.g.
JqueryResources.groovy
modules = {
'jquery' {
    resource url:[plugin:'jquery',dir:'js/jquery', file:'jquery-1.4.4-min.js'], disposition:'head'
}

}
I am getting the following exception
2011-05-13 17:35:11,944 [main] ERROR resource.ResourceService  - Resource not found: /plugins/jquery-1.4.4.1/js/jquery/jquery-1.4.4-min.js
2011-05-13 17:35:11,991 [main] ERROR plugins.DefaultGrailsPluginManager  - Error configuring dynamic methods for plugin [resources:1.0-RC2]: java.io.FileNotFoundException: Cannot locate resource [/plugins/jquery-1.4.4.1/js/jquery/jquery-1.4.4-min.js]
org.codehaus.groovy.runtime.InvokerInvocationException: java.io.FileNotFoundException: Cannot locate resource [/plugins/jquery-1.4.4.1/js/jquery/jquery-1.4.4-min.js]
    at org.grails.tomcat.TomcatServer.start(TomcatServer.groovy:212)
    at grails.web.container.EmbeddableServer$start.call(Unknown Source)
    at _GrailsRun_groovy$_run_closure5_closure12.doCall(_GrailsRun_groovy:158)

Maybe im defining the path to the resource incorrectly?
E.g. Path to jquery. ../web-app/js/jquery/jquery-1.4.4-min.js


Q: Unable to use fwrite properly I'm unable to figure out how to use fwrite here. I'm getting a segmentation fault. Is there any other way I can write 0x00 to rgbtRed, rgbtBlue and rgbtGreen? I've looked up online, but couldn't find the right way to do this.
#include <stdio.h>
#include <stdint.h>
#include <string.h>

typedef uint8_t  BYTE;

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

int main (void)
{

    RGBTRIPLE triple;
    /*code which opens a bmp file, copies it and exports it to another
    file based on the changes which I ask it.
    I'm trying to set R's (of RGB) value to 0 to see if that solves
    the problem. I'm trying to figure out how to set the value to 0*/

    fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, 0x00);

}

A: fwrite is for writing to a file, but you want to set memory to zero, which is not quite the same thing.
With this line of code, the whole triple structure is set to zero.
memset(&triple, 0, sizeof triple);

A: Fourth argument of fwrite should be opened for writing FILE
Giving zero has result in exception
FILE * aFileYouWrite = fopen("afilename.xyz","wb");
memset(&triple, 0, sizeof triple);
fwrite(&triple.rgbtRed, sizeof(uint8_t), 1, aFileYouWrite );


Q: How to check if a string only contains chars from an array? I try to check if a word (wordToCheck) only consists of letters from an array (letters) and also contains every letter in the array only as often (or rather not more times than they are in the array) as it actually is inside of the array.
Here are examples of what the desired function should return:
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]) === true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]) === false

How can I make this code work?
function checkIfWordContainsLetters(wordToCheck, letters) {
    var lettersToString = letters.toString();
    var lettersTrimmed = lettersToString.replace(/,/gi, "?");
    var regEx = new RegExp(lettersTrimmed, "gi");
    if (wordToCheck.match(regEx)!== null) {
        return true;
    }
    else return false;
}

A: You could use this ES6 function:

function checkIfWordContainsLetters(wordToCheck, letters){
  return !letters.reduce((a, b) => a.replace(b,''), wordToCheck.toLowerCase()).length;
}

console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));

The idea is to go through each letter in the letters array, and remove one (not more!) occurrence of it in the given wordToCheck argument (well, not exactly in it, but taking a copy that lacks that one character). If after making these removals there are still characters left over, the return value is false -- true otherwise.
Of course, if you use Internet Explorer, you won't have the necessary ES6 support. This is the ES5-compatible code:

function checkIfWordContainsLetters(wordToCheck, letters){
    return !letters.reduce(function (a, b) {
        return a.replace(b, '');
    }, wordToCheck.toLowerCase()).length;
}

console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));

A: As long as it is not the best solution for long strings for which using some clever regex is definitely better, it works for short ones without whitespaces.
function checkIfWordContainsLetters(word, letters){
  word = word.toLowerCase().split('');

  for(var i = 0; i < letters.length; i++) {
    var index = word.indexOf( letters[i].toLowerCase() );
    if( index  !== -1 ) {
      // if word contains that letter, remove it
      word.splice( index , 1 );
      // if words length is 0, return true
      if( !word.length ) return true;
    }
  }
  return false;

}
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]); // returns true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]); // returns false


Q: What is the path of the cache directory on Android and iOS? I need to insert the path of the cache directory, that the image will be saved on android and iOS, by the library, but I don't know which path this is. Can someone please tell me which way it is?
export const openImage = (setFunc, w, h) => {
  ImagePicker.openPicker({
    cropping: true,
    path: "INSERT PATH HERE",
    mediaType: 'photo',
    width: p42(w) * 2.5,
    height: p42(h) * 2.5,
  })
    .then(response => {
      // alert(JSON.stringify(response));
      setFunc(response.path);
    })
    .catch(error => console.log('>>>>', error))
    .finally(() => ImagePicker.clean());
};

A: You can use react-native-fs for that.
CachesDirectoryPath (String) The absolute path to the caches directory
ExternalCachesDirectoryPath (String) The absolute path to the external caches directory (android only)


Q: Javascript Promise.all() inside of a loop I am trying to make a web API call twice inside of a loop, then wait until the webAPI has returned before pushing the returned values as a subarray within a larger array. Here's my code:
var latlngPairs = [];
function extractLatLongPairs(jsonobj){
    for(var i = 0; i<10; i++){
        let promises = [googlePlace(jsonobj[i]['From LID']), googlePlace(jsonobj[i]['To LID'])];

        Promise.all(promises).then((results) => {
            var temp2 = [results[0], results[1]];
            latlngPairs.push(temp2);
            console.log(latlngPairs);
        });
    }
}

The googlePlace function being called in promises:
function googlePlace(airport){
    https.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=' + airport + '&inputtype=textquery&fields=geometry', (resp) => {
        let data = '';

        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });

        //All data is returned
        resp.on('end', () => {
            data = JSON.parse(data);
            let obj = {
                name: airport,
                location: data.candidates[0].geometry.location
            };
            console.log('latlong should print after this');
            return Promise.resolve(obj);
            });

        }).on("error", (err) => {
            console.log("Error: " + err.message);

    });
}

I am expecting console.log('latlong should print after this') to print out before latlngPairs is printed. Because the order is vice versa, latlngPairs is filled with subarrays with undefined values. The output is something like:
[
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ]
]
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this

To be clear, the order I'm rying to achieve is 'latlong should print after this' then ' [[obj, obj], [obj, obj]]. I think I must have some fundamental misunderstanding about how promise.all works, and any help would be much appreciated!

A: You need to make your googlePlace function actually return a promise:
function googlePlace(airport) {
    // notice the new Promise here
    return new Promise((resolve, reject) => {
        https
            .get(
                "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=" +
                    airport +
                    "&inputtype=textquery&fields=geometry",
                (resp) => {
                    let data = "";

                    // A chunk of data has been recieved.
                    resp.on("data", (chunk) => {
                        data += chunk;
                    });

                    //All data is returned
                    resp.on("end", () => {
                        data = JSON.parse(data);
                        let obj = {
                            name: airport,
                            location: data.candidates[0].geometry.location,
                        };
                        console.log("latlong should print after this");
                        // notice the resolve here
                        resolve(obj);
                    });
                }
            )
            .on("error", (err) => {
                console.log("Error: " + err.message);
                reject(err.message);
            });
    });
}


Q: Zend Framework 2: setAttribute() on a non-object error occurs when trying to edit I'm new to the PHP Zend Framework 2 and I'm going through one of the online tutorials in learning how to use it.  The tutorial involves having you create and edit albums.  The problem is when I try to edit an album by clicking on the edit links, I get an error stating:
Call to a member function setAttribute() on a non-object
Controller:
public function editAction()
 {
     $id = (int) $this->params()->fromRoute('id', 0);
     if (!$id) {
         return $this->redirect()->toRoute('album', array(
             'action' => 'add'
         ));
     }

     // Get the Album with the specified id.  An exception is thrown
     // if it cannot be found, in which case go to the index page.
     try {
         $album = $this->getAlbumTable()->getAlbum($id);
     }
     catch (\Exception $ex) {
         return $this->redirect()->toRoute('album', array(
             'action' => 'index'
         ));
     }

     $form = new AlbumForm();
     $form->bind($album);
     $form->get('submit')->setAttribute('value', 'Edit');

     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter($album->getInputFilter());
         $form->setData($request->getPost());

         if ($form->isValid()) {
             $this->getAlbumTable()->saveAlbum($album);

             // Redirect to list of albums
             return $this->redirect()->toRoute('album');
         }
    // EDIT: This bracket below was missing originally
    // This is what was causing the 'setAttribute' error when
    // Clicking on the edit links for any of my albums
     }

     return array(
         'id' => $id,
         'form' => $form,
     );
 }

View:
<?php
//module/Album/view/album/album/edit.phtml:

$title = 'Edit album';
$this->headTitle($title);
?>

<h1><?php echo $this->escapeHtml($title); ?> </h1>

<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'album',
array(
    'action' => 'edit',
    'id'     => $this->id,
    )
));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('title'));
echo $this->formRow($form->get('artist'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

?>

EDIT: Here is the code from AlbumForm.php
AlbumForm.php:
<?php

namespace Album\Form;

use Zend\Form\Form;

class AlbumForm extends Form
{
   public function __construct($name = null)
   {
    // we want to ignore the name passed
    parent::__construct('album');

    $this->add(array(
        'name' => 'id',
        'type' => 'Hidden',
        ));
    $this->add(array(
        'name' => 'title',
        'type' => 'Text',
        'options' => array(
            'label' => 'Title',
        ),
        ));
    $this->add(array(
        'name' => 'artist',
        'type' => 'Text',
        'options' => array(
            'label' => 'Artist',
            ),
        ));
    $this->add(array(
        'name' => 'submit',
        'type' => 'Submit',
        'attributes' => array(
            'value' => 'Go',
            'id' => 'submitbutton',
            ),
        ));
   }
}

?>

I'm not really sure why this occurring since I'm following the tutorial exactly, so any help is greatly appreciated!


Q: Ionic native advanced Admob functionality I am implementing a new mobile app using ionic/angular/capacitor .I would like to know if it is possible to create native advanced Admob formats with any plugin that you might recommend? Not banner,interstitial or reward. Just native advanced one.
I want banners to be displayed inside certain div's not on top, bottom, or center of the screen.How can I achieve that ?
Thanks,


Q: system Audio Processing Objects (sAPO) and Skype in windows 8.1 I have googled and searched a number of forums and developer websites without any success; I believe it is a  specific question that needs direct expertise or knowledge, so please read on!
BACKGROUND:
I have an audio enhancement algorithm that is implemented as a system Audio Processing Object (sAPO)  that was developed and tested successfully in Windows 7. As an APO, it applies processing to all audio stream through an end point device, including audio originating from Skype.
QUESTION:
Is it true that this is not applicable to  Windows 8.x ( 8.1 or greater)? More specifically, does sAPO processing still work for  Skype?  Does Skype disable any and all APO processing on its stream?
WHAT HAS BEEN TRIED SO FAR:
(1) I have succeeded in following the standard procedure of loading an unsigned APO from Windows 7 in Windows 8.
(2) I have tested this with Skype audio stream and that works as well.
HOWEVER:
(1) above, fails in Windows 8.1 developer preview. As a result I have not been able to test (2).
Please note that I am specifically asking about Windows 8.1, in a laptop or desktop. This is not for mobile phones or tablets. Any information or links regarding this is much appreciated!

A: I am also trying to update an APO which have been developed for W7/8 to the new format introduced by W8.1, however it doesn't seem like much documentation has been released yet.
What I have found so far, is that Windows 8.1 requires some new methods for discovery and control of effects to be implemented into the APO. This means that Skype would be able to discover certain APO effects and disable them if it needs to.
The new interface IAudioSystemEffects2:
link
Some updated code can be found in the new SwapAPO example:
link
Not much, but hopefully it can help you get going in the right direction.


Q: Connect React App served on dockerized Nginx to Express server For production, I have a Dockerfile which serves a React app using Nginx:
# Stage 1

FROM node:15.6.0-alpine3.10 as react-build
WORKDIR /app/client/
COPY package*.json ./
RUN npm install
COPY ./ ./
RUN npm run build

# Stage 2 - the production environment

FROM nginx:1.19.6
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=react-build /app/client/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

While for the backend written in Node / Express, I have the following Dockerfile:
FROM node:15.6.0-alpine3.10
WORKDIR /app/server/
COPY package*.json ./
RUN npm install
COPY ./ ./
EXPOSE 8080
CMD ["npm", "start"]

These containers are managed with this docker-compose.yml:
version: "3.0"

services:
  # React Client
  web:
    image: xxx.dkr.ecr.eu-west-2.amazonaws.com/client:latest
    ports:
      - "80:80"

  # Node Server
  server:
    image: xxx.dkr.ecr.xxx.amazonaws.com/server:latest
    command: npm start
    ports:
      - "8080:8080"

Here the nginx.conf:
server {
  listen 80;

  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }

  include /etc/nginx/extra-conf.d/*.conf;
}

PREMISES

*

*On local everything works fine, I run React through react-scripts and the backend with docker-compose (and so without the React client)

*Both images have been pushed to AWS ECR, their content is the equivalent of the Dockerfile above

*When fetching the server, endpoints look like fetch("/users/:id", {..})

*On package.json, I've set "proxy": "http://localhost:8080/"

*Both images have both been tested and are working, both on dev and prod

PROBLEM
When hitting an api endpoint from the client, I get a 405 (Not Allowed).
That's actually expected, as I'm not really telling the client (Nginx) where to redirect these calls to.
Inspecting the network tab I can see the request is made against xxx.xxx.xxx.xxx:80 (which represents the client), when it should be redirected to same address but port 8080 instead (where the Express server stands).
On development it works since there's proxy set on package.json, but that's for development only, so it won't affect production.
WHAT I TRIED

*

*Using links on docker-compose, not supported from AWS

*Using driver networks on docker-compose, not supported from AWS

*Adding proxy_pass on nginx.conf, but haven't been able to make it working

CONCLUSIONS
So premised all this, how can I connect a React build served with Nginx (client) to a Node server when both dockerized and on production?
I believe it should need some configuration on nginx.conf, but what I tried didn't land me that far.
Thank you in advance for your help!

A: First you need to specify proxy pass directive for your api calls - I would propose to add /api in your fetch calls. Than provide upstream using the same name for your backend service as specified in docker-compose.yml. It is important that backend service proceed the web service in docker-compose.yml, otherwise you would get connection error in nginx like this nginx: [emerg] host not found in upstream "backend:8080" You can update your nginx.conf as follows:
upstream backend {
  server backend:8080;
}

server {
  listen 80;

  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://backend;
  }

  include /etc/nginx/extra-conf.d/*.conf;
}

Or simply in your case provide a proxy pass to localhost as follows:
server {
   listen 80;

   location / {
     root /usr/share/nginx/html;
     index index.html index.htm;
     try_files $uri $uri/ /index.html =404;
   }

   location /api {
     rewrite /api/(.*) /$1 break;
     proxy_pass http://localhost:8080;
   }

   include /etc/nginx/extra-conf.d/*.conf;
}

A: Sample Docker file, Included the Production build in the docker file
FROM node:15.6.0-alpine3.10 as react-build

# install and cache app dependencies
COPY package.json package-lock.json ./
RUN npm install && mkdir /react-frontend && mv ./node_modules ./react-frontend

WORKDIR /app/client/

COPY . .

RUN npm run build

# ------------------------------------------------------
# Production Build
# ------------------------------------------------------
FROM nginx:1.16.0-alpine
COPY --from=builder /react-frontend/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

To add nginx as a server to our app we need to create a nginx.conf in the project root folder. Below is the sample file
server {

  listen 80;

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }

  error_page   500 502 503 504  /50x.html;

  location = /50x.html {
    root   /usr/share/nginx/html;
  }

}


Q: Payment for uploading app into android market Registration fee is 25$. It will only be for one year? After one year we have to pay 25$ or it will expire? How much do we have to pay for renewal?

A: "There is a one time $25 registration fee"
Extracted from here


Q: Why my jetstream application in Laravel not showing proper CSS and JS path when uploading in Cpanel? I have built a project in laravel using jetstream. The project is running smoothly in my local machine (localhost) but the CSS and JS path is not working when I am uploading in server. Can anyone help?

My cpanel directory is
public_html/pro1/admin/

Error
Falied to load resource : app.js
Falied to load resource : app.css
Falied to load resource : app.css


Q: How to modify Djongo ArrayModelField as shown in Django Admin I'm experimenting with Djongo right now. So far a great project! What I don't like yet is the way ArrayModelField fields are integrated in the Django admin. I am missing something like an add-button. At the moment only one additional empty inline Form is shown for the nested model.
Is there a possibility to add new inline models with an "add-button"?


Q: "This will merge 0 commits." I have somehow messed up my git branch badly. Certain branches didn't seem to be merged properly. I'm not sure how to explain, things just aren't how I wanted. I was working on different branches branched from master and then pushing them to one called development, but I think because I merged some of those branches together while working on them, that has somehow messed up the final result.
I went into development and reverted all the merges from when I started working. This should be OK since I have the original branches still. But when I try merge these branches back into development, the GitHub app app says there are no changes to commit. How can this be if I reverted everything?

A: Reverting does not delete commits, it creates a new commit that is the inverse of the patch set. So if you're cherry picking previous commits into a new branch, the old ones won't be identified as needing to be merged.
You could attempt to rebase those same commits into a new branch, then merge those back in. The rebasing would replay and create new commits for your reverted items. Since you don't provide a lot of details, I can't give an exact answer.


Q: How do I bind the Header of a TextBox? In windows phone 8.1, I can bind the text in a textbox to a string resource in my Resources.resw.
How do I do the same thing for the Header="My Header" tag?
i.e. bind the Header text to another string resource in Resources.resw
<TextBox Header="My Header" Text="{Binding textboxtext}" x:Name="TextBox"/>

A: Same way you Bind the Text field.
<TextBox Header="{Binding myBinding}" Text="{Binding textboxtext}" x:Name="TextBox"/>

If you want to point it to a Resource then
<Page.Resources>
    <x:String x:Key="myTextBoxHeader">this is a textbox header</x:String>
</Page.Resources>

<TextBox Text="{Binding textboxtest}"
    Header="{StaticResource myTextBoxHeader}"></TextBox>

If you pointing to a .resw file then in most cases you will need a x:Uid like this
<TextBox x:Uid="MyLocalizeTextBox"></TextBox>

Then you need to edit the strings for the stuff you want to display, in this case your Header + Text

Look at the highlighted section very carefully, you see the pattern?  It won't show up on the designer and will show up when you deploy [See Image Below]

So by now you may be wondering if you combine both methods? (one to show in the designer and one to show while deploy because you're localizing).  This is actually the prefer method.
2 in 1 (Both methods)
<TextBox x:Uid="MyLocalizeTextBox"
    Text="{Binding textboxtest}" Header="{StaticResource myBinding}"></TextBox>

During design time it will use your local resouces, when deploy it will use the resources in the resw file.


Q: How to convert full path of a file to only the file name in batch scripting I have a variable called %file% and it contains path to a file, i want that ONLY the file name in a new variable called %file_name% (without the extension like .exe). I am new to batch scripting so this might be very easy...
Thanks in advance!

A: for %%i in (%file%) do @echo %%~nxi

n for name
x for extension
for more options see for /?


Q: PHP Related items from database I have been googling for a while and searching SO but I still can't find an answer.
So my problem is that I want to pull related content from mySQL database on what id is currently being displayed on the page. In the database I have a column dedicated to keywords, and I am using the LIKE query to pull id's based on those keywords. However, I get only one id because the LIKE query looks at the keyword literally. For example, keyword1 = 'apples berries oranges' is not the same as keywords2 = 'apples' 'berries' 'oranges'. I want the latter so it can pull in more related data.
I also think I may be approaching this wrong, but I don't know any other way to pull related items.
Here's my code...
<?php
            include 'data/data_connect.php';

            if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE '$keywords' LIMIT 4")) {
                if ($q_count = $sugg_qs->num_rows) {
                    echo $q_count;
                        while($row = $sugg_qs->fetch_assoc()) {
                            echo $row->title;
                        }
                            $sugg_qs->free();
                        } else {
                            die('error');
                        }
                } else {
                    die('error');
            }
        ?>

UPDATE
if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE CONCAT('%', '$keywords' ,'%') LIMIT 3")) {
                if ($q_count = $sugg_qs->num_rows) {
                    $row = $sugg_qs->fetch_all(MYSQLI_ASSOC);
                    foreach ($row as $rows) {
                        echo $rows['title'];
                    }
                } else {
                    die('error');
            }

This code does work with id's that only have one keyword. So I guess a possible (but undesired) solution would be to create a new column for each new keyword and use LIKE for each keyword.
Is there a way to avoid creating more columns?
THANKS for those who helped already :)

FINAL UPDATE?
Ok. So I figured it out in probably the messiest way to write code, but apparently it works for me. So first of all I standardized my table where each element is limited to only 5 keywords and 1 category. So in the query I call for items with similar keywords, and if there aren't similar results I then call for items from the same category from the original item.
Here is the (messy) code for those looking for a solution!
$q_kw_arr = explode(' ', $keywords);

            if ($sugg_qs = $db->query("SELECT keywords, category, title FROM questions WHERE keywords LIKE CONCAT('%', '$q_kw_arr[0]' ,'%') OR CONCAT('%', '$q_kw_arr[1]' ,'%') OR CONCAT('%', '$q_kw_arr[2]' ,'%') OR CONCAT('%', '$q_kw_arr[3]' ,'%') OR CONCAT('%', '$q_kw_arr[4]' ,'%') OR category= '$category' LIMIT 4")) {
                if ($q_count = $sugg_qs->num_rows) {
                    $row = $sugg_qs->fetch_all(MYSQLI_ASSOC);
                    foreach ($row as $rows) {
                        echo $rows['title'];
                    }
                } else {
                    echo 'error';
                    }
            }

SPECIAL THANKS TO..
Terminus, Grzegorz J, and infidelsawyer

A: You might need some checking if there are any keywords in the $keywords variable but here is a solution that works with your current structure.
Presuming each keyword in the string is separated by a space:
$keywordSeparator = " ";
$keywords = explode($keywordSeparator, $keywords);
$keywordsWhere = " WHERE keywords LIKE '%" . implode("%' OR keywords LIKE '%", $keywords) . "%'";

$query = "SELECT *
FROM questions
" . $keywordsWhere;

if ($sugg_qs = $db->query($query)) {

Edit
Paul Spiegel made some good comments (not just pointing out the error in my code:)
If you want to avoid partial matches on keywords then you should wrap all keywords in a separator.
So to avoid apple matching appliepie you would store the keyword with spaces around the keyword. So apple oranges becomes apple oranges. A search for those keywords would be WHERE keywords LIKE '% apple %' OR keywords LIKE '% oranges %'.
However, at that point, you should see performance improvements if you store the keywords in there own table, one keyword per row. A sample table structure for a modified questions table and the new question_keywords table below:
--
-- Table structure for table `questions`
--
CREATE TABLE IF NOT EXISTS `questions` (
`question_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(254) NOT NULL,
  PRIMARY KEY (`question_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

--
-- Table structure for table `question_keywords`
--
CREATE TABLE IF NOT EXISTS `question_keywords` (
`keyword_id` int(11) NOT NULL AUTO_INCREMENT,
  `question_id` int(11) NOT NULL,
  `keyword` varchar(50) NOT NULL,
  PRIMARY KEY (`keyword_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Indexes for table `question_keywords`
--
ALTER TABLE `question_keywords`
 ADD KEY `question_id_keyword` (`question_id`,`keyword`);

Some sample data
INSERT INTO `questions` (`title`) VALUES ('Question #1'), ('Question #2'), ('Question #3');

INSERT INTO `question_keywords` (`question_id`, `keyword`)
VALUES
    (1, 'apple')
    ,(2, 'orange')
    ,(3, 'ILikeFruit')
    ,(3, 'banana')
    ,(3, 'grape')
    ,(3, 'apple');

You can then search like this
$keywordSeparator = " ";
$keywords = explode($keywordSeparator, $keywords);
$keywordsAnd = "'" . implode("','", $keywords) . "'";

$query = "
  SELECT DISTINCT q.*
  FROM questions q
  INNER JOIN question_keywords k
    ON q.question_id = k.question_id
    AND k.keyword IN (" . $keywordsAnd . ")";

if ($sugg_qs = $db->query($query)) {

The search might seem more complicated since we now need that JOIN but it should speed up since it doesn't have to search using % and can take advantage of the index we have of the keyword column.

A: You could try:
if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE CONCAT('%', $keywords ,'%') LIMIT 4")) {


Q: Deleting the Contents of the Selected Folder with the Checkbox when the Button is Clicked? If checkbox is selected, what is the code used to delete the contents of the folder when the button is pressed? Also, if it is not selected, it should not be deleted.

private void button1_click(object sender, EventArgs e)
{
  string[] folder = Directory.GetFiles(@"D:\java\");
  foreach (string _file in folder)
  {
    File.Delete(_file);
  }
}

A: One of many ways to do achieve your objective:

*

*Make an array of checkboxes on your current form that are checked.

*Go through the array to build the folder name based on the Text.

*Delete the entire folder, then replace it with an empty one.

You may want to familiarize yourself with System.Linq extension methods like Where and Any if you haven't already.
The [Clear] button should only be enabled if something is checked.

Making an array of the checkboxes will be handy. It can be used every time you Clear. At the same time, the [Clear] button shouldn't be enabled unless one or more of the checkboxes are marked.
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();

        // Make an array of the checkboxes to use throughout the app.
        _checkboxes = Controls.OfType<CheckBox>().ToArray();

        // This provides a way to make sure the Clear button is
        // only enabled when one or more checkboxes is marked.
        foreach (CheckBox checkBox in _checkboxes)
        {
            checkBox.CheckedChanged += onAnyCheckboxChanged;
        }

        // Attach the 'Click' handler to the button if you
        // haven't already done this in the form Designer.
        buttonClear.Enabled = false;
        buttonClear.Click += onClickClear;
    }
    const string basePath = @"D:\java\";
    CheckBox[] _checkboxes;
    .
    .
    .
}

Set the Clear button Enabled (or not)
Here we respond to changes in the checkbox state.
private void onAnyCheckboxChanged(object sender, EventArgs e)
{
    buttonClear.Enabled = _checkboxes.Any(_=>_.Checked);
}

Exec Clear
Build a subfolder path using the Text of the checkboxes. If the checkbox is selected, delete the entire folder, replacing it with a new, empty one.
private void onClickClear(object sender, EventArgs e)
{
    // Get the checkboxes that are selected.
    CheckBox[] selectedCheckBoxes =
        _checkboxes.Where(_ => _.Checked).ToArray();
    foreach (CheckBox checkBox in selectedCheckBoxes)
    {
        // Build the folder path
        string folderPath = Path.Combine(basePath, checkBox.Text);
        // Can't delete if it doesn't exist.
        if (Directory.Exists(folderPath))
        {
            // Delete the directory and all its files and subfolders.
            Directory.Delete(path: folderPath, recursive: true);
        }
        // Replace deleted folder with new, empty one.
        Directory.CreateDirectory(path: folderPath);
    }
}

A: I understand, you have this structure
D
|-java
    |-Document
    |-Person
    |-Picture

And you said "delete the contents of the folder". So, I assume you need to keep folders
In this case
public void EmptyFolder(string root, IEnumerable<string> subfolders)
{
    foreach(string folder in subfolders)
    {
        string dirPath = Path.Combine(root, folder);

        foreach (string subdir in Directory.EnumerateDirectories(dirPath))
            Directory.Delete(subdir, true);

        foreach (string file in Directory.EnumerateFiles(dirPath))
            File.Delete(file);
    }
}

// (assuming check box text is the name of folder. Or you can use tag property to set real folder name there)
private IEnumerable<string> Getfolders()
{
    foreach(control c in this.Controls) // "this" being a form or control, or use specificControl.Controls
    {
        if (c is Checkbox check && check.Checked)
            yield return check.Text;

    }
}

// USAGE

EmptyFolder(@"D:\java\", Getfolders());

NOTE: written from memory and not tested


Q: Declaring RequireJS dependencies with TypeScript I am using TypeScript with RequireJS. As you can see in the following image, I define some imports using the RequireJS config; of course these imports are sourced via <script> tags:

TypeScript cannot see those declarations, so I was thinking of just declaring them as globals or something, to avoid transpilation errors.
What might be the best thing to do in this situation? Everything seems to run fine, but I do get more compilation errors and of course red syntax highlighting everywhere.
In the first image we see that requirejs is not recognized, also in the below image we see that TypeScript doesn't know what 'redux' is, (but it's in the RequireJS config).

So what I would like to do is tell TypeScript about the following dependencies: requirejs, redux, react, rxjs, socketio, etc

A: So part of the problem was I needed to run:
npm install -D @types/requirejs
npm install -D @types/redux

and then in my tsconfig.json, add:
  "types": [
      "node",
      "lodash",
      "react",
      "react-dom",
      "redux",
      "react-redux",
      "async",
      "requirejs"
    ],
    "typeRoots": [
      "node_modules/@types"
    ],

but also, to address the problem of TypeScript not understand where <script> tag dependencies come from in the front-end, it looks like we can do something like this:
https://weblog.west-wind.com/posts/2016/Sep/12/External-JavaScript-dependencies-in-Typescript-and-Angular-2

De-referencing Globals In order to keep the Typescript compiler happy
  and not end up with compilation errors, or have a boat load of type
  imports you may only use once or twice, it's sometimes easier to
  simply manage the external libraries yourself. Import it using a
  regular script tag, or packaged as part of a separate vendor bundle
  and then simply referenced in the main page.
So rather than using import to pull in the library, we can just import
  using  tag as in the past:
Then in any Typescript class/component where you want to use these
  libraries explicitly dereference each of the library globals by
  explicitly using declare and casting them to any:

declare var redux:any;
declare var socketio: any;


Q: Can Dart or Flutter unit tests be automatically repeated? When unit testing with Dart or Flutter
If there are 100 unit tests, if you run the flutter test command, 100 test codes will be tested once.
But I want to repeat this N times.
Is there a command or way to automatically start the test again after one full test and report if the test is broken?

A: I'm not sure why this would be necessary, but I suppose you could wrap the tests you want to repeat in a for loop from 0 to N.
If you define N using int.fromEnvironment then you can pass in a value for N at the command line.
flutter test --dart-define=N=100
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:example/main.dart';

const N = int.fromEnvironment('N', defaultValue: 1);

void main() {
  for (int i = 0; i < N; i++) {
    testWidgets('Counter increments smoke test $i',
        (WidgetTester tester) async {
      // Build our app and trigger a frame.
      await tester.pumpWidget(const MyApp());

      // Verify that our counter starts at 0.
      expect(find.text('0'), findsOneWidget);
      expect(find.text('1'), findsNothing);

      // Tap the '+' icon and trigger a frame.
      await tester.tap(find.byIcon(Icons.add));
      await tester.pump();

      // Verify that our counter has incremented.
      expect(find.text('0'), findsNothing);
      expect(find.text('1'), findsOneWidget);
    });
  }
}

Alternatively you could write a program that runs flutter test N times.


Q: configure NodeJS process on two different machine I have two different nodejs web app running on two different machine.
But I need to have one endpoint to user api1.abc.com/v1 to go one process and api2.abc.com/v2 go to another process.
how can i do this kind of request with the single endpoint to user (abc.com). need a nginx setup guide ?
I need this setup because internally I need to call user authenticated api from one server to another.

A: On one server you need to receive the data (using express & router):
router.get('/v1', function(req, res) {
  // TODO
  res.render('something');
});

and on the other you need to fetch:
var express = require('express');
var router = express.Router();

var app = express()

app.use('api1.abc.com', router);

router.post('/v1', function(req, res) {
  // process res
});

A: You can write code at version two apis. In request you can pass version on which you need to call.
Call all api's on version 2. If it required to call on second server. Write code on version one to identify the call from version 2. So that it can by pass the basic authentication.
Thanks,


Q: Power BI duration filter for hours minutes and seconds I have data in following format define as Time (hh:mm:ss) in Modeling tab:

When I try to turn on filter (Power BI filter or in filter in Visuals) all I can do is filter to day granularity.
I tried some of the custom filters but none of them is working.
How can I filter based on hh/mm/ss?

A: Acepted answer is data warehouse aproach with creation of separate tables and relations to time table. That's bit too long for me.
But if you can do it easily like this:
Calculate duration using DATEDIFF formula:
time_in_sec= DATEDIFF([time_end];[time_start];SECOND)

Than you can use that to calculate your 3 custom columns for hours, minutes and seconds using this:
For hours:
duration_hh = if([time_in_sec]>0;FLOOR( [time_in_sec] / 3600; 1);0)

For minutes:
duration_mm = if([time_in_sec]>0;FLOOR( MOD( [hpm_trajanje_poziva_sec]; 3600) / 60; 1);0)

For seconds:
hpm_trajanje_poziva_ss = if([hpm_trajanje_poziva_sec]>0; FLOOR( MOD ( MOD( [hpm_trajanje_poziva_sec]; 3600) ;60 ); 1) ;0)

Than you can use those 3 calculated columns to filter your data in visuals.

A: The best approach would be to create a new time dimension, link it to your time fields and then use that to apply the filter rather than filtering those fields directly.
Here's a helpful guide giving a couple of was to apply this.


Q: Java application using Maven Build My project team is using maven build.  We have a package name as **/**/**/RCS under which all the classes are getting generated.  But the jar does not contain these classes for some reason.  Is there a way to include these classes into the RCS.jar?
We are using maven build to compile all the modules in the application.  There is no problem with other packages having a similar format.
Please suggest where the issue can be.
Thanks in advance!!!
This is the pom.xml for the package. Have removed certain dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>

<groupId>XX.4-1.Components.Oracle</groupId>
<artifactId>RCS</artifactId>
<version>4.1</version>
<packaging>jar</packaging>
<name>RCS</name>
<url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <archDeliveryPath>/home/user/BuildWorkspace/Product_Deployment/Dependent_Jars</archDeliveryPath>
  </properties>

<dependencies><dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>Oracle</groupId>
<artifactId>ojdbc5</artifactId>
<version>1.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>*</groupId>
 <artifactId>*</artifactId>
</exclusion>
 </exclusions>
</dependency>
<dependency>
<groupId>Oracle</groupId>
<artifactId>j2ee</artifactId>
<version>1.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>*</groupId>
 <artifactId>*</artifactId>
</exclusion>
 </exclusions>
</dependency>
<dependency>
<groupId>Oracle</groupId>
<artifactId>ErrorMessages</artifactId>
<version>1.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>*</groupId>
 <artifactId>*</artifactId>
</exclusion>
 </exclusions>
</dependency>
<dependency>
<groupId>ThirdpartyLicensedDependencyPOM</groupId>
<artifactId>License-Base</artifactId>
<version>1.0</version>
<type>pom</type>
</dependency>
<dependency><groupId>com.sum</groupId><artifactId>rt</artifactId><version>0.1</version><scope>system</scope><systemPath>${java.home}/lib/rt.jar</systemPath></dependency>
<dependency><groupId>com.sun</groupId><artifactId>tools</artifactId><version>0.1</version><scope>system</scope><systemPath>${java.home}/../lib/tools.jar</systemPath></dependency>
<dependency>
<groupId>XX.4-1.Components.Oracle</groupId>
<artifactId>XX</artifactId>
<version>(,4.1]</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>XX.4-1.Components.Oracle</groupId>
<artifactId>XX</artifactId>
<version>(,4.1]</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>ARCHPOM</groupId>
<artifactId>XX</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${archDeliveryPath}/XX.jar</systemPath>
</dependency>
<dependency>
<groupId>ARCHPOM</groupId>
<artifactId>CommonFunctionality</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${archDeliveryPath}/CommonFunctionality.jar</systemPath>
</dependency>

</dependencies>
<repositories>
<repository>
<id>id1</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
<repository>
<id>Artifactory</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
<repository>
<id>Artifactory</id>
<name>Artifactory-releases</name>
<url>http://URL</url>
</repository>
<repository>
<id>Licensed Artifactory</id>
<name>Artifactory-releases</name>
<url>http://URL</url>
</repository>
<repository>
<id>id4</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
<repository>
<id>id3</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>id2</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
</distributionManagement>

</project>

A: the problem is resolved. Changed the default excludes in plexus-utils-2.0.5.jar/org/codehaus/plexus/util/AbstractScanner.java which was excluding **/RCS & **/RCS/**. Commented the RCS line and voila, it worked.

A: Try adding this to your pom.xml
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <includes>
                    <include>**/RCS/*</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>


Q: Spring : Singleton VS Prototype i'm new to Spring starting to learn new concepts , and i found topic speaking about bean Scopes :
 - Singleton : returns the same instance every time.
 - Prototype : returns new instance of the object per every request.
my question is : how is this helpful for me what is the difference between the same instance , and new instance of the object , or why the prototype scope exists !

A: Same instance would mean any call (from anywhere) to getBean() from ApplicationContext or BeanFactory will land you with the same instance, i.e. constructor is called just once when Spring is being initialized (per Spring container).
However, there are scenarios when you would want different object instances to work with.
For example, if you have a Point object as a member variable in a Triangle class, in case of Singleton, when the Triangle class is being instantiated, the Point object also is instantiated as it is dependent.
If you require a different instance of Point to work with elsewhere, then you will need to define the Point as a prototype, else it carries the same state.
Googling would surely help you find answers and examples demonstrating the use case.
Hope this helps.

A: In case if the same instance is injected everywhere as Singleton, you can use it's shared state for containing any kind of data. In case if new instance is created any time bean is being injected - it's state is not shared. By default all beans are Singletons. Prototype scope stands for cases when bean's inner data should be unique for each place you inject bean into.
Example: you have the bean which represents REST client. Different parts of application use different REST services, each requires some specific request headers - for security purposes, for example. You can inject the same REST client in all these beans to have it's own REST client bean with some specific headers. At the same time you can configure client's politics in common for the whole application - request timeouts, etc.
See also: When to use Spring prototype scope?

A: It helps in designing a software, refer java design patterns you fill find much useful information, In case of singleton you will be able to create only object, it will helps cases like  1.saving time in creating a very complex object (we can reuse the same object) 2.Some times we need to use the same object throughout the application E.g if you want count the total number of active users in the application, you can use singleton object to store it, because there will be only one object so you can easily update and retrieve data.  In case of Prototype it will always give you different object, it is necessary in some cases like some access token, you should always get the new /valid token to proceed further, so prototype pattern /Bean is useful.

A: My understanding for Singleton is more likely used in the situation like return single Utility instance.
//SomeUtil is Singleton
var util = SomeUtil.getInstance();
print(util.doTask1());
print(util.doTask2());

If another thread goes into these code, SomeUtil.getInstance() just return the SomeUtil instance other than creating a new one (which might cost much to create a new one).
As to Prototype, I just found this situation using Prototype:

Lets understand this pattern using an example. I am creating an entertainment application that will require instances of Movie,
  Album and Show classes very frequently. I do not want to create their instances everytime as it is costly.
  So, I will create their prototype instances, and everytime when i will need a new instance,
  I will just clone the prototype.

Example code locates https://github.com/keenkit/DesignPattern/tree/master/src/PrototypePattern


Q: XLRD cannot read multiindex column name I have a problem with multiindex column name. I'm using XLRD to convert excel data to json using json.dumps but instead it gives me only one row of column name only. I have read about multilevel json but i have no idea how to do it using XLRD.
Here is my sample of table column name
Sample of code:
for i in path:
with xlrd.open_workbook(i) as wb:
    print([i])
    kwd = 'sage'
    print(wb.sheet_names())
    for j in range(wb.nsheets):
        worksheet = wb.sheet_by_index(j)
        data = []
        n = 0
        nn = 0
        keyword = 'sage'
        keyword2 = 'adm'
        try:
            skip = skip_row(worksheet, n, keyword)
            keys = [v.value for v in worksheet.row(skip)]
        except:
            try:
                skip = skip_row2(worksheet, nn, keyword2)
                keys = [v.value for v in worksheet.row(skip)]
            except:
                continue
        print(keys)
        for row_number in range(check_skip(skip), worksheet.nrows):
            if row_number == 0:
                continue
            row_data = {}
            for col_number, cell in enumerate(worksheet.row(row_number)):

                row_data[keys[col_number]] = cell.value
            data.append(row_data)
        print(json.dumps({'Data': data}))

ouh by the way, each worksheet have different number to skip before column name so that's why my code got function of skip row. After I skip the row and found the exact location of my column name. Then i start to read the values. But it yah there is where the problem raise from my view because i got two rows of column name. And still confuse how to do multi level json with XLRD or at least join the column name with XLRD (which i guess can't).
Desired outcome multilevel json:
{ "Data":[{ "ID" : "997", "Tax" : [{"Date" : "9/7/2019", "Total" : 2300, "Grand Total" : 340000"}], "Tax ID" : "ST-000", .... }]}

pss:// I've tried to use pandas but it gives me a lot of trouble since i work with big data.

A: You can use  multi indexing in panda, first you need to get header row index for each sheet.
header_indexes = get_header_indexes(excel_filepath, sheet_index) #returns list of header indexes

You need to write get_header_indexes function which scans sheet and return header indexes.
you can use panda to get JSON from dataframe.
import pandas as pd
df = pd.read_excel(excel_filepath, header=header_indexes, sheet_name=sheet_index)
data = df.to_dict(orient="records")

for multiple headers data containts list of dict and each dict has tuple as key, you can reformat it to final JSON as per your requirement.
Note: Use chunksize for reading large files.